@gymmymac/bob-widget 3.2.20 → 3.2.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/components/ProductTile.d.ts +0 -8
- package/dist/components/mobile/ContainedMobileBobLayout.d.ts +1 -1
- package/dist/components/mobile/MobileBobLayout.d.ts +1 -1
- package/dist/components/mobile/MobileBobLayoutCore.d.ts +2 -15
- package/dist/components/mobile/MobileProductColumn.d.ts +5 -41
- package/dist/components/mobile/index.d.ts +2 -1
- package/dist/components/shelf/HorizontalRow.d.ts +19 -0
- package/dist/components/shelf/PartslotSection.d.ts +16 -0
- package/dist/components/shelf/ServicePackageCard.d.ts +11 -0
- package/dist/components/shelf/ShelfColumn.d.ts +40 -0
- package/dist/components/shelf/ShelfHeader.d.ts +9 -0
- package/dist/components/shelf/ShelfLoadingState.d.ts +7 -0
- package/dist/components/shelf/TierCard.d.ts +15 -0
- package/dist/components/shelf/TierProductList.d.ts +8 -0
- package/dist/components/shelf/VariantSelector.d.ts +11 -0
- package/dist/components/shelf/index.d.ts +10 -0
- package/dist/hooks/useBobChat.d.ts +3 -2
- package/dist/index.js +32 -31
- package/dist/index.mjs +4616 -4204
- package/dist/style.css +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var ci=t=>{throw TypeError(t)};var fn=(t,e,r)=>e.has(t)||ci("Cannot "+r);var _=(t,e,r)=>(fn(t,e,"read from private field"),r?r.call(t):e.get(t)),X=(t,e,r)=>e.has(t)?ci("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),M=(t,e,r,s)=>(fn(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),le=(t,e,r)=>(fn(t,e,"access private method"),r);var $s=(t,e,r,s)=>({set _(n){M(t,e,n,r)},get _(){return _(t,e,s)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("react");function Co(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 xt=Co(g),Vt="3.2.21",Ao=()=>Vt;var _n={exports:{}},ns={};/**
|
|
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 ui;function Oo(){if(ui)return ns;ui=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(o,c,u){var d,h={},p=null,f=null;u!==void 0&&(p=""+u),c.key!==void 0&&(p=""+c.key),c.ref!==void 0&&(f=c.ref);for(d in c)s.call(c,d)&&!i.hasOwnProperty(d)&&(h[d]=c[d]);if(o&&o.defaultProps)for(d in c=o.defaultProps,c)h[d]===void 0&&(h[d]=c[d]);return{$$typeof:e,type:o,key:p,ref:f,props:h,_owner:n.current}}return ns.Fragment=r,ns.jsx=a,ns.jsxs=a,ns}var is={};/**
|
|
10
10
|
* @license React
|
|
11
11
|
* react-jsx-runtime.development.js
|
|
12
12
|
*
|
|
@@ -14,33 +14,33 @@
|
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the MIT license found in the
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var
|
|
18
|
-
`+
|
|
19
|
-
`),
|
|
20
|
-
`),
|
|
21
|
-
`+
|
|
17
|
+
*/var di;function Po(){return di||(di=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"),o=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),y=Symbol.iterator,b="@@iterator";function m(v){if(v===null||typeof v!="object")return null;var I=y&&v[y]||v[b];return typeof I=="function"?I:null}var k=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function w(v){{for(var I=arguments.length,$=new Array(I>1?I-1:0),ee=1;ee<I;ee++)$[ee-1]=arguments[ee];S("error",v,$)}}function S(v,I,$){{var ee=k.ReactDebugCurrentFrame,he=ee.getStackAddendum();he!==""&&(I+="%s",$=$.concat([he]));var ce=$.map(function(oe){return String(oe)});ce.unshift("Warning: "+I),Function.prototype.apply.call(console[v],console,ce)}}var x=!1,A=!1,T=!1,R=!1,E=!1,O;O=Symbol.for("react.module.reference");function j(v){return!!(typeof v=="string"||typeof v=="function"||v===s||v===i||E||v===n||v===u||v===d||R||v===f||x||A||T||typeof v=="object"&&v!==null&&(v.$$typeof===p||v.$$typeof===h||v.$$typeof===a||v.$$typeof===o||v.$$typeof===c||v.$$typeof===O||v.getModuleId!==void 0))}function C(v,I,$){var ee=v.displayName;if(ee)return ee;var he=I.displayName||I.name||"";return he!==""?$+"("+he+")":$}function L(v){return v.displayName||"Context"}function P(v){if(v==null)return null;if(typeof v.tag=="number"&&w("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof v=="function")return v.displayName||v.name||null;if(typeof v=="string")return v;switch(v){case s:return"Fragment";case r:return"Portal";case i:return"Profiler";case n:return"StrictMode";case u:return"Suspense";case d:return"SuspenseList"}if(typeof v=="object")switch(v.$$typeof){case o:var I=v;return L(I)+".Consumer";case a:var $=v;return L($._context)+".Provider";case c:return C(v,v.render,"ForwardRef");case h:var ee=v.displayName||null;return ee!==null?ee:P(v.type)||"Memo";case p:{var he=v,ce=he._payload,oe=he._init;try{return P(oe(ce))}catch{return null}}}return null}var F=Object.assign,B=0,N,H,Z,W,z,fe,re;function se(){}se.__reactDisabledLog=!0;function Ee(){{if(B===0){N=console.log,H=console.info,Z=console.warn,W=console.error,z=console.group,fe=console.groupCollapsed,re=console.groupEnd;var v={configurable:!0,enumerable:!0,value:se,writable:!0};Object.defineProperties(console,{info:v,log:v,warn:v,error:v,group:v,groupCollapsed:v,groupEnd:v})}B++}}function te(){{if(B--,B===0){var v={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:F({},v,{value:N}),info:F({},v,{value:H}),warn:F({},v,{value:Z}),error:F({},v,{value:W}),group:F({},v,{value:z}),groupCollapsed:F({},v,{value:fe}),groupEnd:F({},v,{value:re})})}B<0&&w("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ge=k.ReactCurrentDispatcher,je;function U(v,I,$){{if(je===void 0)try{throw Error()}catch(he){var ee=he.stack.trim().match(/\n( *(at )?)/);je=ee&&ee[1]||""}return`
|
|
18
|
+
`+je+v}}var $e=!1,Ve;{var tt=typeof WeakMap=="function"?WeakMap:Map;Ve=new tt}function _e(v,I){if(!v||$e)return"";{var $=Ve.get(v);if($!==void 0)return $}var ee;$e=!0;var he=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var ce;ce=ge.current,ge.current=null,Ee();try{if(I){var oe=function(){throw Error()};if(Object.defineProperty(oe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(oe,[])}catch(ve){ee=ve}Reflect.construct(v,[],oe)}else{try{oe.call()}catch(ve){ee=ve}v.call(oe.prototype)}}else{try{throw Error()}catch(ve){ee=ve}v()}}catch(ve){if(ve&&ee&&typeof ve.stack=="string"){for(var ne=ve.stack.split(`
|
|
19
|
+
`),Ne=ee.stack.split(`
|
|
20
|
+
`),Te=ne.length-1,Ce=Ne.length-1;Te>=1&&Ce>=0&&ne[Te]!==Ne[Ce];)Ce--;for(;Te>=1&&Ce>=0;Te--,Ce--)if(ne[Te]!==Ne[Ce]){if(Te!==1||Ce!==1)do if(Te--,Ce--,Ce<0||ne[Te]!==Ne[Ce]){var Re=`
|
|
21
|
+
`+ne[Te].replace(" at new "," at ");return v.displayName&&Re.includes("<anonymous>")&&(Re=Re.replace("<anonymous>",v.displayName)),typeof v=="function"&&Ve.set(v,Re),Re}while(Te>=1&&Ce>=0);break}}}finally{$e=!1,ge.current=ce,te(),Error.prepareStackTrace=he}var yt=v?v.displayName||v.name:"",dt=yt?U(yt):"";return typeof v=="function"&&Ve.set(v,dt),dt}function De(v,I,$){return _e(v,!1)}function ct(v){var I=v.prototype;return!!(I&&I.isReactComponent)}function rt(v,I,$){if(v==null)return"";if(typeof v=="function")return _e(v,ct(v));if(typeof v=="string")return U(v);switch(v){case u:return U("Suspense");case d:return U("SuspenseList")}if(typeof v=="object")switch(v.$$typeof){case c:return De(v.render);case h:return rt(v.type,I,$);case p:{var ee=v,he=ee._payload,ce=ee._init;try{return rt(ce(he),I,$)}catch{}}}return""}var Be=Object.prototype.hasOwnProperty,gt={},ur=k.ReactDebugCurrentFrame;function st(v){if(v){var I=v._owner,$=rt(v.type,v._source,I?I.type:null);ur.setExtraStackFrame($)}else ur.setExtraStackFrame(null)}function qe(v,I,$,ee,he){{var ce=Function.call.bind(Be);for(var oe in v)if(ce(v,oe)){var ne=void 0;try{if(typeof v[oe]!="function"){var Ne=Error((ee||"React class")+": "+$+" type `"+oe+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof v[oe]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Ne.name="Invariant Violation",Ne}ne=v[oe](I,oe,ee,$,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Te){ne=Te}ne&&!(ne instanceof Error)&&(st(he),w("%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).",ee||"React class",$,oe,typeof ne),st(null)),ne instanceof Error&&!(ne.message in gt)&&(gt[ne.message]=!0,st(he),w("Failed %s type: %s",$,ne.message),st(null))}}}var V=Array.isArray;function ie(v){return V(v)}function ke(v){{var I=typeof Symbol=="function"&&Symbol.toStringTag,$=I&&v[Symbol.toStringTag]||v.constructor.name||"Object";return $}}function Q(v){try{return me(v),!1}catch{return!0}}function me(v){return""+v}function ye(v){if(Q(v))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ke(v)),me(v)}var Qe=k.ReactCurrentOwner,Ue={key:!0,ref:!0,__self:!0,__source:!0},Dt,Ie;function Is(v){if(Be.call(v,"ref")){var I=Object.getOwnPropertyDescriptor(v,"ref").get;if(I&&I.isReactWarning)return!1}return v.ref!==void 0}function Ns(v){if(Be.call(v,"key")){var I=Object.getOwnPropertyDescriptor(v,"key").get;if(I&&I.isReactWarning)return!1}return v.key!==void 0}function Fs(v,I){typeof v.ref=="string"&&Qe.current}function Bs(v,I){{var $=function(){Dt||(Dt=!0,w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",I))};$.isReactWarning=!0,Object.defineProperty(v,"key",{get:$,configurable:!0})}}function Ls(v,I){{var $=function(){Ie||(Ie=!0,w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",I))};$.isReactWarning=!0,Object.defineProperty(v,"ref",{get:$,configurable:!0})}}var K=function(v,I,$,ee,he,ce,oe){var ne={$$typeof:e,type:v,key:I,ref:$,props:oe,_owner:ce};return ne._store={},Object.defineProperty(ne._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(ne,"_self",{configurable:!1,enumerable:!1,writable:!1,value:ee}),Object.defineProperty(ne,"_source",{configurable:!1,enumerable:!1,writable:!1,value:he}),Object.freeze&&(Object.freeze(ne.props),Object.freeze(ne)),ne};function de(v,I,$,ee,he){{var ce,oe={},ne=null,Ne=null;$!==void 0&&(ye($),ne=""+$),Ns(I)&&(ye(I.key),ne=""+I.key),Is(I)&&(Ne=I.ref,Fs(I,he));for(ce in I)Be.call(I,ce)&&!Ue.hasOwnProperty(ce)&&(oe[ce]=I[ce]);if(v&&v.defaultProps){var Te=v.defaultProps;for(ce in Te)oe[ce]===void 0&&(oe[ce]=Te[ce])}if(ne||Ne){var Ce=typeof v=="function"?v.displayName||v.name||"Unknown":v;ne&&Bs(oe,Ce),Ne&&Ls(oe,Ce)}return K(v,ne,Ne,he,ee,Qe.current,oe)}}var ae=k.ReactCurrentOwner,Le=k.ReactDebugCurrentFrame;function Ye(v){if(v){var I=v._owner,$=rt(v.type,v._source,I?I.type:null);Le.setExtraStackFrame($)}else Le.setExtraStackFrame(null)}var Ct;Ct=!1;function bt(v){return typeof v=="object"&&v!==null&&v.$$typeof===e}function _t(){{if(ae.current){var v=P(ae.current.type);if(v)return`
|
|
22
22
|
|
|
23
|
-
Check the render method of \``+
|
|
23
|
+
Check the render method of \``+v+"`."}return""}}function ut(v){return""}var At={};function Ut(v){{var I=_t();if(!I){var $=typeof v=="string"?v:v.displayName||v.name;$&&(I=`
|
|
24
24
|
|
|
25
|
-
Check the top-level render call using
|
|
25
|
+
Check the top-level render call using <`+$+">.")}return I}}function Me(v,I){{if(!v._store||v._store.validated||v.key!=null)return;v._store.validated=!0;var $=Ut(I);if(At[$])return;At[$]=!0;var ee="";v&&v._owner&&v._owner!==ae.current&&(ee=" It was passed a child from "+P(v._owner.type)+"."),Ye(v),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',$,ee),Ye(null)}}function Mt(v,I){{if(typeof v!="object")return;if(ie(v))for(var $=0;$<v.length;$++){var ee=v[$];bt(ee)&&Me(ee,I)}else if(bt(v))v._store&&(v._store.validated=!0);else if(v){var he=m(v);if(typeof he=="function"&&he!==v.entries)for(var ce=he.call(v),oe;!(oe=ce.next()).done;)bt(oe.value)&&Me(oe.value,I)}}}function Qt(v){{var I=v.type;if(I==null||typeof I=="string")return;var $;if(typeof I=="function")$=I.propTypes;else if(typeof I=="object"&&(I.$$typeof===c||I.$$typeof===h))$=I.propTypes;else return;if($){var ee=P(I);qe($,v.props,"prop",ee,v)}else if(I.PropTypes!==void 0&&!Ct){Ct=!0;var he=P(I);w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",he||"Unknown")}typeof I.getDefaultProps=="function"&&!I.getDefaultProps.isReactClassApproved&&w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function nt(v){{for(var I=Object.keys(v.props),$=0;$<I.length;$++){var ee=I[$];if(ee!=="children"&&ee!=="key"){Ye(v),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",ee),Ye(null);break}}v.ref!==null&&(Ye(v),w("Invalid attribute `ref` supplied to `React.Fragment`."),Ye(null))}}var Xe={};function Ot(v,I,$,ee,he,ce){{var oe=j(v);if(!oe){var ne="";(v===void 0||typeof v=="object"&&v!==null&&Object.keys(v).length===0)&&(ne+=" 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 Ne=ut();Ne?ne+=Ne:ne+=_t();var Te;v===null?Te="null":ie(v)?Te="array":v!==void 0&&v.$$typeof===e?(Te="<"+(P(v.type)||"Unknown")+" />",ne=" Did you accidentally export a JSX literal instead of a component?"):Te=typeof v,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Te,ne)}var Ce=de(v,I,$,he,ce);if(Ce==null)return Ce;if(oe){var Re=I.children;if(Re!==void 0)if(ee)if(ie(Re)){for(var yt=0;yt<Re.length;yt++)Mt(Re[yt],v);Object.freeze&&Object.freeze(Re)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Mt(Re,v)}if(Be.call(I,"key")){var dt=P(v),ve=Object.keys(I).filter(function(Yt){return Yt!=="key"}),kt=ve.length>0?"{key: someKey, "+ve.join(": ..., ")+": ...}":"{key: someKey}";if(!Xe[dt+kt]){var D=ve.length>0?"{"+ve.join(": ..., ")+": ...}":"{}";w(`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} />`,kt,dt,D,dt),Xe[dt+kt]=!0}}return v===s?nt(Ce):Qt(Ce),Ce}}function Ze(v,I,$){return Ot(v,I,$,!0)}function mt(v,I,$){return Ot(v,I,$,!1)}var dr=mt,Ge=Ze;is.Fragment=s,is.jsx=dr,is.jsxs=Ge}()),is}process.env.NODE_ENV==="production"?_n.exports=Oo():_n.exports=Po();var l=_n.exports;function rn(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function Io(t,e,r,s){function n(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function o(d){try{u(s.next(d))}catch(h){a(h)}}function c(d){try{u(s.throw(d))}catch(h){a(h)}}function u(d){d.done?i(d.value):n(d.value).then(o,c)}u((s=s.apply(t,e||[])).next())})}const No=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Xn extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}}class Fo extends Xn{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class hi extends Xn{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class fi extends Xn{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var kn;(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"})(kn||(kn={}));class Bo{constructor(e,{headers:r={},customFetch:s,region:n=kn.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=No(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Io(this,arguments,void 0,function*(r,s={}){var n;let i,a;try{const{headers:o,method:c,body:u,signal:d,timeout:h}=s;let p={},{region:f}=s;f||(f=this.region);const y=new URL(`${this.url}/${r}`);f&&f!=="any"&&(p["x-region"]=f,y.searchParams.set("forceFunctionRegion",f));let b;u&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",b=u):typeof u=="string"?(p["Content-Type"]="text/plain",b=u):typeof FormData<"u"&&u instanceof FormData?b=u:(p["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 k=yield this.fetch(y.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),o),body:b,signal:m}).catch(A=>{throw new Fo(A)}),w=k.headers.get("x-relay-error");if(w&&w==="true")throw new hi(k);if(!k.ok)throw new fi(k);let S=((n=k.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),x;return S==="application/json"?x=yield k.json():S==="application/octet-stream"||S==="application/pdf"?x=yield k.blob():S==="text/event-stream"?x=k:S==="multipart/form-data"?x=yield k.formData():x=yield k.text(),{data:x,error:null,response:k}}catch(o){return{data:null,error:o,response:o instanceof fi||o instanceof hi?o.context:void 0}}finally{i&&clearTimeout(i)}})}}var Lo=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},$o=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const s=this.fetch;let n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let a=null,o=null,c=null,u=i.status,d=i.statusText;if(i.ok){var h,p;if(r.method!=="HEAD"){var f;const m=await i.text();m===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?o=m:o=JSON.parse(m))}const y=(h=r.headers.get("Prefer"))===null||h===void 0?void 0:h.match(/count=(exact|planned|estimated)/),b=(p=i.headers.get("content-range"))===null||p===void 0?void 0:p.split("/");y&&b&&b.length>1&&(c=parseInt(b[1])),r.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,u=406,d="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{const y=await i.text();try{a=JSON.parse(y),Array.isArray(a)&&i.status===404&&(o=[],a=null,u=200,d="OK")}catch{i.status===404&&y===""?(u=204,d="No Content"):a={message:y}}if(a&&r.shouldThrowOnError)throw new Lo(a)}return{error:a,data:o,count:c,status:u,statusText:d}});return this.shouldThrowOnError||(n=n.catch(i=>{var a;let o="",c="",u="";const d=i==null?void 0:i.cause;if(d){var h,p,f,y;const k=(h=d==null?void 0:d.message)!==null&&h!==void 0?h:"",w=(p=d==null?void 0:d.code)!==null&&p!==void 0?p:"";o=`${(f=i==null?void 0:i.name)!==null&&f!==void 0?f:"FetchError"}: ${i==null?void 0:i.message}`,o+=`
|
|
31
31
|
|
|
32
|
-
Caused by: ${(y=d==null?void 0:d.name)!==null&&y!==void 0?y:"Error"}: ${k}`,
|
|
33
|
-
${d.stack}`)}else{var m;o=(m=i==null?void 0:i.stack)!==null&&m!==void 0?m:""}const _=this.url.toString().length;return(i==null?void 0:i.name)==="AbortError"||(i==null?void 0:i.code)==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",_>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${_} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((d==null?void 0:d.name)==="HeadersOverflowError"||(d==null?void 0:d.code)==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",_>this.urlLengthLimit&&(c+=`. Your request URL is ${_} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(a=i==null?void 0:i.name)!==null&&a!==void 0?a:"FetchError"}: ${i==null?void 0:i.message}`,details:o,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},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.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var a;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const ui=new RegExp("[,()]");var Fr=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"&&ui.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"&&ui.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");const i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Po=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET";let i=!1;const a=(t??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",a),s&&c.append("Prefer",`count=${s}`),new Fr({method:n,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:i,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),r||a.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(o.length>0){const c=[...new Set(o)].map(u=>`"${u}"`);i.searchParams.set("columns",c.join(","))}}return new Fr({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const a="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),n||c.append("Prefer","missing=default"),Array.isArray(t)){const u=t.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(u.length>0){const d=[...new Set(u)].map(h=>`"${h}"`);o.searchParams.set("columns",d.join(","))}}return new Fr({method:a,url:o,headers:c,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Fr({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 Fr({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function fs(t){"@babel/helpers - typeof";return fs=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},fs(t)}function No(t,e){if(fs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(fs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Io(t){var e=No(t,"string");return fs(e)=="symbol"?e:e+""}function Bo(t,e,r){return(e=Io(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function di(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 Fs(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?di(Object(r),!0).forEach(function(s){Bo(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):di(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Fo=class ca{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:a=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=a;const o=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,u)=>{const d=new AbortController,h=setTimeout(()=>d.abort(),i),g=u==null?void 0:u.signal;if(g){if(g.aborted)return clearTimeout(h),o(c,u);const f=()=>{clearTimeout(h),d.abort()};return g.addEventListener("abort",f,{once:!0}),o(c,Fs(Fs({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(h),g.removeEventListener("abort",f)})}return o(c,Fs(Fs({},u),{},{signal:d.signal})).finally(()=>clearTimeout(h))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Po(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new ca(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var a;let o;const c=new URL(`${this.url}/rpc/${e}`);let u;const d=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(d)),h=s&&Object.values(r).some(d);h?(o="POST",u=r):s||n?(o=s?"HEAD":"GET",Object.entries(r).filter(([f,y])=>y!==void 0).map(([f,y])=>[f,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([f,y])=>{c.searchParams.append(f,y)})):(o="POST",u=r);const g=new Headers(this.headers);return h?g.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&g.set("Prefer",`count=${i}`),new Fr({method:o,url:c,headers:g,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};class Lo{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"}: ${k}`,w&&(o+=` (${w})`),d!=null&&d.stack&&(o+=`
|
|
33
|
+
${d.stack}`)}else{var b;o=(b=i==null?void 0:i.stack)!==null&&b!==void 0?b:""}const 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:o,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},Do=class extends $o{select(t){let e=!1;const r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var a;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const pi=new RegExp("[,()]");var $r=class extends Do{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"&&pi.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"&&pi.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");const i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},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:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",a),s&&c.append("Prefer",`count=${s}`),new $r({method:n,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:i,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),r||a.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(o.length>0){const c=[...new Set(o)].map(u=>`"${u}"`);i.searchParams.set("columns",c.join(","))}}return new $r({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const a="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),n||c.append("Prefer","missing=default"),Array.isArray(t)){const u=t.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(u.length>0){const d=[...new Set(u)].map(h=>`"${h}"`);o.searchParams.set("columns",d.join(","))}}return new $r({method:a,url:o,headers:c,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new $r({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 $r({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function gs(t){"@babel/helpers - typeof";return gs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gs(t)}function Mo(t,e){if(gs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(gs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Wo(t){var e=Mo(t,"string");return gs(e)=="symbol"?e:e+""}function qo(t,e,r){return(e=Wo(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function gi(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function Ds(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?gi(Object(r),!0).forEach(function(s){qo(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):gi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var zo=class fa{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:a=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=a;const o=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,u)=>{const d=new AbortController,h=setTimeout(()=>d.abort(),i),p=u==null?void 0:u.signal;if(p){if(p.aborted)return clearTimeout(h),o(c,u);const f=()=>{clearTimeout(h),d.abort()};return p.addEventListener("abort",f,{once:!0}),o(c,Ds(Ds({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(h),p.removeEventListener("abort",f)})}return o(c,Ds(Ds({},u),{},{signal:d.signal})).finally(()=>clearTimeout(h))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Uo(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new fa(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var a;let o;const c=new URL(`${this.url}/rpc/${e}`);let u;const d=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(d)),h=s&&Object.values(r).some(d);h?(o="POST",u=r):s||n?(o=s?"HEAD":"GET",Object.entries(r).filter(([f,y])=>y!==void 0).map(([f,y])=>[f,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([f,y])=>{c.searchParams.append(f,y)})):(o="POST",u=r);const p=new Headers(this.headers);return h?p.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&p.set("Prefer",`count=${i}`),new $r({method:o,url:c,headers:p,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};class Ho{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 isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const $o="2.101.0",Do=`realtime-js/${$o}`,Uo="1.0.0",ua="2.0.0",Mo=ua,Wo=1e4,qo=100,zt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},da={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},wn={connecting:"connecting",closing:"closing",closed:"closed"};class Ho{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},a=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,r,s){var n,i;const a=e.topic,o=(n=e.ref)!==null&&n!==void 0?n:"",c=(i=e.join_ref)!==null&&i!==void 0?i:"",u=e.payload.event,d=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=Object.keys(d).length===0?"":JSON.stringify(d);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const g=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+o.length+a.length+u.length+h.length,f=new ArrayBuffer(this.HEADER_LENGTH+g);let y=new DataView(f),m=0;y.setUint8(m++,this.KINDS.userBroadcastPush),y.setUint8(m++,c.length),y.setUint8(m++,o.length),y.setUint8(m++,a.length),y.setUint8(m++,u.length),y.setUint8(m++,h.length),y.setUint8(m++,r),Array.from(c,k=>y.setUint8(m++,k.charCodeAt(0))),Array.from(o,k=>y.setUint8(m++,k.charCodeAt(0))),Array.from(a,k=>y.setUint8(m++,k.charCodeAt(0))),Array.from(u,k=>y.setUint8(m++,k.charCodeAt(0))),Array.from(h,k=>y.setUint8(m++,k.charCodeAt(0)));var _=new Uint8Array(f.byteLength+s.byteLength);return _.set(new Uint8Array(f),0),_.set(new Uint8Array(s),f.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){const s=JSON.parse(e),[n,i,a,o,c]=s;return r({join_ref:n,ref:i,topic:a,event:o,payload:c})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;switch(s){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,n)}}_decodeUserBroadcast(e,r,s){const n=r.getUint8(1),i=r.getUint8(2),a=r.getUint8(3),o=r.getUint8(4);let c=this.HEADER_LENGTH+4;const u=s.decode(e.slice(c,c+n));c=c+n;const d=s.decode(e.slice(c,c+i));c=c+i;const h=s.decode(e.slice(c,c+a));c=c+a;const g=e.slice(c,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(s.decode(g)):g,y={type:this.BROADCAST_EVENT,event:d,payload:f};return a>0&&(y.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e==null?void 0:e.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}var Te;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(Te||(Te={}));const hi=(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]=zo(a,t,e,n),i),{}):{}},zo=(t,e,r,s)=>{const n=e.find(o=>o.name===t),i=n==null?void 0:n.type,a=r[t];return i&&!s.includes(i)?ha(i,a):xn(a)},ha=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return Jo(e,r)}switch(t){case Te.bool:return Ko(e);case Te.float4:case Te.float8:case Te.int2:case Te.int4:case Te.int8:case Te.numeric:case Te.oid:return Vo(e);case Te.json:case Te.jsonb:return Go(e);case Te.timestamp:return Qo(e);case Te.abstime:case Te.date:case Te.daterange:case Te.int4range:case Te.int8range:case Te.money:case Te.reltime:case Te.text:case Te.time:case Te.timestamptz:case Te.timetz:case Te.tsrange:case Te.tstzrange:return xn(e);default:return xn(e)}},xn=t=>t,Ko=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Vo=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Go=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Jo=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i;const a=t.slice(1,r);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(o=>ha(e,o))}return t},Qo=t=>typeof t=="string"?t.replace(" ","T"):t,fa=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var cs=t=>typeof t=="function"?t:function(){return t},Yo=typeof self<"u"?self:null,Lr=typeof window<"u"?window:null,kt=Yo||Lr||globalThis,Xo="2.0.0",Zo=1e4,el=1e3,Rt={connecting:0,open:1,closing:2,closed:3},et={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Pt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},_n={longpoll:"longpoll",websocket:"websocket"},tl={complete:4},kn="base64url.bearer.phx.",Ls=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},pa=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},rl=class{constructor(t,e,r){this.state=et.closed,this.topic=t,this.params=cs(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Ls(this,Pt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new pa(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=et.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=et.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=et.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=et.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Ls(this,Pt.leave,cs({}),this.timeout).send(),this.state=et.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Pt.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=et.closed,this.bindings=[]}onClose(t){this.on(Pt.close,t)}onError(t){return this.on(Pt.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new Ls(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=et.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Pt.close,"leave")},r=new Ls(this,Pt.leave,cs({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=et.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(a=>a.event===t&&this.filterBindings(a,e,r));for(let a=0;a<i.length;a++)i[a].callback(n,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===et.closed}isErrored(){return this.state===et.errored}isJoined(){return this.state===et.joined}isJoining(){return this.state===et.joining}isLeaving(){return this.state===et.leaving}},Ks=class{static request(t,e,r,s,n,i,a){if(kt.XDomainRequest){let o=new kt.XDomainRequest;return this.xdomainRequest(o,t,e,s,n,i,a)}else if(kt.XMLHttpRequest){let o=new kt.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,n,i,a)}else{if(kt.fetch&&kt.AbortController)return this.fetchRequest(t,e,r,s,n,i,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,n,i,a){let o={method:t,headers:r,body:s},c=null;return n&&(c=new AbortController,setTimeout(()=>c.abort(),n),o.signal=c.signal),kt.fetch(e,o).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>a&&a(u)).catch(u=>{u.name==="AbortError"&&i?i():a&&a(null)}),c}static xdomainRequest(t,e,r,s,n,i,a){return t.timeout=n,t.open(e,r),t.onload=()=>{let o=this.parseJSON(t.responseText);a&&a(o)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,i,a,o){t.open(e,r,!0),t.timeout=i;for(let[c,u]of Object.entries(s))t.setRequestHeader(c,u);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===tl.complete&&o){let c=this.parseJSON(t.responseText);o(c)}},a&&(t.ontimeout=a),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,i=t[s];typeof i=="object"?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},sl=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(r[n]);return btoa(e)},Cr=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(kn)&&(this.authToken=atob(e[1].slice(kn.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Rt.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+_n.websocket),"$1/"+_n.longpoll)}endpointURL(){return Ks.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Rt.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Rt.open||this.readyState===Rt.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Rt.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=sl(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
38
|
-
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=Rt.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let i,a=()=>{this.reqs.delete(i),s()};i=Ks.request(t,this.endpointURL(),e,r,this.timeout,a,o=>{this.reqs.delete(i),this.isActive()&&n(o)}),this.reqs.add(i)}},nl=class is{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=is.syncState(this.state,n,i,a),this.pendingDiffs.forEach(c=>{this.state=is.syncDiff(this.state,c,i,a)}),this.pendingDiffs=[],o()}),this.channel.on(s.diff,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=is.syncDiff(this.state,n,i,a),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return is.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let i=this.clone(e),a={},o={};return this.map(i,(c,u)=>{r[c]||(o[c]=u)}),this.map(r,(c,u)=>{let d=i[c];if(d){let h=u.metas.map(m=>m.phx_ref),g=d.metas.map(m=>m.phx_ref),f=u.metas.filter(m=>g.indexOf(m.phx_ref)<0),y=d.metas.filter(m=>h.indexOf(m.phx_ref)<0);f.length>0&&(a[c]=u,a[c].metas=f),y.length>0&&(o[c]=this.clone(d),o[c].metas=y)}else a[c]=u}),this.syncDiff(i,{joins:a,leaves:o},s,n)}static syncDiff(e,r,s,n){let{joins:i,leaves:a}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(i,(o,c)=>{let u=e[o];if(e[o]=this.clone(c),u){let d=e[o].metas.map(g=>g.phx_ref),h=u.metas.filter(g=>d.indexOf(g.phx_ref)<0);e[o].metas.unshift(...h)}s(o,u,c)}),this.map(a,(o,c)=>{let u=e[o];if(!u)return;let d=c.metas.map(h=>h.phx_ref);u.metas=u.metas.filter(h=>d.indexOf(h.phx_ref)<0),n(o,u,c),u.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static clone(e){return JSON.parse(JSON.stringify(e))}},$s={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,i,a]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:i,payload:a})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:i}=t,a=this.META_LENGTH+e.length+r.length+n.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),c=new DataView(o),u=0;c.setUint8(u++,this.KINDS.push),c.setUint8(u++,e.length),c.setUint8(u++,r.length),c.setUint8(u++,n.length),c.setUint8(u++,s.length),Array.from(e,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(r,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(n,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(s,h=>c.setUint8(u++,h.charCodeAt(0)));var d=new Uint8Array(o.byteLength+i.byteLength);return d.set(new Uint8Array(o),0),d.set(new Uint8Array(i),o.byteLength),d.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(a,a+s));a=a+s;let c=r.decode(t.slice(a,a+n));a=a+n;let u=r.decode(t.slice(a,a+i));a=a+i;let d=t.slice(a,t.byteLength);return{join_ref:o,ref:null,topic:c,event:u,payload:d}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,c=r.decode(t.slice(o,o+s));o=o+s;let u=r.decode(t.slice(o,o+n));o=o+n;let d=r.decode(t.slice(o,o+i));o=o+i;let h=r.decode(t.slice(o,o+a));o=o+a;let g=t.slice(o,t.byteLength),f={status:h,response:g};return{join_ref:c,ref:u,topic:d,event:Pt.reply,payload:f}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=this.HEADER_LENGTH+2,a=r.decode(t.slice(i,i+s));i=i+s;let o=r.decode(t.slice(i,i+n));i=i+n;let c=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:c}}},il=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Zo,this.transport=e.transport||kt.WebSocket||Cr,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||kt&&kt.sessionStorage,this.establishedConnections=0,this.defaultEncoder=$s.encode.bind($s),this.defaultDecoder=$s.decode.bind($s),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Cr?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;Lr&&Lr.addEventListener&&(Lr.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),r=this.connectClock)}),Lr.addEventListener("pageshow",s=>{r===this.connectClock&&(r=null,this.connect())}),Lr.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=s=>e.rejoinAfterMs?e.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>e.reconnectAfterMs?e.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(s,n,i)=>{console.log(`${s}: ${n}`,i)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=cs(e.params||{}),this.endPoint=`${t}/${_n.websocket}`,this.vsn=e.vsn||Xo,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new pa(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return Cr}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Ks.appendParams(Ks.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=cs(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Cr?this.connectWithFallback(Cr,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(n=>{n.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){switch(t){case Cr:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${kn}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,i,a=this.transportName(t),o=c=>{this.log("transport",`falling back to ${a}...`,c),this.off([n,i]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),i=this.onError(c=>{this.log("transport","error",c),s&&!r&&(clearTimeout(this.fallbackTimer),o(c))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let c=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${c}`,"true"),this.log("transport",`established ${c} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(c=>{this.log("transport","connected to primary after",c),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),el,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===Rt.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Pt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Rt.connecting:return"connecting";case Rt.open:return"open";case Rt.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new rl(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:n,join_ref:i}=t;this.log("push",`${e} ${r} (${i}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",o)}catch(c){this.log("error","error in heartbeat callback",c)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${i&&"("+i+")"||""}`.trim(),n);for(let o=0;o<this.channels.length;o++){const c=this.channels[o];c.isMember(r,s,n,a)&&c.trigger(s,n,i,a)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class us{constructor(e,r){const s=ol(r);this.presence=new nl(e.getChannel(),s),this.presence.onJoin((n,i,a)=>{const o=us.onJoinPayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,i,a)=>{const o=us.onLeavePayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return us.transformState(this.presence.state)}static transformState(e){return e=al(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=zs(n),r},{})}static onJoinPayload(e,r,s){const n=fi(r),i=zs(s);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,r,s){const n=fi(r),i=zs(s);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function zs(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function al(t){return JSON.parse(JSON.stringify(t))}function ol(t){return(t==null?void 0:t.events)&&{events:t.events}}function fi(t){return t!=null&&t.metas?zs(t):[]}var pi;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(pi||(pi={}));class ll{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new us(this.channel.channelAdapter,r)}}class cl{constructor(e,r,s){const n=ul(s);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,s){let n;try{n=this.channel.push(e,r,s)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>qo){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===zt.joined}isJoined(){return this.state===zt.joined}isJoining(){return this.state===zt.joining}isClosed(){return this.state===zt.closed}isLeaving(){return this.state===zt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function ul(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var gi;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(gi||(gi={}));var Ur;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Ur||(Ur={}));var Nt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Nt||(Nt={}));class ds{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new cl(this.socket.socketAdapter,e,this.params),this.presence=new ll(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=fa(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var s,n,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:a,presence:o,private:c}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(f=>f.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[Ur.PRESENCE]&&this.bindings[Ur.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},g={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:d}),postgres_changes:u,private:c};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(f=>{e==null||e(Nt.CHANNEL_ERROR,f)}),this._onClose(()=>e==null?void 0:e(Nt.CLOSED)),this.updateJoinPayload(Object.assign({config:g},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:f})=>{if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e==null||e(Nt.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",f=>{this.state=zt.errored,e==null||e(Nt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(Nt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const n=this.bindings.postgres_changes,i=(s=n==null?void 0:n.length)!==null&&s!==void 0?s:0,a=[];for(let o=0;o<i;o++){const c=n[o],{filter:{event:u,schema:d,table:h,filter:g}}=c,f=e&&e[o];if(f&&f.event===u&&ds.isFilterValueEqual(f.schema,d)&&ds.isFilterValueEqual(f.table,h)&&ds.isFilterValueEqual(f.filter,g))a.push(Object.assign(Object.assign({},c),{id:f.id}));else{this.unsubscribe(),this.state=zt.errored,r==null||r(Nt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=zt.errored&&r&&r(Nt.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){const n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===Ur.PRESENCE||e===Ur.POSTGRES_CHANGES;if(n&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(o.status===202)return{success:!0};let c=o.statusText;try{const u=await o.json();c=u.error||u.message||c}catch{}return Promise.reject(new Error(c))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:a}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,o,c;const u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){const n=new AbortController,i=setTimeout(()=>n.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),a}_on(e,r,s){const n=e.toLocaleLowerCase(),i=this.channelAdapter.on(e,s),a={type:n,filter:r,callback:s,ref:i};return this.bindings[n]?this.bindings[n].push(a):this.bindings[n]=[a],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,i,a,o,c,u,d;const h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;const g=(n=this.bindings[h])===null||n===void 0?void 0:n.find(f=>f.ref===e.ref);if(!g)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in g){const f=g.id,y=(i=g.filter)===null||i===void 0?void 0:i.event;return f&&((a=r.ids)===null||a===void 0?void 0:a.includes(f))&&(y==="*"||(y==null?void 0:y.toLocaleLowerCase())===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const f=(u=(c=g==null?void 0:g.filter)===null||c===void 0?void 0:c.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return f==="*"||f===((d=r==null?void 0:r.event)===null||d===void 0?void 0:d.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){const{close:s,error:n,leave:i,join:a}=da;return r&&[s,n,i,a].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){const n=r.data,{schema:i,table:a,commit_timestamp:o,type:c,errors:u}=n;return Object.assign(Object.assign({},{schema:i,table:a,commit_timestamp:o,eventType:c,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=hi(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=hi(e.columns,e.old_record)),r}}class dl{constructor(e,r){this.socket=new il(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==wn.connecting}isDisconnecting(){return this.socket.connectionState()==wn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const hl={HEARTBEAT_INTERVAL:25e3},fl=[1e3,2e3,5e3,1e4],pl=1e4,gl=`
|
|
37
|
+
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const Ko="2.101.1",Vo=`realtime-js/${Ko}`,Go="1.0.0",pa="2.0.0",Jo=pa,Qo=1e4,Yo=100,er={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ga={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Sn={connecting:"connecting",closing:"closing",closed:"closed"};class Xo{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},a=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,r,s){var n,i;const a=e.topic,o=(n=e.ref)!==null&&n!==void 0?n:"",c=(i=e.join_ref)!==null&&i!==void 0?i:"",u=e.payload.event,d=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=Object.keys(d).length===0?"":JSON.stringify(d);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const p=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+o.length+a.length+u.length+h.length,f=new ArrayBuffer(this.HEADER_LENGTH+p);let y=new DataView(f),b=0;y.setUint8(b++,this.KINDS.userBroadcastPush),y.setUint8(b++,c.length),y.setUint8(b++,o.length),y.setUint8(b++,a.length),y.setUint8(b++,u.length),y.setUint8(b++,h.length),y.setUint8(b++,r),Array.from(c,k=>y.setUint8(b++,k.charCodeAt(0))),Array.from(o,k=>y.setUint8(b++,k.charCodeAt(0))),Array.from(a,k=>y.setUint8(b++,k.charCodeAt(0))),Array.from(u,k=>y.setUint8(b++,k.charCodeAt(0))),Array.from(h,k=>y.setUint8(b++,k.charCodeAt(0)));var m=new Uint8Array(f.byteLength+s.byteLength);return m.set(new Uint8Array(f),0),m.set(new Uint8Array(s),f.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,o,c]=s;return r({join_ref:n,ref:i,topic:a,event:o,payload:c})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;switch(s){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,n)}}_decodeUserBroadcast(e,r,s){const n=r.getUint8(1),i=r.getUint8(2),a=r.getUint8(3),o=r.getUint8(4);let c=this.HEADER_LENGTH+4;const u=s.decode(e.slice(c,c+n));c=c+n;const d=s.decode(e.slice(c,c+i));c=c+i;const h=s.decode(e.slice(c,c+a));c=c+a;const p=e.slice(c,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(s.decode(p)):p,y={type:this.BROADCAST_EVENT,event:d,payload:f};return a>0&&(y.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e==null?void 0:e.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}var 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 bi=(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]=Zo(a,t,e,n),i),{}):{}},Zo=(t,e,r,s)=>{const n=e.find(o=>o.name===t),i=n==null?void 0:n.type,a=r[t];return i&&!s.includes(i)?ba(i,a):En(a)},ba=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return sl(e,r)}switch(t){case xe.bool:return el(e);case xe.float4:case xe.float8:case xe.int2:case xe.int4:case xe.int8:case xe.numeric:case xe.oid:return tl(e);case xe.json:case xe.jsonb:return rl(e);case xe.timestamp:return nl(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 En(e);default:return En(e)}},En=t=>t,el=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},tl=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},rl=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},sl=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i;const a=t.slice(1,r);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(o=>ba(e,o))}return t},nl=t=>typeof t=="string"?t.replace(" ","T"):t,ma=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var hs=t=>typeof t=="function"?t:function(){return t},il=typeof self<"u"?self:null,Dr=typeof window<"u"?window:null,It=il||Dr||globalThis,al="2.0.0",ol=1e4,ll=1e3,$t={connecting:0,open:1,closing:2,closed:3},it={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},qt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},jn={longpoll:"longpoll",websocket:"websocket"},cl={complete:4},Tn="base64url.bearer.phx.",Us=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},ya=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},ul=class{constructor(t,e,r){this.state=it.closed,this.topic=t,this.params=hs(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Us(this,qt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ya(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=it.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=it.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=it.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=it.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Us(this,qt.leave,hs({}),this.timeout).send(),this.state=it.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(qt.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=it.closed,this.bindings=[]}onClose(t){this.on(qt.close,t)}onError(t){return this.on(qt.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new Us(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=it.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(qt.close,"leave")},r=new Us(this,qt.leave,hs({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=it.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(a=>a.event===t&&this.filterBindings(a,e,r));for(let a=0;a<i.length;a++)i[a].callback(n,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===it.closed}isErrored(){return this.state===it.errored}isJoined(){return this.state===it.joined}isJoining(){return this.state===it.joining}isLeaving(){return this.state===it.leaving}},Js=class{static request(t,e,r,s,n,i,a){if(It.XDomainRequest){let o=new It.XDomainRequest;return this.xdomainRequest(o,t,e,s,n,i,a)}else if(It.XMLHttpRequest){let o=new It.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,n,i,a)}else{if(It.fetch&&It.AbortController)return this.fetchRequest(t,e,r,s,n,i,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,n,i,a){let o={method:t,headers:r,body:s},c=null;return n&&(c=new AbortController,setTimeout(()=>c.abort(),n),o.signal=c.signal),It.fetch(e,o).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>a&&a(u)).catch(u=>{u.name==="AbortError"&&i?i():a&&a(null)}),c}static xdomainRequest(t,e,r,s,n,i,a){return t.timeout=n,t.open(e,r),t.onload=()=>{let o=this.parseJSON(t.responseText);a&&a(o)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,i,a,o){t.open(e,r,!0),t.timeout=i;for(let[c,u]of Object.entries(s))t.setRequestHeader(c,u);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===cl.complete&&o){let c=this.parseJSON(t.responseText);o(c)}},a&&(t.ontimeout=a),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,i=t[s];typeof i=="object"?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},dl=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(r[n]);return btoa(e)},Or=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Tn)&&(this.authToken=atob(e[1].slice(Tn.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=$t.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+jn.websocket),"$1/"+jn.longpoll)}endpointURL(){return Js.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=$t.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===$t.open||this.readyState===$t.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=$t.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=dl(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
38
|
+
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=$t.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let i,a=()=>{this.reqs.delete(i),s()};i=Js.request(t,this.endpointURL(),e,r,this.timeout,a,o=>{this.reqs.delete(i),this.isActive()&&n(o)}),this.reqs.add(i)}},hl=class ls{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=ls.syncState(this.state,n,i,a),this.pendingDiffs.forEach(c=>{this.state=ls.syncDiff(this.state,c,i,a)}),this.pendingDiffs=[],o()}),this.channel.on(s.diff,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=ls.syncDiff(this.state,n,i,a),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return ls.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let i=this.clone(e),a={},o={};return this.map(i,(c,u)=>{r[c]||(o[c]=u)}),this.map(r,(c,u)=>{let d=i[c];if(d){let h=u.metas.map(b=>b.phx_ref),p=d.metas.map(b=>b.phx_ref),f=u.metas.filter(b=>p.indexOf(b.phx_ref)<0),y=d.metas.filter(b=>h.indexOf(b.phx_ref)<0);f.length>0&&(a[c]=u,a[c].metas=f),y.length>0&&(o[c]=this.clone(d),o[c].metas=y)}else a[c]=u}),this.syncDiff(i,{joins:a,leaves:o},s,n)}static syncDiff(e,r,s,n){let{joins:i,leaves:a}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(i,(o,c)=>{let u=e[o];if(e[o]=this.clone(c),u){let d=e[o].metas.map(p=>p.phx_ref),h=u.metas.filter(p=>d.indexOf(p.phx_ref)<0);e[o].metas.unshift(...h)}s(o,u,c)}),this.map(a,(o,c)=>{let u=e[o];if(!u)return;let d=c.metas.map(h=>h.phx_ref);u.metas=u.metas.filter(h=>d.indexOf(h.phx_ref)<0),n(o,u,c),u.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Ms={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,i,a]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:i,payload:a})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:i}=t,a=this.META_LENGTH+e.length+r.length+n.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),c=new DataView(o),u=0;c.setUint8(u++,this.KINDS.push),c.setUint8(u++,e.length),c.setUint8(u++,r.length),c.setUint8(u++,n.length),c.setUint8(u++,s.length),Array.from(e,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(r,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(n,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(s,h=>c.setUint8(u++,h.charCodeAt(0)));var d=new Uint8Array(o.byteLength+i.byteLength);return d.set(new Uint8Array(o),0),d.set(new Uint8Array(i),o.byteLength),d.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(a,a+s));a=a+s;let c=r.decode(t.slice(a,a+n));a=a+n;let u=r.decode(t.slice(a,a+i));a=a+i;let d=t.slice(a,t.byteLength);return{join_ref:o,ref:null,topic:c,event:u,payload:d}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,c=r.decode(t.slice(o,o+s));o=o+s;let u=r.decode(t.slice(o,o+n));o=o+n;let d=r.decode(t.slice(o,o+i));o=o+i;let h=r.decode(t.slice(o,o+a));o=o+a;let p=t.slice(o,t.byteLength),f={status:h,response:p};return{join_ref:c,ref:u,topic:d,event:qt.reply,payload:f}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=this.HEADER_LENGTH+2,a=r.decode(t.slice(i,i+s));i=i+s;let o=r.decode(t.slice(i,i+n));i=i+n;let c=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:c}}},fl=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||ol,this.transport=e.transport||It.WebSocket||Or,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||It&&It.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Ms.encode.bind(Ms),this.defaultDecoder=Ms.decode.bind(Ms),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Or?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;Dr&&Dr.addEventListener&&(Dr.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),r=this.connectClock)}),Dr.addEventListener("pageshow",s=>{r===this.connectClock&&(r=null,this.connect())}),Dr.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=s=>e.rejoinAfterMs?e.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>e.reconnectAfterMs?e.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(s,n,i)=>{console.log(`${s}: ${n}`,i)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=hs(e.params||{}),this.endPoint=`${t}/${jn.websocket}`,this.vsn=e.vsn||al,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ya(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return Or}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Js.appendParams(Js.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=hs(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Or?this.connectWithFallback(Or,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(n=>{n.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){switch(t){case Or:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Tn}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,i,a=this.transportName(t),o=c=>{this.log("transport",`falling back to ${a}...`,c),this.off([n,i]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),i=this.onError(c=>{this.log("transport","error",c),s&&!r&&(clearTimeout(this.fallbackTimer),o(c))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let c=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${c}`,"true"),this.log("transport",`established ${c} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(c=>{this.log("transport","connected to primary after",c),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),ll,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===$t.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(qt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case $t.connecting:return"connecting";case $t.open:return"open";case $t.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new ul(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:n,join_ref:i}=t;this.log("push",`${e} ${r} (${i}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",o)}catch(c){this.log("error","error in heartbeat callback",c)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${i&&"("+i+")"||""}`.trim(),n);for(let o=0;o<this.channels.length;o++){const c=this.channels[o];c.isMember(r,s,n,a)&&c.trigger(s,n,i,a)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class fs{constructor(e,r){const s=gl(r);this.presence=new hl(e.getChannel(),s),this.presence.onJoin((n,i,a)=>{const o=fs.onJoinPayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,i,a)=>{const o=fs.onLeavePayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return fs.transformState(this.presence.state)}static transformState(e){return e=pl(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=Gs(n),r},{})}static onJoinPayload(e,r,s){const n=mi(r),i=Gs(s);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,r,s){const n=mi(r),i=Gs(s);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function Gs(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function pl(t){return JSON.parse(JSON.stringify(t))}function gl(t){return(t==null?void 0:t.events)&&{events:t.events}}function mi(t){return t!=null&&t.metas?Gs(t):[]}var yi;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(yi||(yi={}));class bl{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new fs(this.channel.channelAdapter,r)}}class ml{constructor(e,r,s){const n=yl(s);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,s){let n;try{n=this.channel.push(e,r,s)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>Yo){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===er.joined}isJoined(){return this.state===er.joined}isJoining(){return this.state===er.joining}isClosed(){return this.state===er.closed}isLeaving(){return this.state===er.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function yl(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var vi;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(vi||(vi={}));var Wr;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Wr||(Wr={}));var zt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(zt||(zt={}));class ps{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new ml(this.socket.socketAdapter,e,this.params),this.presence=new bl(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=ma(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var s,n,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:a,presence:o,private:c}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(f=>f.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[Wr.PRESENCE]&&this.bindings[Wr.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},p={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:d}),postgres_changes:u,private:c};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(f=>{e==null||e(zt.CHANNEL_ERROR,f)}),this._onClose(()=>e==null?void 0:e(zt.CLOSED)),this.updateJoinPayload(Object.assign({config:p},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:f})=>{if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e==null||e(zt.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",f=>{this.state=er.errored,e==null||e(zt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(zt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const n=this.bindings.postgres_changes,i=(s=n==null?void 0:n.length)!==null&&s!==void 0?s:0,a=[];for(let o=0;o<i;o++){const c=n[o],{filter:{event:u,schema:d,table:h,filter:p}}=c,f=e&&e[o];if(f&&f.event===u&&ps.isFilterValueEqual(f.schema,d)&&ps.isFilterValueEqual(f.table,h)&&ps.isFilterValueEqual(f.filter,p))a.push(Object.assign(Object.assign({},c),{id:f.id}));else{this.unsubscribe(),this.state=er.errored,r==null||r(zt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=er.errored&&r&&r(zt.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){const n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===Wr.PRESENCE||e===Wr.POSTGRES_CHANGES;if(n&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(o.status===202)return{success:!0};let c=o.statusText;try{const u=await o.json();c=u.error||u.message||c}catch{}return Promise.reject(new Error(c))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:a}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,o,c;const u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){const n=new AbortController,i=setTimeout(()=>n.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),a}_on(e,r,s){const n=e.toLocaleLowerCase(),i=this.channelAdapter.on(e,s),a={type:n,filter:r,callback:s,ref:i};return this.bindings[n]?this.bindings[n].push(a):this.bindings[n]=[a],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,i,a,o,c,u,d;const h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;const p=(n=this.bindings[h])===null||n===void 0?void 0:n.find(f=>f.ref===e.ref);if(!p)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in p){const f=p.id,y=(i=p.filter)===null||i===void 0?void 0:i.event;return f&&((a=r.ids)===null||a===void 0?void 0:a.includes(f))&&(y==="*"||(y==null?void 0:y.toLocaleLowerCase())===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const f=(u=(c=p==null?void 0:p.filter)===null||c===void 0?void 0:c.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return f==="*"||f===((d=r==null?void 0:r.event)===null||d===void 0?void 0:d.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){const{close:s,error:n,leave:i,join:a}=ga;return r&&[s,n,i,a].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){const n=r.data,{schema:i,table:a,commit_timestamp:o,type:c,errors:u}=n;return Object.assign(Object.assign({},{schema:i,table:a,commit_timestamp:o,eventType:c,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=bi(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=bi(e.columns,e.old_record)),r}}class vl{constructor(e,r){this.socket=new fl(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Sn.connecting}isDisconnecting(){return this.socket.connectionState()==Sn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const wl={HEARTBEAT_INTERVAL:25e3},xl=[1e3,2e3,5e3,1e4],_l=1e4,kl=`
|
|
39
39
|
addEventListener("message", (e) => {
|
|
40
40
|
if (e.data.event === "start") {
|
|
41
41
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
42
42
|
}
|
|
43
|
-
});`;class
|
|
43
|
+
});`;class Sl{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var s;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new Xo,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=i=>i?(...a)=>i(...a):(...a)=>fetch(...a),!(!((s=r==null?void 0:r.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;const n=this._initializeOptions(r);this.socketAdapter=new vl(e,n),this.httpEndpoint=ma(e),this.fetch=this._resolveFetch(r==null?void 0:r.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const r=e.message;throw r.includes("Node.js")?new Error(`${r}
|
|
44
44
|
|
|
45
45
|
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
46
46
|
|
|
@@ -53,31 +53,32 @@ Option 2: Install and provide the "ws" package:
|
|
|
53
53
|
const client = new RealtimeClient(url, {
|
|
54
54
|
...options,
|
|
55
55
|
transport: ws
|
|
56
|
-
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=this.channels.map(async s=>{const n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}connectionState(){return this.socketAdapter.connectionState()||wn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{const i=new ds(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const i={access_token:r,version:Do};r&&n.updateJoinPayload(i),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(da.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,s)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([gl],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,i,a,o,c,u,d;this.worker=(r=e==null?void 0:e.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e==null?void 0:e.accessToken)!==null&&s!==void 0?s:null;const h={};h.timeout=(n=e==null?void 0:e.timeout)!==null&&n!==void 0?n:Wo,h.heartbeatIntervalMs=(i=e==null?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:hl.HEARTBEAT_INTERVAL,h.transport=(a=e==null?void 0:e.transport)!==null&&a!==void 0?a:Lo.getWebSocketConstructor(),h.params=e==null?void 0:e.params,h.logger=e==null?void 0:e.logger,h.heartbeatCallback=this._wrapHeartbeatCallback(e==null?void 0:e.heartbeatCallback),h.reconnectAfterMs=(o=e==null?void 0:e.reconnectAfterMs)!==null&&o!==void 0?o:m=>fl[m-1]||pl;let g,f;const y=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:Mo;switch(y){case Uo:g=(m,_)=>_(JSON.stringify(m)),f=(m,_)=>_(JSON.parse(m));break;case ua:g=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${h.vsn}`)}if(h.vsn=y,h.encode=(u=e==null?void 0:e.encode)!==null&&u!==void 0?u:g,h.decode=(d=e==null?void 0:e.decode)!==null&&d!==void 0?d:f,h.beforeReconnect=this._reconnectAuth.bind(this),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,h.params=Object.assign(Object.assign({},h.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl,h.autoSendHeartbeat=!this.worker}return h}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var ps=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 bl(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 yl(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 vl(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const o=bl(t.baseUrl,s,n),c=await yl(t.auth),u=await e(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...c,...a},body:i?JSON.stringify(i):void 0}),d=await u.text(),h=(u.headers.get("content-type")||"").includes("application/json"),g=h&&d?JSON.parse(d):d;if(!u.ok){const f=h?g:void 0,y=f==null?void 0:f.error;throw new ps((y==null?void 0:y.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:y==null?void 0:y.type,icebergCode:y==null?void 0:y.code,details:f})}return{status:u.status,headers:u.headers,data:g}}}}function Ds(t){return t.join("")}var wl=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:Ds(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/${Ds(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ds(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ds(t.namespace)}`}),!0}catch(e){if(e instanceof ps&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof ps&&r.status===409)return;throw r}}};function Ar(t){return t.join("")}var xl=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/${Ar(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/${Ar(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/${Ar(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/${Ar(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/${Ar(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/${Ar(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof ps&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof ps&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},_l=class{constructor(t){var s;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=vl({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(s=t.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new wl(this.client,e),this.tableOps=new xl(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)}},en=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 tn(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Sn=class extends en{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}}},ga=class extends en{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const kl=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Sl=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)},En=t=>{if(Array.isArray(t))return t.map(r=>En(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]=En(s)}),e},El=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function gs(t){"@babel/helpers - typeof";return gs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gs(t)}function jl(t,e){if(gs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(gs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Tl(t){var e=jl(t,"string");return gs(e)=="symbol"?e:e+""}function Rl(t,e,r){return(e=Tl(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function mi(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function ee(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?mi(Object(r),!0).forEach(function(s){Rl(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):mi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const bi=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)},Cl=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){const n=t;let i=parseInt(n.status,10);Number.isFinite(i)||(i=500),n.json().then(a=>{const o=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||i+"";e(new Sn(bi(a),i,o,s))}).catch(()=>{const a=i+"";e(new Sn(n.statusText||`HTTP ${i} error`,i,a,s))})}else e(new ga(bi(t),t,s))},Al=(t,e,r,s)=>{const n={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||t==="HEAD"||!s?ee(ee({},n),r):(Sl(s)?(n.headers=ee({"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),ee(ee({},n),r))};async function ss(t,e,r,s,n,i,a){return new Promise((o,c)=>{t(r,Al(e,s,n,i)).then(u=>{if(!u.ok)throw u;if(s!=null&&s.noResolveJson)return u;if(a==="vectors"){const d=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>o(u)).catch(u=>Cl(u,c,s,a))})}function ma(t="storage"){return{get:async(e,r,s,n)=>ss(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>ss(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>ss(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>ss(e,"HEAD",r,ee(ee({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>ss(e,"DELETE",r,n,i,s,t)}}const Ol=ma("storage"),{get:ms,post:yt,put:jn,head:Pl,remove:Jn}=Ol,lt=ma("vectors");var es=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=kl(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=ee(ee({},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(tn(r))return{data:null,error:r};throw r}}},Nl=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(tn(e))return{data:null,error:e};throw e}}};let ba;ba=Symbol.toStringTag;var Il=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[ba]="BlobDownloadBuilder",this.promise=null}asStream(){return new Nl(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(tn(e))return{data:null,error:e};throw e}}};const Bl={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},yi={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Fl=class extends es{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=ee(ee({},yi),s);let o=ee(ee({},n.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const c=a.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",n.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),c&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(c))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,c&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(c))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s!=null&&s.headers&&(o=ee(ee({},o),s.headers));const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),h=await(t=="PUT"?jn:yt)(n.fetch,`${n.url}/object/${d}`,i,ee({headers:o},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{path:u,id:h.Id,fullPath:h.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;const i=n._removeEmptyFolders(t),a=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),n.handleOperation(async()=>{let c;const u=ee(ee({},yi),s),d=ee(ee({},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 jn(n.fetch,o.toString(),c,{headers:d})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=ee({},r.headers);e!=null&&e.upsert&&(n["x-upsert"]="true");const i=await yt(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new en("No token returned by API");return{signedUrl:a.toString(),path:t,token:o}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await yt(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await yt(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t);const i=typeof(r==null?void 0:r.transform)=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await yt(s.fetch,`${s.url}/object/sign/${n}`,ee({expiresIn:e},i?{transform:r.transform}:{}),{headers:s.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"",c=i&&a.signedURL.includes("/object/sign/")?a.signedURL.replace("/object/sign/","/render/image/sign/"):a.signedURL;return{signedUrl:encodeURI(`${s.url}${c}${o}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await yt(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(a=>ee(ee({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${i}`):null}))})}download(t,e,r){const s=typeof(e==null?void 0:e.transform)<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),i=n?`?${n}`:"",a=this._getFinalPath(t),o=()=>ms(this.fetch,`${this.url}/${s}/${a}${i}`,{headers:this.headers,noResolveJson:!0},r);return new Il(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>En(await ms(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await Pl(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(tn(n)){var s;const i=n instanceof Sn?n.status:n instanceof ga?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=[],n=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&s.push(n);const i=typeof(e==null?void 0:e.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});a!==""&&s.push(a);let o=s.join("&");return o!==""&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${o}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await Jn(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=ee(ee(ee({},Bl),e),{},{prefix:t||""});return await yt(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=ee({},t);return await yt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}};const Ll="2.101.0",Cs={"X-Client-Info":`storage-js/${Ll}`};var $l=class extends es{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=ee(ee({},Cs),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await ms(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await ms(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await yt(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await jn(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await yt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Jn(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():""}},Dl=class extends es{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ee(ee({},Cs),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await yt(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&r.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&r.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&r.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&r.set("sortOrder",t.sortOrder),t!=null&&t.search&&r.set("search",t.search);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await ms(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Jn(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!El(t))throw new en("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 _l({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){const a=n[i];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(n,o),error:null}}catch(c){if(s)throw c;return{data:null,error:c}}}}})}},Ul=class extends es{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ee(ee({},Cs),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await lt.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await lt.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await lt.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await lt.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Ml=class extends es{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ee(ee({},Cs),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await lt.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await lt.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 lt.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await lt.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 lt.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Wl=class extends es{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ee(ee({},Cs),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await lt.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await lt.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await lt.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await lt.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},ql=class extends Wl{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Hl(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)}},Hl=class extends Ul{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,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,ee(ee({},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 zl(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},zl=class extends Ml{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,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,ee(ee({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Kl=class extends $l{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new Fl(this.url,this.headers,t,this.fetch)}get vectors(){return new ql(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Dl(this.url+"/iceberg",this.headers,this.fetch)}};const ya="2.101.0",$r=30*1e3,Tn=3,un=Tn*$r,Vl="http://localhost:9999",Gl="supabase.auth.token",Jl={"X-Client-Info":`gotrue-js/${ya}`},Rn="X-Supabase-Api-Version",va={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Ql=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Yl=10*60*1e3;class bs extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function V(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class Xl extends bs{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function Zl(t){return V(t)&&t.name==="AuthApiError"}class dr extends bs{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class Lt extends bs{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class at extends Lt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function dn(t){return V(t)&&t.name==="AuthSessionMissingError"}class Or extends Lt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Us extends Lt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Ms extends Lt{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 ec(t){return V(t)&&t.name==="AuthImplicitGrantRedirectError"}class vi extends Lt{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 tc extends Lt{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 Cn extends Lt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function hn(t){return V(t)&&t.name==="AuthRetryableFetchError"}class wi extends Lt{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class An extends Lt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Vs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),xi=`
|
|
57
|
-
\r=`.split(""),rc=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<xi.length;e+=1)t[xi[e].charCodeAt(0)]=-2;for(let e=0;e<Vs.length;e+=1)t[Vs[e].charCodeAt(0)]=e;return t})();function _i(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(Vs[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(Vs[s]),e.queuedBits-=6}}function wa(t,e,r){const s=rc[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 ki(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{ic(a,s,r)};for(let a=0;a<t.length;a+=1)wa(t.charCodeAt(a),n,i);return e.join("")}function sc(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 nc(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}sc(s,e)}}function ic(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 Mr(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)wa(t.charCodeAt(n),r,s);return new Uint8Array(e)}function ac(t){const e=[];return nc(t,r=>e.push(r)),new Uint8Array(e)}function hr(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>_i(n,r,s)),_i(null,r,s),e.join("")}function oc(t){return Math.round(Date.now()/1e3)+t}function lc(){return Symbol("auth-callback")}const He=()=>typeof window<"u"&&typeof document<"u",lr={tested:!1,writable:!1},xa=()=>{if(!He())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(lr.tested)return lr.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),lr.tested=!0,lr.writable=!0}catch{lr.tested=!0,lr.writable=!1}return lr.writable};function cc(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 _a=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),uc=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Dr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},cr=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},qe=async(t,e)=>{await t.removeItem(e)};class rn{constructor(){this.promise=new rn.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}rn.promiseConstructor=Promise;function Ws(t){const e=t.split(".");if(e.length!==3)throw new An("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Ql.test(e[s]))throw new An("JWT not in base64url format");return{header:JSON.parse(ki(e[0])),payload:JSON.parse(ki(e[1])),signature:Mr(e[2]),raw:{header:e[0],payload:e[1]}}}async function dc(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function hc(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 fc(t){return("0"+t.toString(16)).substr(-2)}function pc(){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,fc).join("")}async function gc(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 mc(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 gc(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Pr(t,e,r=!1){const s=pc();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await Dr(t,`${e}-code-verifier`,n);const i=await mc(s);return[i,s===i?"plain":"s256"]}const bc=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function yc(t){const e=t.headers.get(Rn);if(!e||!e.match(bc))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function vc(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 wc(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 xc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Nr(t){if(!xc.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function fn(){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 _c(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 Si(t){return JSON.parse(JSON.stringify(t))}const ur=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),kc=[502,503,504];async function Ei(t){var e;if(!uc(t))throw new Cn(ur(t),0);if(kc.includes(t.status))throw new Cn(ur(t),t.status);let r;try{r=await t.json()}catch(i){throw new dr(ur(i),i)}let s;const n=yc(t);if(n&&n.getTime()>=va["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 wi(ur(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new at}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 wi(ur(r),t.status,r.weak_password.reasons);throw new Xl(ur(r),t.status||500,s)}const Sc=(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 X(t,e,r,s){var n;const i=Object.assign({},s==null?void 0:s.headers);i[Rn]||(i[Rn]=va["2024-01-01"].name),s!=null&&s.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const a=(n=s==null?void 0:s.query)!==null&&n!==void 0?n:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await Ec(t,e,r+o,{headers:i,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(c):{data:Object.assign({},c),error:null}}async function Ec(t,e,r,s,n,i){const a=Sc(e,s,n,i);let o;try{o=await t(r,Object.assign({},a))}catch(c){throw console.error(c),new Cn(ur(c),0)}if(o.ok||await Ei(o),s!=null&&s.noResolveJson)return o;try{return await o.json()}catch(c){await Ei(c)}}function bt(t){var e;let r=null;Rc(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=oc(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function ji(t){const e=bt(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 Kt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function jc(t){return{data:t,error:null}}function Tc(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=Zs(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},c=Object.assign({},a);return{data:{properties:o,user:c},error:null}}function Ti(t){return t}function Rc(t){return t.access_token&&t.refresh_token&&t.expires_in}const pn=["global","local","others"];class Cc{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=_a(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,r=pn[0]){if(pn.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${pn.join(", ")}`);try{return await X(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(V(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await X(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Kt})}catch(s){if(V(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=Zs(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 X(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Tc,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(V(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await X(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Kt})}catch(r){if(V(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,a,o,c;try{const u={nextPage:null,lastPage:0,total:0},d=await X(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:Ti});if(d.error)throw d.error;const h=await d.json(),g=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(c=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(y=>{const m=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(y.split(";")[1].split("=")[1]);u[`${_}Page`]=m}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(V(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Nr(e);try{return await X(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Kt})}catch(r){if(V(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Nr(e);try{return await X(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Kt})}catch(s){if(V(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){Nr(e);try{return await X(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Kt})}catch(s){if(V(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Nr(e.userId);try{const{data:r,error:s}=await X(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(V(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Nr(e.userId),Nr(e.id);try{return{data:await X(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(V(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,a,o,c;try{const u={nextPage:null,lastPage:0,total:0},d=await X(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:Ti});if(d.error)throw d.error;const h=await d.json(),g=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(c=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(y=>{const m=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(y.split(";")[1].split("=")[1]);u[`${_}Page`]=m}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(V(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await X(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(V(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await X(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(V(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await X(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(V(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await X(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(V(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await X(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(V(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e!=null&&e.type&&(r.type=e.type),await X(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s==null?void 0:s.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(V(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await X(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(V(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await X(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(V(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await X(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(V(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await X(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(V(r))return{data:null,error:r};throw r}}}function Ri(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const _t={debug:!!(globalThis&&xa()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ka extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Ci extends ka{}async function Ac(t,e,r){_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;let n;e>0&&(n=setTimeout(()=>{s.abort(),_t.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){clearTimeout(n),_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw _t.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Ci(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(_t.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(n),await r()}})}catch(i){if(e>0&&clearTimeout(n),(i==null?void 0:i.name)==="AbortError"&&e>0){if(s.signal.aborted)return _t.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async a=>{if(a){_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,a.name);try{return await r()}finally{_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,a.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw _t.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Ci(`Lock "${t}" was released because another request stole it`)}throw i}}function Oc(){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 Sa(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Pc(t){return parseInt(t,16)}function Nc(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Ic(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:c,resources:u,scheme:d,uri:h,version:g}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(g!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${g}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
58
|
-
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const f=
|
|
59
|
-
`:"",
|
|
56
|
+
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=this.channels.map(async s=>{const n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}connectionState(){return this.socketAdapter.connectionState()||Sn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{const i=new ps(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const i={access_token:r,version:Vo};r&&n.updateJoinPayload(i),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(ga.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,s)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([kl],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,i,a,o,c,u,d;this.worker=(r=e==null?void 0:e.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e==null?void 0:e.accessToken)!==null&&s!==void 0?s:null;const h={};h.timeout=(n=e==null?void 0:e.timeout)!==null&&n!==void 0?n:Qo,h.heartbeatIntervalMs=(i=e==null?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:wl.HEARTBEAT_INTERVAL,h.transport=(a=e==null?void 0:e.transport)!==null&&a!==void 0?a:Ho.getWebSocketConstructor(),h.params=e==null?void 0:e.params,h.logger=e==null?void 0:e.logger,h.heartbeatCallback=this._wrapHeartbeatCallback(e==null?void 0:e.heartbeatCallback),h.reconnectAfterMs=(o=e==null?void 0:e.reconnectAfterMs)!==null&&o!==void 0?o:b=>xl[b-1]||_l;let p,f;const y=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:Jo;switch(y){case Go:p=(b,m)=>m(JSON.stringify(b)),f=(b,m)=>m(JSON.parse(b));break;case pa:p=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${h.vsn}`)}if(h.vsn=y,h.encode=(u=e==null?void 0:e.encode)!==null&&u!==void 0?u:p,h.decode=(d=e==null?void 0:e.decode)!==null&&d!==void 0?d:f,h.beforeReconnect=this._reconnectAuth.bind(this),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,h.params=Object.assign(Object.assign({},h.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl,h.autoSendHeartbeat=!this.worker}return h}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var bs=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 El(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 jl(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 Tl(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const o=El(t.baseUrl,s,n),c=await jl(t.auth),u=await e(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...c,...a},body:i?JSON.stringify(i):void 0}),d=await u.text(),h=(u.headers.get("content-type")||"").includes("application/json"),p=h&&d?JSON.parse(d):d;if(!u.ok){const f=h?p:void 0,y=f==null?void 0:f.error;throw new bs((y==null?void 0:y.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:y==null?void 0:y.type,icebergCode:y==null?void 0:y.code,details:f})}return{status:u.status,headers:u.headers,data:p}}}}function Ws(t){return t.join("")}var Rl=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:Ws(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ws(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ws(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ws(t.namespace)}`}),!0}catch(e){if(e instanceof bs&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof bs&&r.status===409)return;throw r}}};function Pr(t){return t.join("")}var Cl=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/${Pr(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/${Pr(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/${Pr(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/${Pr(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/${Pr(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/${Pr(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof bs&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof bs&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Al=class{constructor(t){var s;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Tl({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(s=t.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new Rl(this.client,e),this.tableOps=new Cl(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}},sn=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function nn(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Rn=class extends sn{constructor(t,e,r,s="storage"){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},va=class extends sn{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const Ol=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Pl=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)},Cn=t=>{if(Array.isArray(t))return t.map(r=>Cn(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]=Cn(s)}),e},Il=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function ms(t){"@babel/helpers - typeof";return ms=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},ms(t)}function Nl(t,e){if(ms(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ms(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Fl(t){var e=Nl(t,"string");return ms(e)=="symbol"?e:e+""}function Bl(t,e,r){return(e=Fl(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function wi(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 Y(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?wi(Object(r),!0).forEach(function(s){Bl(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):wi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const xi=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)},Ll=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){const n=t;let i=parseInt(n.status,10);Number.isFinite(i)||(i=500),n.json().then(a=>{const o=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||i+"";e(new Rn(xi(a),i,o,s))}).catch(()=>{const a=i+"";e(new Rn(n.statusText||`HTTP ${i} error`,i,a,s))})}else e(new va(xi(t),t,s))},$l=(t,e,r,s)=>{const n={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||t==="HEAD"||!s?Y(Y({},n),r):(Pl(s)?(n.headers=Y({"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),Y(Y({},n),r))};async function as(t,e,r,s,n,i,a){return new Promise((o,c)=>{t(r,$l(e,s,n,i)).then(u=>{if(!u.ok)throw u;if(s!=null&&s.noResolveJson)return u;if(a==="vectors"){const d=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>o(u)).catch(u=>Ll(u,c,s,a))})}function wa(t="storage"){return{get:async(e,r,s,n)=>as(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>as(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>as(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>as(e,"HEAD",r,Y(Y({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>as(e,"DELETE",r,n,i,s,t)}}const Dl=wa("storage"),{get:ys,post:jt,put:An,head:Ul,remove:Zn}=Dl,pt=wa("vectors");var rs=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Ol(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=Y(Y({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(nn(r))return{data:null,error:r};throw r}}},Ml=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(nn(e))return{data:null,error:e};throw e}}};let xa;xa=Symbol.toStringTag;var Wl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[xa]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ml(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(nn(e))return{data:null,error:e};throw e}}};const ql={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_i={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var zl=class extends rs{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=Y(Y({},_i),s);let o=Y(Y({},n.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const c=a.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",n.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),c&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(c))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,c&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(c))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s!=null&&s.headers&&(o=Y(Y({},o),s.headers));const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),h=await(t=="PUT"?An:jt)(n.fetch,`${n.url}/object/${d}`,i,Y({headers:o},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{path:u,id:h.Id,fullPath:h.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;const i=n._removeEmptyFolders(t),a=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),n.handleOperation(async()=>{let c;const u=Y(Y({},_i),s),d=Y(Y({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",u.cacheControl)):(c=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType),{path:i,fullPath:(await An(n.fetch,o.toString(),c,{headers:d})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=Y({},r.headers);e!=null&&e.upsert&&(n["x-upsert"]="true");const i=await jt(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new sn("No token returned by API");return{signedUrl:a.toString(),path:t,token:o}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await jt(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 jt(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t);const i=typeof(r==null?void 0:r.transform)=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await jt(s.fetch,`${s.url}/object/sign/${n}`,Y({expiresIn:e},i?{transform:r.transform}:{}),{headers:s.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"",c=i&&a.signedURL.includes("/object/sign/")?a.signedURL.replace("/object/sign/","/render/image/sign/"):a.signedURL;return{signedUrl:encodeURI(`${s.url}${c}${o}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await jt(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=>Y(Y({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${i}`):null}))})}download(t,e,r){const s=typeof(e==null?void 0:e.transform)<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),i=n?`?${n}`:"",a=this._getFinalPath(t),o=()=>ys(this.fetch,`${this.url}/${s}/${a}${i}`,{headers:this.headers,noResolveJson:!0},r);return new Wl(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>Cn(await ys(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await Ul(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(nn(n)){var s;const i=n instanceof Rn?n.status:n instanceof va?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=[],n=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&s.push(n);const i=typeof(e==null?void 0:e.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});a!==""&&s.push(a);let o=s.join("&");return o!==""&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${o}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await Zn(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=Y(Y(Y({},ql),e),{},{prefix:t||""});return await jt(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=Y({},t);return await jt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}};const Hl="2.101.1",As={"X-Client-Info":`storage-js/${Hl}`};var Kl=class extends rs{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=Y(Y({},As),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await ys(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await ys(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await jt(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await An(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await jt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Zn(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Vl=class extends rs{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=Y(Y({},As),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await jt(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 ys(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Zn(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Il(t))throw new sn("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new Al({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){const a=n[i];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(n,o),error:null}}catch(c){if(s)throw c;return{data:null,error:c}}}}})}},Gl=class extends rs{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=Y(Y({},As),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await pt.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await pt.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await pt.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await pt.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Jl=class extends rs{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=Y(Y({},As),{},{"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 pt.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await pt.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 pt.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await pt.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 pt.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Ql=class extends rs{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=Y(Y({},As),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await pt.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await pt.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await pt.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await pt.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Yl=class extends Ql{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Xl(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)}},Xl=class extends Gl{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,Y(Y({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,Y(Y({},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 Zl(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Zl=class extends Jl{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,Y(Y({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,Y(Y({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,Y(Y({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,Y(Y({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,Y(Y({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},ec=class extends Kl{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new zl(this.url,this.headers,t,this.fetch)}get vectors(){return new Yl(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Vl(this.url+"/iceberg",this.headers,this.fetch)}};const _a="2.101.1",Ur=30*1e3,On=3,pn=On*Ur,tc="http://localhost:9999",rc="supabase.auth.token",sc={"X-Client-Info":`gotrue-js/${_a}`},Pn="X-Supabase-Api-Version",ka={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},nc=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,ic=10*60*1e3;class vs extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function q(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class ac extends vs{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function oc(t){return q(t)&&t.name==="AuthApiError"}class br extends vs{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class Gt extends vs{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class ht extends Gt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function gn(t){return q(t)&&t.name==="AuthSessionMissingError"}class Ir extends Gt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class qs extends Gt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class zs extends Gt{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 lc(t){return q(t)&&t.name==="AuthImplicitGrantRedirectError"}class ki extends Gt{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 cc extends Gt{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 In extends Gt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function bn(t){return q(t)&&t.name==="AuthRetryableFetchError"}class Si extends Gt{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class Nn extends Gt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Qs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ei=`
|
|
57
|
+
\r=`.split(""),uc=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Ei.length;e+=1)t[Ei[e].charCodeAt(0)]=-2;for(let e=0;e<Qs.length;e+=1)t[Qs[e].charCodeAt(0)]=e;return t})();function ji(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(Qs[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(Qs[s]),e.queuedBits-=6}}function Sa(t,e,r){const s=uc[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 Ti(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{fc(a,s,r)};for(let a=0;a<t.length;a+=1)Sa(t.charCodeAt(a),n,i);return e.join("")}function dc(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 hc(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}dc(s,e)}}function fc(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 qr(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)Sa(t.charCodeAt(n),r,s);return new Uint8Array(e)}function pc(t){const e=[];return hc(t,r=>e.push(r)),new Uint8Array(e)}function mr(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>ji(n,r,s)),ji(null,r,s),e.join("")}function gc(t){return Math.round(Date.now()/1e3)+t}function bc(){return Symbol("auth-callback")}const He=()=>typeof window<"u"&&typeof document<"u",fr={tested:!1,writable:!1},Ea=()=>{if(!He())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(fr.tested)return fr.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),fr.tested=!0,fr.writable=!0}catch{fr.tested=!0,fr.writable=!1}return fr.writable};function mc(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 ja=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),yc=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Mr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},pr=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},ze=async(t,e)=>{await t.removeItem(e)};class an{constructor(){this.promise=new an.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}an.promiseConstructor=Promise;function Hs(t){const e=t.split(".");if(e.length!==3)throw new Nn("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!nc.test(e[s]))throw new Nn("JWT not in base64url format");return{header:JSON.parse(Ti(e[0])),payload:JSON.parse(Ti(e[1])),signature:qr(e[2]),raw:{header:e[0],payload:e[1]}}}async function vc(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function wc(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 xc(t){return("0"+t.toString(16)).substr(-2)}function _c(){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,xc).join("")}async function kc(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 Sc(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 kc(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Nr(t,e,r=!1){const s=_c();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await Mr(t,`${e}-code-verifier`,n);const i=await Sc(s);return[i,s===i?"plain":"s256"]}const Ec=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function jc(t){const e=t.headers.get(Pn);if(!e||!e.match(Ec))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Tc(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 Rc(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 Cc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Fr(t){if(!Cc.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function mn(){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 Ac(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 Ri(t){return JSON.parse(JSON.stringify(t))}const gr=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Oc=[502,503,504];async function Ci(t){var e;if(!yc(t))throw new In(gr(t),0);if(Oc.includes(t.status))throw new In(gr(t),t.status);let r;try{r=await t.json()}catch(i){throw new br(gr(i),i)}let s;const n=jc(t);if(n&&n.getTime()>=ka["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 Si(gr(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new ht}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 Si(gr(r),t.status,r.weak_password.reasons);throw new ac(gr(r),t.status||500,s)}const Pc=(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 J(t,e,r,s){var n;const i=Object.assign({},s==null?void 0:s.headers);i[Pn]||(i[Pn]=ka["2024-01-01"].name),s!=null&&s.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const a=(n=s==null?void 0:s.query)!==null&&n!==void 0?n:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await Ic(t,e,r+o,{headers:i,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(c):{data:Object.assign({},c),error:null}}async function Ic(t,e,r,s,n,i){const a=Pc(e,s,n,i);let o;try{o=await t(r,Object.assign({},a))}catch(c){throw console.error(c),new In(gr(c),0)}if(o.ok||await Ci(o),s!=null&&s.noResolveJson)return o;try{return await o.json()}catch(c){await Ci(c)}}function Et(t){var e;let r=null;Bc(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=gc(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function Ai(t){const e=Et(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 tr(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Nc(t){return{data:t,error:null}}function Fc(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=rn(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},c=Object.assign({},a);return{data:{properties:o,user:c},error:null}}function Oi(t){return t}function Bc(t){return t.access_token&&t.refresh_token&&t.expires_in}const yn=["global","local","others"];class Lc{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=ja(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,r=yn[0]){if(yn.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${yn.join(", ")}`);try{return await J(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(q(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await J(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:tr})}catch(s){if(q(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=rn(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s==null?void 0:s.newEmail,delete n.newEmail),await J(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Fc,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(q(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await J(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:tr})}catch(r){if(q(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,a,o,c;try{const u={nextPage:null,lastPage:0,total:0},d=await J(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:Oi});if(d.error)throw d.error;const h=await d.json(),p=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(c=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(y=>{const b=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(y.split(";")[1].split("=")[1]);u[`${m}Page`]=b}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(q(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Fr(e);try{return await J(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:tr})}catch(r){if(q(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Fr(e);try{return await J(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:tr})}catch(s){if(q(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){Fr(e);try{return await J(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:tr})}catch(s){if(q(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Fr(e.userId);try{const{data:r,error:s}=await J(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(q(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Fr(e.userId),Fr(e.id);try{return{data:await J(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(q(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,a,o,c;try{const u={nextPage:null,lastPage:0,total:0},d=await J(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:Oi});if(d.error)throw d.error;const h=await d.json(),p=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(c=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(y=>{const b=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(y.split(";")[1].split("=")[1]);u[`${m}Page`]=b}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(q(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await J(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(q(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await J(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(q(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await J(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(q(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await J(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(q(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await J(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(q(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e!=null&&e.type&&(r.type=e.type),await J(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s==null?void 0:s.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(q(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await J(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(q(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await J(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(q(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await J(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(q(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await J(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(q(r))return{data:null,error:r};throw r}}}function Pi(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const Pt={debug:!!(globalThis&&Ea()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Ta extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Ii extends Ta{}async function $c(t,e,r){Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;let n;e>0&&(n=setTimeout(()=>{s.abort(),Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){clearTimeout(n),Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Ii(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Pt.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(n),await r()}})}catch(i){if(e>0&&clearTimeout(n),(i==null?void 0:i.name)==="AbortError"&&e>0){if(s.signal.aborted)return Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async a=>{if(a){Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,a.name);try{return await r()}finally{Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,a.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Ii(`Lock "${t}" was released because another request stole it`)}throw i}}function Dc(){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 Ra(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Uc(t){return parseInt(t,16)}function Mc(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Wc(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:c,resources:u,scheme:d,uri:h,version:p}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
58
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const f=Ra(t.address),y=d?`${d}://${s}`:s,b=t.statement?`${t.statement}
|
|
59
|
+
`:"",m=`${y} wants you to sign in with your Ethereum account:
|
|
60
60
|
${f}
|
|
61
61
|
|
|
62
|
-
${
|
|
63
|
-
Version: ${
|
|
62
|
+
${b}`;let k=`URI: ${h}
|
|
63
|
+
Version: ${p}
|
|
64
64
|
Chain ID: ${r}${a?`
|
|
65
65
|
Nonce: ${a}`:""}
|
|
66
66
|
Issued At: ${i.toISOString()}`;if(n&&(k+=`
|
|
67
67
|
Expiration Time: ${n.toISOString()}`),o&&(k+=`
|
|
68
68
|
Not Before: ${o.toISOString()}`),c&&(k+=`
|
|
69
|
-
Request ID: ${c}`),u){let
|
|
70
|
-
Resources:`;for(const
|
|
71
|
-
- ${
|
|
72
|
-
${k}`}class Fe 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 Gs extends Fe{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function Bc({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 Fe({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 Fe({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 Fe({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 Fe({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 Fe({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Fe({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new Fe({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Fe({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(Ea(a)){if(i.rp.id!==a)return new Fe({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Fe({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 Fe({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 Fe({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 Fe({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Fc({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 Fe({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Fe({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(Ea(s)){if(r.rpId!==s)return new Fe({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Fe({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Fe({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 Fe({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class Lc{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 $c=new Lc;function Dc(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=Zs(t,["challenge","user","excludeCredentials"]),i=Mr(e).buffer,a=Object.assign(Object.assign({},r),{id:Mr(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let c=0;c<s.length;c++){const u=s[c];o.excludeCredentials[c]=Object.assign(Object.assign({},u),{id:Mr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function Uc(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=Zs(t,["challenge","allowCredentials"]),n=Mr(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const o=r[a];i.allowCredentials[a]=Object.assign(Object.assign({},o),{id:Mr(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return i}function Mc(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:hr(new Uint8Array(t.response.attestationObject)),clientDataJSON:hr(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Wc(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:hr(new Uint8Array(n.authenticatorData)),clientDataJSON:hr(new Uint8Array(n.clientDataJSON)),signature:hr(new Uint8Array(n.signature)),userHandle:n.userHandle?hr(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Ea(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Ai(){var t,e;return!!(He()&&"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 qc(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Gs("Browser returned unexpected credential type",e)}:{data:null,error:new Gs("Empty credential response",e)}}catch(e){return{data:null,error:Bc({error:e,options:t})}}}async function Hc(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Gs("Browser returned unexpected credential type",e)}:{data:null,error:new Gs("Empty credential response",e)}}catch(e){return{data:null,error:Fc({error:e,options:t})}}}const zc={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Kc={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Js(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const i in n){const a=n[i];if(a!==void 0)if(Array.isArray(a))s[i]=a;else if(r(a))s[i]=a;else if(e(a)){const o=s[i];e(o)?s[i]=Js(o,a):s[i]=Js(a)}else s[i]=a}return s}function Vc(t,e){return Js(zc,t,e||{})}function Gc(t,e){return Js(Kc,t,e||{})}class Jc{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},i){var a;try{const{data:o,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:c};const u=n??$c.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:d}=o.webauthn.credential_options.publicKey;if(!d.name){const h=s;if(h)d.name=`${d.id}:${h}`;else{const f=(await this.client.getUser()).data.user,y=((a=f==null?void 0:f.user_metadata)===null||a===void 0?void 0:a.name)||(f==null?void 0:f.email)||(f==null?void 0:f.id)||"User";d.name=`${d.id}:${y}`}}d.displayName||(d.displayName=d.name)}switch(o.webauthn.type){case"create":{const d=Vc(o.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:h,error:g}=await qc({publicKey:d,signal:u});return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:g}}case"request":{const d=Gc(o.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:g}=await Hc(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:d,signal:u}));return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:g}}}}catch(o){return V(o)?{data:null,error:o}:{data:null,error:new dr("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new bs("rpId is required for WebAuthn authentication")};try{if(!Ai())return{data:null,error:new dr("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!a)return{data:null,error:o};const{webauthn:c}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:s,credential_response:c.credential_response}})}catch(a){return V(a)?{data:null,error:a}:{data:null,error:new dr("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 bs("rpId is required for WebAuthn registration")};try{if(!Ai())return{data:null,error:new dr("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(d=>{var h;return(h=d.data)===null||h===void 0?void 0:h.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d==null?void 0:d.id}):void 0),{data:null,error:o};const{data:c,error:u}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return c?this._verify({factorId:a.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(a){return V(a)?{data:null,error:a}:{data:null,error:new dr("Unexpected error in register",a)}}}}Oc();const Qc={url:Vl,storageKey:Gl,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Jl,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Oi(t,e,r){return await r()}const Ir={};class ys{get jwks(){var e,r;return(r=(e=Ir[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Ir[this.storageKey]=Object.assign(Object.assign({},Ir[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Ir[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ir[this.storageKey]=Object.assign(Object.assign({},Ir[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({},Qc),e);if(this.storageKey=i.storageKey,this.instanceID=(r=ys.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,ys.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&He()){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 Cc({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=_a(i.fetch),this.lock=i.lock||Oi,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&&He()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=Ac:this.lock=Oi,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 Jc(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:xa()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Ri(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Ri(this.memoryStorage)),He()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}i.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ya}) ${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(He()&&(r=cc(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),He()&&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),ec(i)){const c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:a,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return V(r)?this._returnResult({error:r}):this._returnResult({error:new dr("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await X(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:bt}),{data:a,error:o}=i;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(V(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){const{email:d,password:h,options:g}=e;let f=null,y=null;this.flowType==="pkce"&&([f,y]=await Pr(this.storage,this.storageKey)),i=await X(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:d,password:h,data:(r=g==null?void 0:g.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:f,code_challenge_method:y},xform:bt})}else if("phone"in e){const{phone:d,password:h,options:g}=e;i=await X(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(s=g==null?void 0:g.data)!==null&&s!==void 0?s:{},channel:(n=g==null?void 0:g.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:bt})}else throw new Us("You must provide either an email or phone number and a password");const{data:a,error:o}=i;if(o||!a)return await qe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(await qe(this.storage,`${this.storageKey}-code-verifier`),V(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:o}=e;r=await X(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:ji})}else if("phone"in e){const{phone:i,password:a,options:o}=e;r=await X(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:ji})}else throw new Us("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 Or;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(V(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,a,o,c,u,d,h,g;let f,y;if("message"in e)f=e.message,y=e.signature;else{const{chain:m,wallet:_,statement:k,options:x}=e;let j;if(He())if(typeof _=="object")j=_;else{const O=window;if("ethereum"in O&&typeof O.ethereum=="object"&&"request"in O.ethereum&&typeof O.ethereum.request=="function")j=O.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof _!="object"||!(x!=null&&x.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");j=_}const w=new URL((r=x==null?void 0:x.url)!==null&&r!==void 0?r:window.location.href),A=await j.request({method:"eth_requestAccounts"}).then(O=>O).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!A||A.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const T=Sa(A[0]);let R=(s=x==null?void 0:x.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!R){const O=await j.request({method:"eth_chainId"});R=Pc(O)}const E={domain:w.host,address:T,statement:k,uri:w.href,version:"1",chainId:R,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:(o=x==null?void 0:x.signInWithEthereum)===null||o===void 0?void 0:o.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};f=Ic(E),y=await j.request({method:"personal_sign",params:[Nc(f),T]})}try{const{data:m,error:_}=await X(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:y},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:bt});if(_)throw _;if(!m||!m.session||!m.user){const k=new Or;return this._returnResult({data:{user:null,session:null},error:k})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:_})}catch(m){if(V(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(e){var r,s,n,i,a,o,c,u,d,h,g,f;let y,m;if("message"in e)y=e.message,m=e.signature;else{const{chain:_,wallet:k,statement:x,options:j}=e;let w;if(He())if(typeof k=="object")w=k;else{const T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))w=T.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof k!="object"||!(j!=null&&j.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=k}const A=new URL((r=j==null?void 0:j.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in w&&w.signIn){const T=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},j==null?void 0:j.signInWithSolana),{version:"1",domain:A.host,uri:A.href}),x?{statement:x}:null));let R;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")R=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)R=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in R&&"signature"in R&&(typeof R.signedMessage=="string"||R.signedMessage instanceof Uint8Array)&&R.signature instanceof Uint8Array)y=typeof R.signedMessage=="string"?R.signedMessage:new TextDecoder().decode(R.signedMessage),m=R.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");y=[`${A.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),...x?["",x,""]:[""],"Version: 1",`URI: ${A.href}`,`Issued At: ${(n=(s=j==null?void 0:j.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=j==null?void 0:j.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${j.signInWithSolana.notBefore}`]:[],...!((a=j==null?void 0:j.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${j.signInWithSolana.expirationTime}`]:[],...!((o=j==null?void 0:j.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${j.signInWithSolana.chainId}`]:[],...!((c=j==null?void 0:j.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${j.signInWithSolana.nonce}`]:[],...!((u=j==null?void 0:j.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${j.signInWithSolana.requestId}`]:[],...!((h=(d=j==null?void 0:j.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...j.signInWithSolana.resources.map(R=>`- ${R}`)]:[]].join(`
|
|
73
|
-
`);const T=await w.signMessage(new TextEncoder().encode(y),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=T}}try{const{data:_,error:k}=await X(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:hr(m)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:bt});if(k)throw k;if(!_||!_.session||!_.user){const x=new Or;return this._returnResult({data:{user:null,session:null},error:x})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:k})}catch(_){if(V(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){const r=await cr(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new tc;const{data:i,error:a}=await X(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:bt});if(await qe(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const o=new Or;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:a})}catch(i){if(await qe(this.storage,`${this.storageKey}-code-verifier`),V(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,o=await X(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:bt}),{data:c,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){const d=new Or;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(V(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;try{if("email"in e){const{email:o,options:c}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Pr(this.storage,this.storageKey));const{error:h}=await X(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(s=c==null?void 0:c.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:o,options:c}=e,{data:u,error:d}=await X(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:d})}throw new Us("You must provide either an email or phone number.")}catch(o){if(await qe(this.storage,`${this.storageKey}-code-verifier`),V(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:o}=await X(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:bt});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const c=a.session,u=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(n){if(V(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,a;try{let o=null,c=null;this.flowType==="pkce"&&([o,c]=await Pr(this.storage,this.storageKey));const u=await X(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:c}),headers:this.headers,xform:jc});return!((i=u.data)===null||i===void 0)&&i.url&&He()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await qe(this.storage,`${this.storageKey}-code-verifier`),V(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new at;const{error:n}=await X(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(V(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 X(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:a,error:o}=await X(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o})}throw new Us("You must provide either an email or phone number and a type")}catch(r){if(V(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 cr(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()<un:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await cr(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=fn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=_c(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 X(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Kt}):await this._useSession(async r=>{var s,n,i;const{data:a,error:o}=r;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new at}:await X(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:Kt})})}catch(r){if(V(r))return dn(r)&&(await this._removeSession(),await qe(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 at;const a=n.session;let o=null,c=null;this.flowType==="pkce"&&e.email!=null&&([o,c]=await Pr(this.storage,this.storageKey));const{data:u,error:d}=await X(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:c}),jwt:a.access_token,xform:Kt});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 qe(this.storage,`${this.storageKey}-code-verifier`),V(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 at;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Ws(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:o,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(V(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:a,error:o}=r;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new at;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(V(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!He())throw new Ms("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ms(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 vi("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ms("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 vi("No code detected.");const{data:x,error:j}=await this._exchangeCodeForSession(e.code);if(j)throw j;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.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:o,expires_at:c,token_type:u}=e;if(!i||!o||!a||!u)throw new Ms("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(o);let g=d+h;c&&(g=parseInt(c));const f=g-d;f*1e3<=$r&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const y=g-h;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,g,d):d-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,g,d);const{data:m,error:_}=await this._getUser(i);if(_)throw _;const k={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:h,expires_at:g,refresh_token:a,token_type:u,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(s){if(V(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 cr(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&&!dn(i))return this._returnResult({error:i});const a=(s=n.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!(Zl(o)&&(o.status===404||o.status===401||o.status===403)||dn(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await qe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=lc(),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 Pr(this.storage,this.storageKey,!0));try{return await X(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 qe(this.storage,`${this.storageKey}-code-verifier`),V(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(V(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async i=>{var a,o,c,u,d;const{data:h,error:g}=i;if(g)throw g;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await X(this.fetch,"GET",f,{headers:this.headers,jwt:(d=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return He()&&!(!((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(V(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:o,token:c,access_token:u,nonce:d}=e,h=await X(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:c,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:bt}),{data:g,error:f}=h;return f?this._returnResult({data:{user:null,session:null},error:f}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new Or}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:f}))}catch(n){if(await qe(this.storage,`${this.storageKey}-code-verifier`),V(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 X(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(V(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 hc(async n=>(n>0&&await dc(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await X(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:bt})),(n,i)=>{const a=200*Math.pow(2,n);return i&&hn(i)&&Date.now()+a-s<$r})}catch(s){if(this._debug(r,"error",s),V(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),He()&&!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 cr(this.storage,this.storageKey);if(n&&this.userStorage){let a=await cr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await Dr(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:fn()}else if(n&&!n.user&&!n.user){const a=await cr(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await qe(this.storage,this.storageKey+"-user"),await Dr(this.storage,this.storageKey,n)):n.user=fn()}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()<un;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${un}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),hn(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(n.access_token);!o&&(a!=null&&a.user)?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new at;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new rn;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new at;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const o={data:i.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(i){if(this._debug(n,"error",i),V(i)){const a={data:null,error:i};return hn(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(c){i.push(c)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await qe(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 Dr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=Si(n);await Dr(this.storage,this.storageKey,i)}else{const n=Si(r);await Dr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await qe(this.storage,this.storageKey),await qe(this.storage,this.storageKey+"-code-verifier"),await qe(this.storage,this.storageKey+"-user"),this.userStorage&&await qe(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&He()&&(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(),$r);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)/$r);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${$r}ms, refresh threshold is ${Tn} ticks`),n<=Tn&&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 ka)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!He()||!(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 Pr(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});n.push(o.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await X(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(V(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await X(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c==null?void 0:c.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(V(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"?Mc(e.webauthn.credential_response):Wc(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:c}=await X(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:c}))})}catch(r){if(V(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 X(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:o}=a;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Dc(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Uc(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(V(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:f}=Ws(e);let y=null;f.aal&&(y=f.aal);let m=y;const{data:{user:_},error:k}=await this.getUser(e);if(k)return this._returnResult({data:null,error:k});((s=(r=_==null?void 0:_.factors)===null||r===void 0?void 0:r.filter(w=>w.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(m="aal2");const j=f.amr||[];return{data:{currentLevel:y,nextLevel:m,currentAuthenticationMethods:j},error:null}}catch(f){if(V(f))return this._returnResult({data:null,error:f});throw f}const{data:{session:a},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=Ws(a.access_token);let u=null;c.aal&&(u=c.aal);let d=u;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const g=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:g},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await X(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 at})})}catch(r){if(V(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 at});const a=await X(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&He()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(V(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 at});const a=await X(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&He()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(V(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 X(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 at})})}catch(e){if(V(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 X(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 at})})}catch(r){if(V(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+Yl>n)return s;const{data:i,error:a}=await X(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:f,error:y}=await this.getSession();if(y||!f.session)return this._returnResult({data:null,error:y});s=f.session.access_token}const{header:n,payload:i,signature:a,raw:{header:o,payload:c}}=Ws(s);r!=null&&r.allowExpired||vc(i.exp);const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!u){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:n,signature:a},error:null}}const d=wc(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,ac(`${o}.${c}`)))throw new An("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(V(s))return this._returnResult({data:null,error:s});throw s}}}ys.nextInstanceID={};const Yc=ys,Xc="2.101.0";let as="";typeof Deno<"u"?as="deno":typeof document<"u"?as="web":typeof navigator<"u"&&navigator.product==="ReactNative"?as="react-native":as="node";const Zc={"X-Client-Info":`supabase-js-${as}/${Xc}`},eu={headers:Zc},tu={schema:"public"},ru={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},su={};function vs(t){"@babel/helpers - typeof";return vs=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},vs(t)}function nu(t,e){if(vs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(vs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function iu(t){var e=nu(t,"string");return vs(e)=="symbol"?e:e+""}function au(t,e,r){return(e=iu(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Pi(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function Pe(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Pi(Object(r),!0).forEach(function(s){au(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Pi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const ou=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),lu=()=>Headers,cu=(t,e,r)=>{const s=ou(r),n=lu();return async(i,a)=>{var o;const c=(o=await e())!==null&&o!==void 0?o:t;let u=new n(a==null?void 0:a.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(i,Pe(Pe({},a),{},{headers:u}))}};function uu(t){return t.endsWith("/")?t:t+"/"}function du(t,e){var r,s;const{db:n,auth:i,realtime:a,global:o}=t,{db:c,auth:u,realtime:d,global:h}=e,g={db:Pe(Pe({},c),n),auth:Pe(Pe({},u),i),realtime:Pe(Pe({},d),a),storage:{},global:Pe(Pe(Pe({},h),o),{},{headers:Pe(Pe({},(r=h==null?void 0:h.headers)!==null&&r!==void 0?r:{}),(s=o==null?void 0:o.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?g.accessToken=t.accessToken:delete g.accessToken,g}function hu(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(uu(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var fu=class extends Yc{constructor(t){super(t)}},pu=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=hu(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:tu,realtime:su,auth:Pe(Pe({},ru),{},{storageKey:a}),global:eu},c=du(r??{},o);if(this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=c.auth)!==null&&u!==void 0?u:{},this.headers,c.global.fetch)}this.fetch=cu(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Pe({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 Kl(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new Ro(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:c,throwOnError:u},d,h){const g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new fu({url:this.authUrl.href,headers:Pe(Pe({},g),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:c,throwOnError:u,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new ml(this.realtimeUrl.href,Pe(Pe({},t),{},{params:Pe(Pe({},{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 On=(t,e,r)=>new pu(t,e,r);function gu(){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}gu()&&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 As=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(){}},pr,Vt,Wr,Zi,mu=(Zi=class extends As{constructor(){super();te(this,pr);te(this,Vt);te(this,Wr);W(this,Wr,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){v(this,Vt)||this.setEventListener(v(this,Wr))}onUnsubscribe(){var e;this.hasListeners()||((e=v(this,Vt))==null||e.call(this),W(this,Vt,void 0))}setEventListener(e){var r;W(this,Wr,e),(r=v(this,Vt))==null||r.call(this),W(this,Vt,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){v(this,pr)!==e&&(W(this,pr,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof v(this,pr)=="boolean"?v(this,pr):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},pr=new WeakMap,Vt=new WeakMap,Wr=new WeakMap,Zi),Qn=new mu,bu={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},St,gr,ea,yu=(ea=class{constructor(){te(this,St,bu);te(this,gr,!1)}setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&v(this,gr)&&t!==v(this,St)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:v(this,St),provider:t}),W(this,St,t),process.env.NODE_ENV!=="production"&&W(this,gr,!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&W(this,gr,!0),v(this,St).setTimeout(t,e)}clearTimeout(t){v(this,St).clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&W(this,gr,!0),v(this,St).setInterval(t,e)}clearInterval(t){v(this,St).clearInterval(t)}},St=new WeakMap,gr=new WeakMap,ea),fr=new yu;function vu(t){setTimeout(t,0)}var wu=typeof window>"u"||"Deno"in globalThis;function rt(){}function xu(t,e){return typeof t=="function"?t(e):t}function Pn(t){return typeof t=="number"&&t>=0&&t!==1/0}function ja(t,e){return Math.max(t+(e||0)-Date.now(),0)}function er(t,e){return typeof t=="function"?t(e):t}function ht(t,e){return typeof t=="function"?t(e):t}function Ni(t,e){const{type:r="all",exact:s,fetchStatus:n,predicate:i,queryKey:a,stale:o}=t;if(a){if(s){if(e.queryHash!==Yn(a,e.options))return!1}else if(!xs(e.queryKey,a))return!1}if(r!=="all"){const c=e.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof o=="boolean"&&e.isStale()!==o||n&&n!==e.state.fetchStatus||i&&!i(e))}function Ii(t,e){const{exact:r,status:s,predicate:n,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(r){if(ws(e.options.mutationKey)!==ws(i))return!1}else if(!xs(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||n&&!n(e))}function Yn(t,e){return((e==null?void 0:e.queryKeyHashFn)||ws)(t)}function ws(t){return JSON.stringify(t,(e,r)=>Bn(r)?Object.keys(r).sort().reduce((s,n)=>(s[n]=r[n],s),{}):r)}function xs(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>xs(t[r],e[r])):!1}var _u=Object.prototype.hasOwnProperty;function Nn(t,e,r=0){if(t===e)return t;if(r>500)return e;const s=Bi(t)&&Bi(e);if(!s&&!(Bn(t)&&Bn(e)))return e;const i=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),o=a.length,c=s?new Array(o):{};let u=0;for(let d=0;d<o;d++){const h=s?d:a[d],g=t[h],f=e[h];if(g===f){c[h]=g,(s?d<i:_u.call(t,h))&&u++;continue}if(g===null||f===null||typeof g!="object"||typeof f!="object"){c[h]=f;continue}const y=Nn(g,f,r+1);c[h]=y,y===g&&u++}return i===o&&u===i?t:c}function In(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 Bi(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function Bn(t){if(!Fi(t))return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(!Fi(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function Fi(t){return Object.prototype.toString.call(t)==="[object Object]"}function ku(t){return new Promise(e=>{fr.setTimeout(e,t)})}function Fn(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 Nn(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 Nn(t,e)}return e}function Su(t,e,r=0){const s=[...t,e];return r&&s.length>r?s.slice(1):s}function Eu(t,e,r=0){const s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}var Qs=Symbol();function Ta(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===Qs&&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===Qs?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function Ra(t,e){return typeof t=="function"?t(...e):!!t}function ju(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 _s=(()=>{let t=()=>wu;return{isServer(){return t()},setIsServer(e){t=e}}})();function Ln(){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 Tu=vu;function Ru(){let t=[],e=0,r=o=>{o()},s=o=>{o()},n=Tu;const i=o=>{e?t.push(o):n(()=>{r(o)})},a=()=>{const o=t;t=[],o.length&&n(()=>{s(()=>{o.forEach(c=>{r(c)})})})};return{batch:o=>{let c;e++;try{c=o()}finally{e--,e||a()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{r=o},setBatchNotifyFunction:o=>{s=o},setScheduler:o=>{n=o}}}var ze=Ru(),qr,Gt,Hr,ta,Cu=(ta=class extends As{constructor(){super();te(this,qr,!0);te(this,Gt);te(this,Hr);W(this,Hr,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",s)}}})}onSubscribe(){v(this,Gt)||this.setEventListener(v(this,Hr))}onUnsubscribe(){var e;this.hasListeners()||((e=v(this,Gt))==null||e.call(this),W(this,Gt,void 0))}setEventListener(e){var r;W(this,Hr,e),(r=v(this,Gt))==null||r.call(this),W(this,Gt,e(this.setOnline.bind(this)))}setOnline(e){v(this,qr)!==e&&(W(this,qr,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return v(this,qr)}},qr=new WeakMap,Gt=new WeakMap,Hr=new WeakMap,ta),Ys=new Cu;function Au(t){return Math.min(1e3*2**t,3e4)}function Ca(t){return(t??"online")==="online"?Ys.isOnline():!0}var $n=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function Aa(t){let e=!1,r=0,s;const n=Ln(),i=()=>n.status!=="pending",a=m=>{var _;if(!i()){const k=new $n(m);g(k),(_=t.onCancel)==null||_.call(t,k)}},o=()=>{e=!0},c=()=>{e=!1},u=()=>Qn.isFocused()&&(t.networkMode==="always"||Ys.isOnline())&&t.canRun(),d=()=>Ca(t.networkMode)&&t.canRun(),h=m=>{i()||(s==null||s(),n.resolve(m))},g=m=>{i()||(s==null||s(),n.reject(m))},f=()=>new Promise(m=>{var _;s=k=>{(i()||u())&&m(k)},(_=t.onPause)==null||_.call(t)}).then(()=>{var m;s=void 0,i()||(m=t.onContinue)==null||m.call(t)}),y=()=>{if(i())return;let m;const _=r===0?t.initialPromise:void 0;try{m=_??t.fn()}catch(k){m=Promise.reject(k)}Promise.resolve(m).then(h).catch(k=>{var T;if(i())return;const x=t.retry??(_s.isServer()?0:3),j=t.retryDelay??Au,w=typeof j=="function"?j(r,k):j,A=x===!0||typeof x=="number"&&r<x||typeof x=="function"&&x(r,k);if(e||!A){g(k);return}r++,(T=t.onFail)==null||T.call(t,r,k),ku(w).then(()=>u()?void 0:f()).then(()=>{e?g(k):y()})})};return{promise:n,status:()=>n.status,cancel:a,continue:()=>(s==null||s(),n),cancelRetry:o,continueRetry:c,canStart:d,start:()=>(d()?y():f().then(y),n)}}var mr,ra,Oa=(ra=class{constructor(){te(this,mr)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Pn(this.gcTime)&&W(this,mr,fr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(_s.isServer()?1/0:5*60*1e3))}clearGcTimeout(){v(this,mr)&&(fr.clearTimeout(v(this,mr)),W(this,mr,void 0))}},mr=new WeakMap,ra),br,zr,dt,yr,Me,Ss,vr,ot,Pa,Ot,sa,Ou=(sa=class extends Oa{constructor(e){super();te(this,ot);te(this,br);te(this,zr);te(this,dt);te(this,yr);te(this,Me);te(this,Ss);te(this,vr);W(this,vr,!1),W(this,Ss,e.defaultOptions),this.setOptions(e.options),this.observers=[],W(this,yr,e.client),W(this,dt,v(this,yr).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,W(this,br,$i(this.options)),this.state=e.state??v(this,br),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=v(this,Me))==null?void 0:e.promise}setOptions(e){if(this.options={...v(this,Ss),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=$i(this.options);r.data!==void 0&&(this.setState(Li(r.data,r.dataUpdatedAt)),W(this,br,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&v(this,dt).remove(this)}setData(e,r){const s=Fn(this.state.data,e,this.options);return de(this,ot,Ot).call(this,{data:s,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),s}setState(e,r){de(this,ot,Ot).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var s,n;const r=(s=v(this,Me))==null?void 0:s.promise;return(n=v(this,Me))==null||n.cancel(e),r?r.then(rt).catch(rt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return v(this,br)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>ht(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Qs||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>er(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:!ja(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=v(this,Me))==null||r.continue()}onOnline(){var r;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=v(this,Me))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),v(this,dt).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(v(this,Me)&&(v(this,vr)||de(this,ot,Pa).call(this)?v(this,Me).cancel({revert:!0}):v(this,Me).cancelRetry()),this.scheduleGc()),v(this,dt).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||de(this,ot,Ot).call(this,{type:"invalidate"})}async fetch(e,r){var c,u,d,h,g,f,y,m,_,k,x,j;if(this.state.fetchStatus!=="idle"&&((c=v(this,Me))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(v(this,Me))return v(this,Me).continueRetry(),v(this,Me).promise}if(e&&this.setOptions(e),!this.options.queryFn){const w=this.observers.find(A=>A.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:()=>(W(this,vr,!0),s.signal)})},i=()=>{const w=Ta(this.options,r),T=(()=>{const R={client:v(this,yr),queryKey:this.queryKey,meta:this.meta};return n(R),R})();return W(this,vr,!1),this.options.persister?this.options.persister(w,T,this):w(T)},o=(()=>{const w={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:v(this,yr),state:this.state,fetchFn:i};return n(w),w})();(u=this.options.behavior)==null||u.onFetch(o,this),W(this,zr,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=o.fetchOptions)==null?void 0:d.meta))&&de(this,ot,Ot).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta}),W(this,Me,Aa({initialPromise:r==null?void 0:r.initialPromise,fn:o.fetchFn,onCancel:w=>{w instanceof $n&&w.revert&&this.setState({...v(this,zr),fetchStatus:"idle"}),s.abort()},onFail:(w,A)=>{de(this,ot,Ot).call(this,{type:"failed",failureCount:w,error:A})},onPause:()=>{de(this,ot,Ot).call(this,{type:"pause"})},onContinue:()=>{de(this,ot,Ot).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const w=await v(this,Me).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),(f=(g=v(this,dt).config).onSuccess)==null||f.call(g,w,this),(m=(y=v(this,dt).config).onSettled)==null||m.call(y,w,this.state.error,this),w}catch(w){if(w instanceof $n){if(w.silent)return v(this,Me).promise;if(w.revert){if(this.state.data===void 0)throw w;return this.state.data}}throw de(this,ot,Ot).call(this,{type:"error",error:w}),(k=(_=v(this,dt).config).onError)==null||k.call(_,w,this),(j=(x=v(this,dt).config).onSettled)==null||j.call(x,this.state.data,w,this),w}finally{this.scheduleGc()}}},br=new WeakMap,zr=new WeakMap,dt=new WeakMap,yr=new WeakMap,Me=new WeakMap,Ss=new WeakMap,vr=new WeakMap,ot=new WeakSet,Pa=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ot=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,...Na(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...Li(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return W(this,zr,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),ze.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),v(this,dt).notify({query:this,type:"updated",action:e})})},sa);function Na(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ca(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Li(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function $i(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 tt,he,Es,Ze,wr,Kr,It,Jt,js,Vr,Gr,xr,_r,Qt,Jr,ye,os,Dn,Un,Mn,Wn,qn,Hn,zn,Ia,na,Pu=(na=class extends As{constructor(e,r){super();te(this,ye);te(this,tt);te(this,he);te(this,Es);te(this,Ze);te(this,wr);te(this,Kr);te(this,It);te(this,Jt);te(this,js);te(this,Vr);te(this,Gr);te(this,xr);te(this,_r);te(this,Qt);te(this,Jr,new Set);this.options=r,W(this,tt,e),W(this,Jt,null),W(this,It,Ln()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(v(this,he).addObserver(this),Di(v(this,he),this.options)?de(this,ye,os).call(this):this.updateResult(),de(this,ye,Wn).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Kn(v(this,he),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Kn(v(this,he),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,de(this,ye,qn).call(this),de(this,ye,Hn).call(this),v(this,he).removeObserver(this)}setOptions(e){const r=this.options,s=v(this,he);if(this.options=v(this,tt).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ht(this.options.enabled,v(this,he))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");de(this,ye,zn).call(this),v(this,he).setOptions(this.options),r._defaulted&&!In(this.options,r)&&v(this,tt).getQueryCache().notify({type:"observerOptionsUpdated",query:v(this,he),observer:this});const n=this.hasListeners();n&&Ui(v(this,he),s,this.options,r)&&de(this,ye,os).call(this),this.updateResult(),n&&(v(this,he)!==s||ht(this.options.enabled,v(this,he))!==ht(r.enabled,v(this,he))||er(this.options.staleTime,v(this,he))!==er(r.staleTime,v(this,he)))&&de(this,ye,Dn).call(this);const i=de(this,ye,Un).call(this);n&&(v(this,he)!==s||ht(this.options.enabled,v(this,he))!==ht(r.enabled,v(this,he))||i!==v(this,Qt))&&de(this,ye,Mn).call(this,i)}getOptimisticResult(e){const r=v(this,tt).getQueryCache().build(v(this,tt),e),s=this.createResult(r,e);return Iu(this,s)&&(W(this,Ze,s),W(this,Kr,this.options),W(this,wr,v(this,he).state)),s}getCurrentResult(){return v(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&&v(this,It).status==="pending"&&v(this,It).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){v(this,Jr).add(e)}getCurrentQuery(){return v(this,he)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=v(this,tt).defaultQueryOptions(e),s=v(this,tt).getQueryCache().build(v(this,tt),r);return s.fetch().then(()=>this.createResult(s,r))}fetch(e){return de(this,ye,os).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),v(this,Ze)))}createResult(e,r){var O;const s=v(this,he),n=this.options,i=v(this,Ze),a=v(this,wr),o=v(this,Kr),u=e!==s?e.state:v(this,Es),{state:d}=e;let h={...d},g=!1,f;if(r._optimisticResults){const S=this.hasListeners(),C=!S&&Di(e,r),D=S&&Ui(e,s,r,n);(C||D)&&(h={...h,...Na(d.data,e.options)}),r._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:y,errorUpdatedAt:m,status:_}=h;f=h.data;let k=!1;if(r.placeholderData!==void 0&&f===void 0&&_==="pending"){let S;i!=null&&i.isPlaceholderData&&r.placeholderData===(o==null?void 0:o.placeholderData)?(S=i.data,k=!0):S=typeof r.placeholderData=="function"?r.placeholderData((O=v(this,Gr))==null?void 0:O.state.data,v(this,Gr)):r.placeholderData,S!==void 0&&(_="success",f=Fn(i==null?void 0:i.data,S,r),g=!0)}if(r.select&&f!==void 0&&!k)if(i&&f===(a==null?void 0:a.data)&&r.select===v(this,js))f=v(this,Vr);else try{W(this,js,r.select),f=r.select(f),f=Fn(i==null?void 0:i.data,f,r),W(this,Vr,f),W(this,Jt,null)}catch(S){W(this,Jt,S)}v(this,Jt)&&(y=v(this,Jt),f=v(this,Vr),m=Date.now(),_="error");const x=h.fetchStatus==="fetching",j=_==="pending",w=_==="error",A=j&&x,T=f!==void 0,E={status:_,fetchStatus:h.fetchStatus,isPending:j,isSuccess:_==="success",isError:w,isInitialLoading:A,isLoading:A,data:f,dataUpdatedAt:h.dataUpdatedAt,error:y,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:x,isRefetching:x&&!j,isLoadingError:w&&!T,isPaused:h.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:w&&T,isStale:Xn(e,r),refetch:this.refetch,promise:v(this,It),isEnabled:ht(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const S=E.data!==void 0,C=E.status==="error"&&!S,D=H=>{C?H.reject(E.error):S&&H.resolve(E.data)},N=()=>{const H=W(this,It,E.promise=Ln());D(H)},F=v(this,It);switch(F.status){case"pending":e.queryHash===s.queryHash&&D(F);break;case"fulfilled":(C||E.data!==F.value)&&N();break;case"rejected":(!C||E.error!==F.reason)&&N();break}}return E}updateResult(){const e=v(this,Ze),r=this.createResult(v(this,he),this.options);if(W(this,wr,v(this,he).state),W(this,Kr,this.options),v(this,wr).data!==void 0&&W(this,Gr,v(this,he)),In(r,e))return;W(this,Ze,r);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,i=typeof n=="function"?n():n;if(i==="all"||!i&&!v(this,Jr).size)return!0;const a=new Set(i??v(this,Jr));return this.options.throwOnError&&a.add("error"),Object.keys(v(this,Ze)).some(o=>{const c=o;return v(this,Ze)[c]!==e[c]&&a.has(c)})};de(this,ye,Ia).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&de(this,ye,Wn).call(this)}},tt=new WeakMap,he=new WeakMap,Es=new WeakMap,Ze=new WeakMap,wr=new WeakMap,Kr=new WeakMap,It=new WeakMap,Jt=new WeakMap,js=new WeakMap,Vr=new WeakMap,Gr=new WeakMap,xr=new WeakMap,_r=new WeakMap,Qt=new WeakMap,Jr=new WeakMap,ye=new WeakSet,os=function(e){de(this,ye,zn).call(this);let r=v(this,he).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(rt)),r},Dn=function(){de(this,ye,qn).call(this);const e=er(this.options.staleTime,v(this,he));if(_s.isServer()||v(this,Ze).isStale||!Pn(e))return;const s=ja(v(this,Ze).dataUpdatedAt,e)+1;W(this,xr,fr.setTimeout(()=>{v(this,Ze).isStale||this.updateResult()},s))},Un=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(v(this,he)):this.options.refetchInterval)??!1},Mn=function(e){de(this,ye,Hn).call(this),W(this,Qt,e),!(_s.isServer()||ht(this.options.enabled,v(this,he))===!1||!Pn(v(this,Qt))||v(this,Qt)===0)&&W(this,_r,fr.setInterval(()=>{(this.options.refetchIntervalInBackground||Qn.isFocused())&&de(this,ye,os).call(this)},v(this,Qt)))},Wn=function(){de(this,ye,Dn).call(this),de(this,ye,Mn).call(this,de(this,ye,Un).call(this))},qn=function(){v(this,xr)&&(fr.clearTimeout(v(this,xr)),W(this,xr,void 0))},Hn=function(){v(this,_r)&&(fr.clearInterval(v(this,_r)),W(this,_r,void 0))},zn=function(){const e=v(this,tt).getQueryCache().build(v(this,tt),this.options);if(e===v(this,he))return;const r=v(this,he);W(this,he,e),W(this,Es,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},Ia=function(e){ze.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(v(this,Ze))}),v(this,tt).getQueryCache().notify({query:v(this,he),type:"observerResultsUpdated"})})},na);function Nu(t,e){return ht(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function Di(t,e){return Nu(t,e)||t.state.data!==void 0&&Kn(t,e,e.refetchOnMount)}function Kn(t,e,r){if(ht(e.enabled,t)!==!1&&er(e.staleTime,t)!=="static"){const s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&Xn(t,e)}return!1}function Ui(t,e,r,s){return(t!==e||ht(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&Xn(t,r)}function Xn(t,e){return ht(e.enabled,t)!==!1&&t.isStaleByTime(er(e.staleTime,t))}function Iu(t,e){return!In(t.getCurrentResult(),e)}function Mi(t){return{onFetch:(e,r)=>{var d,h,g,f,y;const s=e.options,n=(g=(h=(d=e.fetchOptions)==null?void 0:d.meta)==null?void 0:h.fetchMore)==null?void 0:g.direction,i=((f=e.state.data)==null?void 0:f.pages)||[],a=((y=e.state.data)==null?void 0:y.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const u=async()=>{let m=!1;const _=j=>{ju(j,()=>e.signal,()=>m=!0)},k=Ta(e.options,e.fetchOptions),x=async(j,w,A)=>{if(m)return Promise.reject();if(w==null&&j.pages.length)return Promise.resolve(j);const R=(()=>{const C={client:e.client,queryKey:e.queryKey,pageParam:w,direction:A?"backward":"forward",meta:e.options.meta};return _(C),C})(),E=await k(R),{maxPages:O}=e.options,S=A?Eu:Su;return{pages:S(j.pages,E,O),pageParams:S(j.pageParams,w,O)}};if(n&&i.length){const j=n==="backward",w=j?Bu:Wi,A={pages:i,pageParams:a},T=w(s,A);o=await x(A,T,j)}else{const j=t??i.length;do{const w=c===0?a[0]??s.initialPageParam:Wi(s,o);if(c>0&&w==null)break;o=await x(o,w),c++}while(c<j)}return o};e.options.persister?e.fetchFn=()=>{var m,_;return(_=(m=e.options).persister)==null?void 0:_.call(m,u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=u}}}function Wi(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 Bu(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 Ts,Et,Qe,kr,jt,Ht,ia,Fu=(ia=class extends Oa{constructor(e){super();te(this,jt);te(this,Ts);te(this,Et);te(this,Qe);te(this,kr);W(this,Ts,e.client),this.mutationId=e.mutationId,W(this,Qe,e.mutationCache),W(this,Et,[]),this.state=e.state||Lu(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){v(this,Et).includes(e)||(v(this,Et).push(e),this.clearGcTimeout(),v(this,Qe).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){W(this,Et,v(this,Et).filter(r=>r!==e)),this.scheduleGc(),v(this,Qe).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){v(this,Et).length||(this.state.status==="pending"?this.scheduleGc():v(this,Qe).remove(this))}continue(){var e;return((e=v(this,kr))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,o,c,u,d,h,g,f,y,m,_,k,x,j,w,A,T,R;const r=()=>{de(this,jt,Ht).call(this,{type:"continue"})},s={client:v(this,Ts),meta:this.options.meta,mutationKey:this.options.mutationKey};W(this,kr,Aa({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(E,O)=>{de(this,jt,Ht).call(this,{type:"failed",failureCount:E,error:O})},onPause:()=>{de(this,jt,Ht).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>v(this,Qe).canRun(this)}));const n=this.state.status==="pending",i=!v(this,kr).canStart();try{if(n)r();else{de(this,jt,Ht).call(this,{type:"pending",variables:e,isPaused:i}),v(this,Qe).config.onMutate&&await v(this,Qe).config.onMutate(e,this,s);const O=await((o=(a=this.options).onMutate)==null?void 0:o.call(a,e,s));O!==this.state.context&&de(this,jt,Ht).call(this,{type:"pending",context:O,variables:e,isPaused:i})}const E=await v(this,kr).start();return await((u=(c=v(this,Qe).config).onSuccess)==null?void 0:u.call(c,E,e,this.state.context,this,s)),await((h=(d=this.options).onSuccess)==null?void 0:h.call(d,E,e,this.state.context,s)),await((f=(g=v(this,Qe).config).onSettled)==null?void 0:f.call(g,E,null,this.state.variables,this.state.context,this,s)),await((m=(y=this.options).onSettled)==null?void 0:m.call(y,E,null,e,this.state.context,s)),de(this,jt,Ht).call(this,{type:"success",data:E}),E}catch(E){try{await((k=(_=v(this,Qe).config).onError)==null?void 0:k.call(_,E,e,this.state.context,this,s))}catch(O){Promise.reject(O)}try{await((j=(x=this.options).onError)==null?void 0:j.call(x,E,e,this.state.context,s))}catch(O){Promise.reject(O)}try{await((A=(w=v(this,Qe).config).onSettled)==null?void 0:A.call(w,void 0,E,this.state.variables,this.state.context,this,s))}catch(O){Promise.reject(O)}try{await((R=(T=this.options).onSettled)==null?void 0:R.call(T,void 0,E,e,this.state.context,s))}catch(O){Promise.reject(O)}throw de(this,jt,Ht).call(this,{type:"error",error:E}),E}finally{v(this,Qe).runNext(this)}}},Ts=new WeakMap,Et=new WeakMap,Qe=new WeakMap,kr=new WeakMap,jt=new WeakSet,Ht=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),ze.batch(()=>{v(this,Et).forEach(s=>{s.onMutationUpdate(e)}),v(this,Qe).notify({mutation:this,type:"updated",action:e})})},ia);function Lu(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Bt,wt,Rs,aa,$u=(aa=class extends As{constructor(e={}){super();te(this,Bt);te(this,wt);te(this,Rs);this.config=e,W(this,Bt,new Set),W(this,wt,new Map),W(this,Rs,0)}build(e,r,s){const n=new Fu({client:e,mutationCache:this,mutationId:++Bs(this,Rs)._,options:e.defaultMutationOptions(r),state:s});return this.add(n),n}add(e){v(this,Bt).add(e);const r=qs(e);if(typeof r=="string"){const s=v(this,wt).get(r);s?s.push(e):v(this,wt).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(v(this,Bt).delete(e)){const r=qs(e);if(typeof r=="string"){const s=v(this,wt).get(r);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&v(this,wt).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=qs(e);if(typeof r=="string"){const s=v(this,wt).get(r),n=s==null?void 0:s.find(i=>i.state.status==="pending");return!n||n===e}else return!0}runNext(e){var s;const r=qs(e);if(typeof r=="string"){const n=(s=v(this,wt).get(r))==null?void 0:s.find(i=>i!==e&&i.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){ze.batch(()=>{v(this,Bt).forEach(e=>{this.notify({type:"removed",mutation:e})}),v(this,Bt).clear(),v(this,wt).clear()})}getAll(){return Array.from(v(this,Bt))}find(e){const r={exact:!0,...e};return this.getAll().find(s=>Ii(r,s))}findAll(e={}){return this.getAll().filter(r=>Ii(e,r))}notify(e){ze.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return ze.batch(()=>Promise.all(e.map(r=>r.continue().catch(rt))))}},Bt=new WeakMap,wt=new WeakMap,Rs=new WeakMap,aa);function qs(t){var e;return(e=t.options.scope)==null?void 0:e.id}var Tt,oa,Du=(oa=class extends As{constructor(e={}){super();te(this,Tt);this.config=e,W(this,Tt,new Map)}build(e,r,s){const n=r.queryKey,i=r.queryHash??Yn(n,r);let a=this.get(i);return a||(a=new Ou({client:e,queryKey:n,queryHash:i,options:e.defaultQueryOptions(r),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(a)),a}add(e){v(this,Tt).has(e.queryHash)||(v(this,Tt).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=v(this,Tt).get(e.queryHash);r&&(e.destroy(),r===e&&v(this,Tt).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){ze.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return v(this,Tt).get(e)}getAll(){return[...v(this,Tt).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(s=>Ni(r,s))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(s=>Ni(e,s)):r}notify(e){ze.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){ze.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ze.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Tt=new WeakMap,oa),Oe,Yt,Xt,Qr,Yr,Zt,Xr,Zr,la,Uu=(la=class{constructor(t={}){te(this,Oe);te(this,Yt);te(this,Xt);te(this,Qr);te(this,Yr);te(this,Zt);te(this,Xr);te(this,Zr);W(this,Oe,t.queryCache||new Du),W(this,Yt,t.mutationCache||new $u),W(this,Xt,t.defaultOptions||{}),W(this,Qr,new Map),W(this,Yr,new Map),W(this,Zt,0)}mount(){Bs(this,Zt)._++,v(this,Zt)===1&&(W(this,Xr,Qn.subscribe(async t=>{t&&(await this.resumePausedMutations(),v(this,Oe).onFocus())})),W(this,Zr,Ys.subscribe(async t=>{t&&(await this.resumePausedMutations(),v(this,Oe).onOnline())})))}unmount(){var t,e;Bs(this,Zt)._--,v(this,Zt)===0&&((t=v(this,Xr))==null||t.call(this),W(this,Xr,void 0),(e=v(this,Zr))==null||e.call(this),W(this,Zr,void 0))}isFetching(t){return v(this,Oe).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return v(this,Yt).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=v(this,Oe).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=v(this,Oe).build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(er(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return v(this,Oe).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=v(this,Oe).get(s.queryHash),i=n==null?void 0:n.state.data,a=xu(e,i);if(a!==void 0)return v(this,Oe).build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return ze.batch(()=>v(this,Oe).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=v(this,Oe).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=v(this,Oe);ze.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=v(this,Oe);return ze.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},s=ze.batch(()=>v(this,Oe).findAll(t).map(n=>n.cancel(r)));return Promise.all(s).then(rt).catch(rt)}invalidateQueries(t,e={}){return ze.batch(()=>(v(this,Oe).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=ze.batch(()=>v(this,Oe).findAll(t).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let i=n.fetch(void 0,r);return r.throwOnError||(i=i.catch(rt)),n.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(rt)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=v(this,Oe).build(this,e);return r.isStaleByTime(er(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(rt).catch(rt)}fetchInfiniteQuery(t){return t.behavior=Mi(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(rt).catch(rt)}ensureInfiniteQueryData(t){return t.behavior=Mi(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Ys.isOnline()?v(this,Yt).resumePausedMutations():Promise.resolve()}getQueryCache(){return v(this,Oe)}getMutationCache(){return v(this,Yt)}getDefaultOptions(){return v(this,Xt)}setDefaultOptions(t){W(this,Xt,t)}setQueryDefaults(t,e){v(this,Qr).set(ws(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...v(this,Qr).values()],r={};return e.forEach(s=>{xs(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){v(this,Yr).set(ws(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...v(this,Yr).values()],r={};return e.forEach(s=>{xs(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...v(this,Xt).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Yn(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===Qs&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...v(this,Xt).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){v(this,Oe).clear(),v(this,Yt).clear()}},Oe=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Qr=new WeakMap,Yr=new WeakMap,Zt=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,la),Ba=ft.createContext(void 0),Fa=t=>{const e=ft.useContext(Ba);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Mu=({client:t,children:e})=>(ft.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),l.jsx(Ba.Provider,{value:t,children:e})),La=ft.createContext(!1),Wu=()=>ft.useContext(La);La.Provider;function qu(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Hu=ft.createContext(qu()),zu=()=>ft.useContext(Hu),Ku=(t,e,r)=>{const s=r!=null&&r.state.error&&typeof t.throwOnError=="function"?Ra(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},Vu=t=>{ft.useEffect(()=>{t.clearReset()},[t])},Gu=({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:n})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(n&&t.data===void 0||Ra(r,[t.error,s])),Ju=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))}},Qu=(t,e)=>t.isLoading&&t.isFetching&&!e,Yu=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,qi=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function Xu(t,e,r){var g,f,y,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=Wu(),n=zu(),i=Fa(),a=i.defaultQueryOptions(t);(f=(g=i.getDefaultOptions().queries)==null?void 0:g._experimental_beforeQuery)==null||f.call(g,a);const o=i.getQueryCache().get(a.queryHash);process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),a._optimisticResults=s?"isRestoring":"optimistic",Ju(a),Ku(a,n,o),Vu(n);const c=!i.getQueryCache().get(a.queryHash),[u]=ft.useState(()=>new e(i,a)),d=u.getOptimisticResult(a),h=!s&&t.subscribed!==!1;if(ft.useSyncExternalStore(ft.useCallback(_=>{const k=h?u.subscribe(ze.batchCalls(_)):rt;return u.updateResult(),k},[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),ft.useEffect(()=>{u.setOptions(a)},[a,u]),Yu(a,d))throw qi(a,u,n);if(Gu({result:d,errorResetBoundary:n,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw d.error;if((m=(y=i.getDefaultOptions().queries)==null?void 0:y._experimental_afterQuery)==null||m.call(y,a,d),a.experimental_prefetchInRender&&!_s.isServer()&&Qu(d,s)){const _=c?qi(a,u,n):o==null?void 0:o.promise;_==null||_.catch(rt).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?d:u.trackResult(d)}function Os(t,e){return Xu(t,Pu)}const Zu=5e3,ed=()=>`bob_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;function $a({ga4Config:t,hostContext:e,callbacks:r,enabled:s=!0,bobSupabaseUrl:n,bobSupabaseKey:i}){const a=p.useRef(ed()),o=p.useRef(!1),c=p.useRef(null),u=p.useRef(!1),d=p.useCallback((E,O)=>{if(!(!(t!=null&&t.measurementId)||typeof window>"u")&&window.gtag){const S={...O,send_to:t.measurementId};t.debug&&console.log("[BobAnalytics] GA4 event:",E,S),window.gtag("event",E,S)}},[t]),h=p.useCallback((E,O={})=>{var C,D,N,F,H,U,ie,Y;if(!s)return;const S={event_name:E,timestamp:new Date().toISOString(),session_id:a.current,user_email:(C=e==null?void 0:e.user)==null?void 0:C.email,user_id:(D=e==null?void 0:e.user)==null?void 0:D.id,vehicle_id:(H=(F=(N=e==null?void 0:e.vehicle)==null?void 0:N.selectedVehicle)==null?void 0:F.vehicle_id)==null?void 0:H.toString(),rego:(ie=(U=e==null?void 0:e.vehicle)==null?void 0:U.selectedVehicle)==null?void 0:ie.rego,parameters:O};d(E,{session_id:S.session_id,user_email:S.user_email,vehicle_id:S.vehicle_id,...O}),(Y=r==null?void 0:r.onAnalyticsEvent)==null||Y.call(r,S),t!=null&&t.debug&&console.log("[BobAnalytics] Event tracked:",S)},[s,e,r,d,t==null?void 0:t.debug]),g=p.useCallback(()=>{var E,O,S;o.current||(o.current=!0,h("bob_session_start",{widget_version:Ft,has_vehicle:!!((E=e==null?void 0:e.vehicle)!=null&&E.selectedVehicle),has_user:!!((O=e==null?void 0:e.user)!=null&&O.id)||!!((S=e==null?void 0:e.user)!=null&&S.email)}))},[h,e]),f=p.useCallback((E,O)=>{h("bob_message_sent",{message_length:E,has_vehicle:O})},[h]),y=p.useCallback(E=>{h("bob_vehicle_identified",{vehicle_make:E.make||"unknown",vehicle_model:E.model||"unknown",vehicle_year:E.year||"unknown",rego:E.rego})},[h]),m=p.useCallback((E,O)=>{h("bob_parts_viewed",{part_count:E,vehicle_id:O})},[h]),_=p.useCallback(E=>{h("bob_product_clicked",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),k=p.useCallback(E=>{h("bob_product_viewed",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),x=p.useCallback(E=>{h("bob_add_to_cart",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand,quantity:E.quantity??1})},[h]),j=p.useCallback((E,O)=>{h("bob_checkout_started",{cart_value:E,item_count:O})},[h]),w=p.useCallback(E=>{const O=Math.ceil(E/5/150*60);h("bob_speech_played",{text_length:E,duration_estimate:O})},[h]),A=p.useCallback(E=>{h("bob_speech_failed",{text_length:E})},[h]),T=p.useCallback((E,O)=>{h("bob_error",{error_type:E,error_message:O})},[h]),R=p.useCallback(E=>{if(!s||!n||!i)return;const O=(E==null?void 0:E.led_to_cart)||(E==null?void 0:E.had_product_match),S=()=>{var D,N,F,H,U,ie;u.current=!1;const C={session_id:a.current,user_id:((D=e==null?void 0:e.user)==null?void 0:D.id)||null,channel:"web",vehicle_id:(E==null?void 0:E.vehicle_id)||((H=(F=(N=e==null?void 0:e.vehicle)==null?void 0:N.selectedVehicle)==null?void 0:F.vehicle_id)==null?void 0:H.toString())||null,rego:(E==null?void 0:E.rego)||((ie=(U=e==null?void 0:e.vehicle)==null?void 0:U.selectedVehicle)==null?void 0:ie.rego)||null,had_product_match:(E==null?void 0:E.had_product_match)||!1,led_to_cart:(E==null?void 0:E.led_to_cart)||!1};fetch(`${n}/functions/v1/bob-conversation-track`,{method:"POST",headers:{"Content-Type":"application/json",apikey:i},body:JSON.stringify(C)}).catch(Y=>{console.warn("[BobAnalytics] Conversation track failed:",Y)})};if(O){c.current&&(clearTimeout(c.current),c.current=null),S();return}u.current||(u.current=!0,c.current=setTimeout(S,Zu))},[s,n,i,e]);return p.useEffect(()=>{g()},[g]),p.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]),{trackEvent:h,sessionId:a.current,trackSessionStart:g,trackMessageSent:f,trackVehicleIdentified:y,trackPartsViewed:m,trackProductClicked:_,trackProductViewed:k,trackAddToCart:x,trackCheckoutStarted:j,trackSpeechPlayed:w,trackSpeechFailed:A,trackError:T,trackConversationActivity:R}}const sn=p.createContext(null);function Zn({children:t,bobConfig:e,hostApiConfig:r,hostContext:s={},callbacks:n={},queryClient:i,ga4Config:a,analyticsEnabled:o=!0,bottomOffset:c=0,zIndexBase:u=50}){const d=p.useMemo(()=>new Uu({defaultOptions:{queries:{retry:1,staleTime:3e5}}}),[]),h=i||d,g=!!i;p.useEffect(()=>{console.log(`[BobWidget] v${Ft} initialized`),console.log(`[BobWidget] QueryClient: ${g?"external (shared)":"internal"}`),console.log(`[BobWidget] Analytics: ${o?"enabled":"disabled"}`),a!=null&&a.measurementId&&console.log(`[BobWidget] GA4: ${a.measurementId}`)},[g,o,a==null?void 0:a.measurementId]);const f=p.useMemo(()=>On(e.supabaseUrl,e.supabaseKey),[e.supabaseUrl,e.supabaseKey]),[y,m]=p.useState(s);p.useEffect(()=>{m(s)},[s]);const _=p.useCallback(x=>{m(j=>({...j,...x}))},[]),k=p.useMemo(()=>({bobSupabase:f,bobConfig:e,hostApiConfig:r,hostContext:y,callbacks:n,updateHostContext:_,ga4Config:a,analyticsEnabled:o,bottomOffset:c,zIndexBase:u}),[f,e,r,y,n,_,a,o,c,u]);return l.jsx(Mu,{client:h,children:l.jsx(sn.Provider,{value:k,children:t})})}function $t(){const t=p.useContext(sn);if(!t)throw new Error("useBobContext must be used within a BobProvider");return t}function td(){const{bobSupabase:t}=$t();return t}function Sr(){const t=p.useContext(sn);return(t==null?void 0:t.bobSupabase)||null}function rd(){const{hostContext:t}=$t();return t}function sd(){const{hostApiConfig:t}=$t();return t}function nd(){const{callbacks:t}=$t();return t}function id(){const{ga4Config:t,analyticsEnabled:e}=$t();return{ga4Config:t,enabled:e}}function ei(){const t=p.useContext(sn);return t?{bottomOffset:t.bottomOffset,zIndexBase:t.zIndexBase}:{bottomOffset:0,zIndexBase:50}}let Hs=null;const Hi=typeof window<"u"?window.AudioContext||window.webkitAudioContext:null,Da=()=>(!Hs&&Hi&&(Hs=new Hi,console.log("[BobWidget] AudioContext created, initial state:",Hs.state)),Hs),Ua=async()=>{const t=Da();if(!t)return!1;if(t.state==="running")return!0;try{return await t.resume(),console.log("[BobWidget] AudioContext resumed →",t.state),t.state==="running"}catch(r){return console.warn("[BobWidget] AudioContext resume failed:",r),!1}},ad=async(t,e,r)=>{const s=Da();s.state!=="running"&&await s.resume();const n=await s.decodeAudioData(t),i=s.createBufferSource();i.buffer=n,i.connect(s.destination);let a=!1;return i.onended=()=>{a||(a=!0,r==null||r())},i.start(0),e==null||e(),{source:i,stop:()=>{try{i.stop()}catch{}}}};let zi=!1;const Ma=t=>{if(!t||zi)return()=>{};const e=async()=>{await Ua()&&(zi=!0,t.removeEventListener("touchstart",e,!0),t.removeEventListener("pointerdown",e,!0),t.removeEventListener("click",e,!0))};return t.addEventListener("touchstart",e,{capture:!0,passive:!0}),t.addEventListener("pointerdown",e,{capture:!0}),t.addEventListener("click",e,{capture:!0}),()=>{t.removeEventListener("touchstart",e,!0),t.removeEventListener("pointerdown",e,!0),t.removeEventListener("click",e,!0)}},od=15e3,ld=t=>t.replace(/\bya\b/gi,"you"),Wa=({onStart:t,onEnd:e,onFailed:r}={})=>{const{bobConfig:s,bobSupabase:n}=$t(),[i,a]=p.useState(!1),o=p.useRef(null),c=p.useRef(null),u=p.useRef(!1),d=p.useRef([]),h=p.useRef(!1),g=p.useRef(!1),f=p.useRef(null),y=p.useRef(null),m=p.useRef(t),_=p.useRef(e),k=p.useRef(r);p.useEffect(()=>{m.current=t,_.current=e,k.current=r},[t,e,r]);const x=p.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),j=p.useCallback(()=>{var S;u.current||(u.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(S=m.current)==null||S.call(m))},[]),w=p.useCallback(async()=>{var N,F;if(h.current||d.current.length===0)return;h.current=!0;const S=d.current.shift();if(!S){h.current=!1;return}const{text:C,isGreeting:D}=S;D&&(g.current=!0),u.current=!1,x(),o.current&&(o.current.stop(),o.current=null),c.current=setTimeout(()=>{var H,U;console.warn("[BobWidget TTS] Timeout - triggering fallback callbacks"),j(),a(!1),g.current=!1,(H=_.current)==null||H.call(_),(U=k.current)==null||U.call(k),o.current=null,h.current=!1,w()},od);try{console.log("[BobWidget TTS] Using ElevenLabs TTS");const H=ld(C),U=await fetch(`${s.supabaseUrl}/functions/v1/bob-tts-elevenlabs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.supabaseKey}`},body:JSON.stringify({text:H})});if(!U.ok){const M=await U.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",M),new Error("TTS request failed")}const ie=await U.arrayBuffer();await Ua();const Y=await ad(ie,()=>{var M;x(),f.current=null,u.current||(u.current=!0,a(!0),console.log("[BobWidget TTS] Audio playing via AudioContext, triggering onStart"),(M=m.current)==null||M.call(m))},()=>{var M;x(),a(!1),g.current=!1,console.log("[BobWidget TTS] Audio ended, triggering onEnd"),(M=_.current)==null||M.call(_),o.current=null,h.current=!1,w()});o.current=Y}catch(H){x(),D&&(f.current=C,console.log("[BobWidget TTS] Greeting stored for retry on user interaction")),console.error("[BobWidget TTS] Speech synthesis error:",H),j(),a(!1),g.current=!1,(N=_.current)==null||N.call(_),(F=k.current)==null||F.call(k),h.current=!1,w()}},[s.supabaseUrl,s.supabaseKey,x,j]),A=p.useCallback((S,C=!1)=>{if(S.trim()){if(C){if(y.current===S){console.log(`[BobWidget TTS] Ignoring duplicate greeting: "${S.substring(0,30)}..."`);return}y.current=S,f.current=null}if(g.current&&!C){console.log("[BobWidget TTS] Greeting playing - queueing message"),d.current.push({text:S,isGreeting:C});return}C?d.current.unshift({text:S,isGreeting:C}):d.current.push({text:S,isGreeting:C}),w()}},[w]),T=p.useCallback(()=>{if(f.current&&!o.current&&!h.current){console.log("[BobWidget TTS] Retrying pending greeting on user interaction");const S=f.current;f.current=null,A(S,!0)}},[A]),R=p.useCallback((S=!1)=>{var C;x(),d.current=[],o.current&&(o.current.stop(),o.current=null),a(!1),g.current=!1,h.current=!1,S||(C=_.current)==null||C.call(_)},[x]),E=p.useCallback(()=>{o.current&&o.current.stop()},[]),O=p.useCallback(()=>{},[]);return p.useEffect(()=>()=>{x(),d.current=[],o.current&&(o.current.stop(),o.current=null)},[x]),{speak:A,stop:R,pause:E,resume:O,isSpeaking:i,isSupported:!0,retryPendingGreeting:T}},Ki="bob_last_visit",cd=30;function qa(t=cd){const[e,r]=p.useState(!1),[s,n]=p.useState(null);return p.useEffect(()=>{try{const i=localStorage.getItem(Ki),a=Date.now();if(i){const o=parseInt(i,10),c=(a-o)/(1e3*60*60*24);c<=t?(r(!0),n(new Date(o)),console.log(`[BobWidget] Returning user detected - last visit ${Math.round(c)} days ago`)):console.log(`[BobWidget] Previous visit was ${Math.round(c)} days ago - treating as new user`)}else console.log("[BobWidget] First time visitor detected");localStorage.setItem(Ki,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 Vn=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},ud=t=>{let e=Vn(t);return e=e.replace(/[\[\]{}]/g,""),e=e.replace(/https?:\/\/[^\s]+/g,""),e=e.replace(/\bSKU\s*:?\s*\w+/gi,""),e},dd=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],Vi=["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"],Ha=({setAnimationState:t,manualMode:e=!1,talkingState:r="talking",thinkingState:s="researching",completeState:n="idle",idleState:i="idle",listenState:a="listening",onStreamStart:o,onStreamComplete:c,onShowingProduct:u,onResearchStart:d,onPartsResearchStart:h,onReadyToSpeak:g,onHighlightPart:f,onHighlightProduct:y,onNoPartsFound:m,onAutoFetchComplete:_,onVariantSelectionRequired:k,shelfCategoriesRef:x,initialVehicle:j})=>{var rr,Ps,Ns,Is;const{bobConfig:w,hostApiConfig:A,hostContext:T,callbacks:R,ga4Config:E,analyticsEnabled:O}=$t(),S=$a({ga4Config:E,hostContext:T,callbacks:R,enabled:O}),{isReturningUser:C}=qa(),[D,N]=p.useState([]),[F,H]=p.useState(""),[U,ie]=p.useState(!1),[Y,M]=p.useState(!1),[G,pe]=p.useState(null),se=p.useRef(null),ne=p.useRef(!1),_e=p.useRef(!1),$=p.useRef(""),re=p.useRef(!1),z=p.useRef(null);p.useRef(null);const I="carfix_bob_session",ke=4*60*60*1e3,je=p.useRef(!1),ve=(Q,oe)=>{try{const Re={messages:Q??D,vehicleCandidates:Se.current,conversationState:Ae.current,identifiedVehicle:oe!==void 0?oe:G,savedAt:Date.now()};sessionStorage.setItem(I,JSON.stringify(Re))}catch(Re){console.warn("[BobWidget] Failed to save session:",Re)}},Se=p.useRef([]),Ae=p.useRef("AWAITING_REGO");p.useEffect(()=>{if(!je.current){je.current=!0;try{const Q=sessionStorage.getItem(I);if(Q){const oe=JSON.parse(Q);if(Date.now()-(oe.savedAt||0)<ke&&Array.isArray(oe.messages)&&oe.messages.length>0){console.log("[BobWidget] Restoring session:",oe.messages.length,"messages, state:",oe.conversationState),N(oe.messages),_e.current=!0,Array.isArray(oe.vehicleCandidates)&&(Se.current=oe.vehicleCandidates),oe.conversationState&&(Ae.current=oe.conversationState),oe.identifiedVehicle&&(pe(oe.identifiedVehicle),console.log("[BobWidget] Restored identifiedVehicle:",oe.identifiedVehicle.make,oe.identifiedVehicle.model));return}else console.log("[BobWidget] Session expired, clearing"),sessionStorage.removeItem(I)}}catch(Q){console.warn("[BobWidget] Failed to restore session:",Q),sessionStorage.removeItem(I)}j&&(console.log("[BobWidget] Applying initialVehicle:",j.make,j.model),Se.current=[j],Ae.current="VEHICLE_CONFIRMED",pe(j))}},[]),p.useEffect(()=>{D.length>0&&ve(D)},[D]);const Ke=()=>{Ve()},Ye=()=>{z.current&&(clearTimeout(z.current),z.current=null)},{speak:Ie,stop:Ve,isSpeaking:pt,retryPendingGreeting:We}=Wa({onStart:()=>{Ye(),re.current=!0,console.log("[BobWidget STATE] Speech STARTED - transitioning to TALK state"),S.trackSpeechPlayed($.current.length),g==null||g(),e||(console.log("[BobWidget STATE] Setting state to:",r),P(r))},onEnd:()=>{Ye(),console.log("[BobWidget STATE] Speech ENDED - transitioning out of TALK state");const Q=Vi.some(oe=>$.current.toLowerCase().includes(oe.toLowerCase()));e||(Q&&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),P(n),setTimeout(()=>{console.log("[BobWidget STATE] Post-complete transition to:",a),P(a)},2e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered"),S.trackSpeechFailed($.current.length)}});p.useEffect(()=>{var Q;(Q=R.onStopSpeechReady)==null||Q.call(R,Ke)},[]),p.useEffect(()=>{var Q;(Q=se.current)==null||Q.scrollIntoView({behavior:"smooth"})},[D]),p.useEffect(()=>{var oe,Re;const Q=(oe=T.vehicle)==null?void 0:oe.selectedVehicle;Q&&!G&&(console.log("[BobWidget] Setting vehicle from host context:",Q),pe(Q),(Re=R.onVehicleIdentified)==null||Re.call(R,Q),S.trackVehicleIdentified({make:Q.make,model:Q.model,year:Q.year,rego:Q.rego}))},[(rr=T.vehicle)==null?void 0:rr.selectedVehicle]),p.useEffect(()=>{var Q;if(D.length===0&&!_e.current){_e.current=!0;const oe=(Q=T.vehicle)==null?void 0:Q.selectedVehicle;let Re;C?(Re="Ah hey... you again! What you after this time?",console.log("[BobWidget] Using returning user greeting")):oe?Re=`G'day! Saw you've got the ${`${oe.year} ${oe.make} ${oe.model}`} - choice wagon! What can I help you find for it today?`:Re="Hey Bro, welcome to CARFIX - what can I get ya?",N([{role:"assistant",content:Re}]),Y||setTimeout(()=>{console.log("[BobWidget] Speaking initial greeting (priority)"),Ie(Re,!0)},500)}},[(Ps=T.vehicle)==null?void 0:Ps.selectedVehicle,D.length,Y,Ie]),p.useEffect(()=>{const Q=()=>{console.log("[BobWidget] User interaction detected - retrying pending greeting"),We(),document.removeEventListener("click",Q),document.removeEventListener("touchstart",Q)};return document.addEventListener("click",Q,{once:!0}),document.addEventListener("touchstart",Q,{once:!0}),()=>{document.removeEventListener("click",Q),document.removeEventListener("touchstart",Q)}},[We]),p.useEffect(()=>{var ct,Ct;const Q=(ct=T.vehicle)==null?void 0:ct.selectedVehicle;if(!Q||ne.current)return;const oe=Q.vehicle_id??Q.id,Re=Number.parseInt(String(oe),10);if(!Number.isFinite(Re)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",Q);return}ne.current=!0;const Xe={...Q,vehicle_id:String(Re)},xt=(Ct=T.user)==null?void 0:Ct.email;(async()=>{var Ut,sr;const Dt=`${w.supabaseUrl}/functions/v1/bob-chat`;try{const ut=await fetch(Dt,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:Xe,customerEmail:xt,autoFetchParts:!0,hostConfig:A,hostContext:T})});if(!ut.ok||!ut.body){console.error("[BobWidget] Auto-fetch failed:",ut.status);return}const jr=ut.body.getReader(),nr=new TextDecoder;let gt="";for(;;){const{done:Tr,value:Rr}=await jr.read();if(Tr)break;gt+=nr.decode(Rr,{stream:!0});let At;for(;(At=gt.indexOf(`
|
|
74
|
-
`))!==-1;){let nt
|
|
75
|
-
`))!==-1;){let
|
|
76
|
-
`+Z;break}}}let le=me.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");le=Vn(le),$.current=le;const ce=Vi.some(be=>me.toLowerCase().includes(be.toLowerCase()));if(console.log("[useBobChat] v3.2.10 scroll debug: highlightCategoryReceived=",Xe,"shelfCategories=",x!=null&&x.current?Array.from(x.current):"none"),!Xe&&(x!=null&&x.current)&&x.current.size>0){const be=le.toLowerCase();let we=null,Be=0;for(const Ue of x.current){const it=Ue.toLowerCase().split(/\s+/).filter(Boolean),L=it.filter(Mt=>be.includes(Mt)).length;L===it.length&&L>Be&&(Be=L,we=Ue)}we&&(console.log("[useBobChat] v3.2.10 shelf category match:",we,`(${Be} words)`),f==null||f(we))}const De=me.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(De){const[,be,we]=De;y==null||y({brand:be,price:parseFloat(we)})}if(!Y&&$.current.trim()){re.current=!1,Ye();const be=ud($.current);console.log("[BobWidget] Playing TTS"),Ie(be),z.current=setTimeout(()=>{re.current||(console.warn("[BobWidget] Speech fallback after 5s"),g==null||g(),e||(ce&&u?u():c?c():(P(n),setTimeout(()=>P(a),3e3))))},5e3)}else g==null||g(),e||(ce&&u?u():c?c():(P(n),setTimeout(()=>P(a),3e3)))}catch(mt){console.error("[BobWidget] Chat error:",mt);const b=mt instanceof Error?mt:new Error("Unknown error");(ar=R.onError)==null||ar.call(R,b),S.trackError(b.name||"ChatError",b.message||"Unknown chat error"),e||P(i)}},Ce=async()=>{if(!F.trim()||U)return;We(),Ve();const Q={role:"user",content:F};N(Xe=>[...Xe,Q]),H(""),S.trackMessageSent(F.length,!!G);const oe=F.toLowerCase();if(dd.some(Xe=>oe.includes(Xe))){const Xe=`G'day mate! I'm running Bob v${Ft} - she's running sweet as! Anything else I can help ya with?`;N(xt=>[...xt,{role:"assistant",content:Xe}]),Y||Ie(Xe);return}ie(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",s),d==null||d(),G&&(h==null||h()),e||P(s),await ae(Q),ie(!1)};return{messages:D,input:F,setInput:H,isLoading:U,handleSend:Ce,handleKeyPress:Q=>{Q.key==="Enter"&&!Q.shiftKey&&(Q.preventDefault(),Ce())},handleInputFocus:()=>{We()},handleInputBlur:()=>{},chatEndRef:se,clearMessages:()=>{sessionStorage.removeItem(I),Se.current=[],Ae.current="AWAITING_REGO",N([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:Y,toggleMute:()=>{M(Q=>!Q),Y||Ve()},isSpeaking:pt,identifiedVehicle:G,clearVehicle:()=>{pe(null)},sendDirectMessage:Q=>{if(!Q.trim())return;console.log("[BobWidget] sendDirectMessage:",Q),Ve(),ie(!1),H("");const oe={role:"user",content:Q};N(Re=>[...Re,oe]),d==null||d(),G&&(h==null||h()),e||P(s),ie(!0),ae(oe).finally(()=>ie(!1))},stopAllAudio:Ke}},hd={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},za=t=>{const e=Fa(),r=Sr();return p.useEffect(()=>{if(!r)return;const s=r.channel("animation-states-changes").on("postgres_changes",{event:"*",schema:"public",table:"animation_states"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe(),n=r.channel("bob-animations-changes").on("postgres_changes",{event:"*",schema:"public",table:"bob_animations"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe();return()=>{r.removeChannel(s),r.removeChannel(n)}},[e,r]),Os({queryKey:["bob-animation-data",t],queryFn:async()=>{var j;if(!r)return console.log("[BobAnimation] No supabase client, returning empty data"),hd;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&&((j=s[0])==null?void 0:j.id)||null;if(!a)return console.warn("[BobAnimation] No looks configured in database"),{states:[],configs:[],uploadedImages:[],looks:s||[],activeLookId:null};console.log(`[BobAnimation] Loading animations for look: ${(i==null?void 0:i.name)||a}`);const{data:o,error:c}=await r.from("animation_states").select("*").eq("is_active",!0).eq("look_id",a).order("display_order");if(c)throw c;const{data:u,error:d}=await r.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",a).order("animation_state").order("sequence_order");if(d)throw d;const h=(o||[]).map(w=>w.state_key);console.log(`[BobAnimation] Loaded ${h.length} states: ${h.join(", ")}`);const f=["idle","talking","listening"].filter(w=>{const A=[w,w.replace("ing",""),w+"ing"];return!h.some(T=>A.includes(T))});f.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${f.join(", ")}`);const y=new Set(h),m=(u||[]).filter(w=>y.has(w.animation_state));console.log(`[BobAnimation] Loaded ${m.length} animation frames`);const{data:_,error:k}=await r.storage.from("bob-images").list();if(k)throw k;const x=(_||[]).map(w=>{const{data:A}=r.storage.from("bob-images").getPublicUrl(w.name);return A.publicUrl});return m.forEach(w=>{const A=new Image;A.src=w.image_url}),{states:o||[],configs:m,uploadedImages:x,looks:s||[],activeLookId:a}},staleTime:30*1e3,gcTime:5*60*1e3})},Ka=(t={})=>{const{isSpeaking:e=!1}=t,[r,s]=p.useState(""),[n,i]=p.useState(0),[a,o]=p.useState(400),[c,u]=p.useState(!1),d=p.useRef(null),h=p.useRef(0),g=p.useRef(e),f=p.useRef(0),y=p.useRef(0),m=p.useRef(!1),_=p.useRef(0),{data:k,isLoading:x}=za(),j=p.useRef({}),{imageUrlsMap:w,alternateImages:A,offsetsMap:T,scalesMap:R,availableStates:E}=p.useMemo(()=>{if(!k)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const N={},F={},H={},U={},ie=k.states.map(Y=>Y.state_key);return ie.forEach(Y=>{const M=k.configs.filter(ne=>ne.animation_state===Y),G=M.map(ne=>ne.image_url),pe=M.map(ne=>ne.vertical_offset||0),se=M.map(ne=>ne.scale||100);if(G.length>0){const ne=k.states.find(_e=>_e.state_key===Y);N[Y]={url:G[0],animation_speed:(ne==null?void 0:ne.animation_speed)||400,pause_duration:(ne==null?void 0:ne.pause_duration)||0,loop_count:(ne==null?void 0:ne.loop_count)||0},F[Y]=G,H[Y]=pe,U[Y]=se}}),{imageUrlsMap:N,alternateImages:F,offsetsMap:H,scalesMap:U,availableStates:ie}},[k]);p.useEffect(()=>{j.current=w},[w]),p.useEffect(()=>{const N=g.current;if(g.current=e,N&&!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 O=p.useCallback(N=>{s(F=>F===N?F:(f.current=0,y.current=0,m.current=!1,i(0),N))},[]);p.useEffect(()=>{E.length>0&&!r&&s(E[0])},[E,r]),p.useEffect(()=>{const N=A[r];if(d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),f.current=0,y.current=0,m.current=!1,h.current=0,i(0),!N||N.length<=1)return;const F=j.current[r],H=(F==null?void 0:F.animation_speed)||a||400,U=(F==null?void 0:F.loop_count)||0,ie=(F==null?void 0:F.pause_duration)||0,Y=r.toLowerCase().includes("talk"),M=G=>{if(h.current===0&&(h.current=G),m.current){G-_.current>=ie&&(m.current=!1,y.current=0,h.current=G),d.current=requestAnimationFrame(M);return}if(G-h.current>=H){h.current=G;const se=(f.current+1)%N.length;se===0?(y.current++,Y&&g.current?(f.current=se,i(se)):U>0&&y.current>=U?ie>0&&(m.current=!0,_.current=G):(f.current=se,i(se))):(f.current=se,i(se))}d.current=requestAnimationFrame(M)};return d.current=requestAnimationFrame(M),()=>{d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)}},[r,A,a]);const S=p.useCallback(()=>{const N=A[r];if(!N||N.length===0){const F=E.find(H=>{var U;return((U=A[H])==null?void 0:U.length)>0});return F?(console.warn(`[useBobAnimation] No images for "${r}", using fallback: ${F}`),A[F][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return N[n]||N[0]},[A,r,E,n]),C=p.useCallback(()=>{const N=T[r];if(!N||N.length===0){const F=E.find(H=>{var U;return((U=T[H])==null?void 0:U.length)>0});return F?T[F][0]:0}return N[n]||N[0]},[T,r,E,n]),D=p.useCallback(()=>{const N=R[r];if(!N||N.length===0){const F=E.find(H=>{var U;return((U=R[H])==null?void 0:U.length)>0});return F?R[F][0]:100}return N[n]||N[0]},[R,r,E,n]);return{animationState:r,setAnimationState:O,getCurrentImage:S,getCurrentOffset:C,getCurrentScale:D,imageUrls:w,availableStates:E,setTalkSpeed:o,manualMode:c,setManualMode:u,isLoading:x}},Va=()=>{const t=Sr(),{data:e=[],isLoading:r}=Os({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}},Ga=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=12,className:i="",verticalOffset:a=0,scale:o=100})=>{const c=a+n,u=55*(o/100);return l.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${i}`,children:l.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[r&&l.jsx("img",{src:r,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),l.jsx("img",{src:t,alt:`Bob ${e}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${c}%`,width:`${u}%`,maxWidth:`${220*(o/100)}px`,transformOrigin:"center bottom"}}),s&&l.jsx("img",{src:s,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${n}%`}})]})})},K={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"},Xs={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"}},gn={"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."},fd="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.",ks={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`},Ja={fitsVehicle:{background:"rgba(34,197,94,0.1)",text:"#22C55E",border:"rgba(34,197,94,0.2)",icon:"Check",label:"Fits Your Vehicle"},viscosity:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",icon:"Gauge"},volume:{background:"#ECFEFF",text:"#0E7490",border:"#A5F3FC",icon:"Droplets"},quantity:{background:"#F1F5F9",text:"#475569",border:"#CBD5E1"},partNumber:{background:"transparent",text:"#64748B",border:"transparent"},carfixValue:{background:"rgba(0,82,204,0.1)",text:"#0052CC",border:"rgba(0,82,204,0.2)",icon:"Sparkles",label:"CARFIX Value"},rotorPair:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",label:"Pair"}},vt={packageTitle:{fontSize:"20px",fontWeight:700},partslotName:{fontSize:"14px",fontWeight:600},productName:{fontSize:"14px",fontWeight:500},description:{fontSize:"14px",fontWeight:400},priceMain:{fontSize:"20px",fontWeight:700},priceSecondary:{fontSize:"12px",fontWeight:400},tierLabel:{fontSize:"14px",fontWeight:500},badgeText:{fontSize:"12px",fontWeight:500}};function Qa(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 Ya(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function st(t){return`$${t.toFixed(2)}`}function Xa(t){if(gn[t])return gn[t];const e=t.toLowerCase();for(const[r,s]of Object.entries(gn))if(e.includes(r.toLowerCase())||r.toLowerCase().includes(e))return s;return fd}const ls=({type:t,value:e,className:r=""})=>{const s=Ja[t],n=e||("label"in s?s.label:""),i=()=>{if(!("icon"in s))return null;const a={width:12,height:12};switch(s.icon){case"Check":return l.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})});case"Sparkles":return l.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("path",{d:"M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"}),l.jsx("path",{d:"M5 19l1 3 1-3 3-1-3-1-1-3-1 3-3 1 3 1z"})]});case"Gauge":return l.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("circle",{cx:"12",cy:"12",r:"10"}),l.jsx("path",{d:"M12 6v6l4 2"})]});case"Droplets":return l.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 11-11.31 0z"})});default:return null}};return l.jsxs("span",{className:r,style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:500,background:s.background,color:s.text,border:`1px solid ${s.border}`,whiteSpace:"nowrap"},children:[i(),n]})},ti=({products:t,title:e,onProductClick:r,onAddToCart:s})=>!t||t.length===0?null:l.jsxs("div",{style:{marginTop:"16px",width:"100%"},children:[e&&l.jsxs("div",{style:{marginBottom:"12px",fontSize:vt.partslotName.fontSize,fontWeight:vt.partslotName.fontWeight,color:K.foreground,display:"flex",alignItems:"center",gap:"8px"},children:[l.jsx("span",{style:{fontSize:"18px"},children:"🚗"}),e]}),l.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.slice(0,6).map((n,i)=>l.jsx(pd,{product:n,onProductClick:r,onAddToCart:s,isRecommended:i===0},n.id||n.sku||i))}),t.length>6&&l.jsxs("div",{style:{marginTop:"12px",fontSize:"13px",color:K.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),pd=({product:t,onProductClick:e,onAddToCart:r,isRecommended:s=!1})=>{const[n,i]=p.useState(!1),[a,o]=p.useState(!1),c=t.image_url||t.image||(t.sku?ks.productImage(t.sku):null),u=t.brand?ks.brandLogo(t.brand):null,d=t.brand||"Quality Part",h=t.name||"Product",g=t.price??0,f=t.partNumber||t.part_number,y=Qa({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:m,unitPriceLabel:_}=Ya(g,y);return l.jsxs("div",{style:{background:K.card,borderRadius:"12px",border:`2px solid ${K.border}`,overflow:"hidden",cursor:e?"pointer":"default",transition:"all 0.2s ease"},onClick:()=>e==null?void 0:e(t),onMouseEnter:k=>{k.currentTarget.style.borderColor=`${K.primary}80`,k.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:k=>{k.currentTarget.style.borderColor=K.border,k.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&l.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${K.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[l.jsx("span",{style:{fontSize:vt.partslotName.fontSize,fontWeight:vt.partslotName.fontWeight,color:K.foreground},children:t.partslotDescription}),s&&l.jsx(ls,{type:"carfixValue"})]}),l.jsxs("div",{style:{padding:"16px",display:"flex",gap:"16px"},children:[l.jsx("div",{style:{width:"96px",minWidth:"96px",height:"96px",borderRadius:"8px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",border:`1px solid ${K.border}`},children:c&&!n?l.jsx("img",{src:c,alt:h,style:{width:"100%",height:"100%",objectFit:"contain",padding:"4px"},onError:()=>i(!0)}):l.jsx("span",{style:{fontSize:"32px",opacity:.5},children:"🔧"})}),l.jsxs("div",{style:{flex:1,minWidth:0},children:[l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[u&&!a&&l.jsx("img",{src:u,alt:d,style:{height:"16px",width:"auto",objectFit:"contain"},onError:()=>o(!0)}),l.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:K.foreground,textTransform:"uppercase"},children:d})]}),l.jsx("div",{style:{fontSize:vt.productName.fontSize,fontWeight:vt.productName.fontWeight,color:K.foreground,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",lineHeight:"1.4",marginBottom:"8px"},children:h}),l.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"12px"},children:[l.jsx(ls,{type:"fitsVehicle"}),y&&l.jsx(ls,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!y&&l.jsx(ls,{type:"quantity",value:`Qty: ${t.quantity}`}),f&&l.jsxs("span",{style:{fontSize:"12px",color:K.mutedForeground},children:["#",f]})]})]}),l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",justifyContent:"space-between",minWidth:"100px"},children:[l.jsxs("div",{style:{textAlign:"right"},children:[l.jsx("div",{style:{fontSize:vt.priceMain.fontSize,fontWeight:vt.priceMain.fontWeight,color:K.foreground},children:st(m)}),_&&l.jsx("div",{style:{fontSize:vt.priceSecondary.fontSize,color:K.mutedForeground},children:_}),l.jsx("div",{style:{fontSize:vt.priceSecondary.fontSize,color:K.mutedForeground},children:"inc GST"})]}),r&&l.jsx("button",{onClick:k=>{k.stopPropagation(),r(t)},style:{background:K.primary,color:"#FFFFFF",border:"none",borderRadius:"8px",padding:"8px 16px",fontSize:"13px",fontWeight:600,cursor:"pointer",transition:"all 0.2s ease",whiteSpace:"nowrap"},onMouseEnter:k=>{k.currentTarget.style.background=K.primaryHover},onMouseLeave:k=>{k.currentTarget.style.background=K.primary},onMouseDown:k=>{k.currentTarget.style.transform="scale(0.98)"},onMouseUp:k=>{k.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},Za=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:o,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,className:g="",onAddToCart:f,onProductClick:y})=>l.jsx("div",{className:g,style:{width:"100%",maxWidth:"72rem",margin:"0 auto",padding:"0 16px 32px 16px"},children:l.jsxs("div",{style:{backgroundColor:"rgba(20, 30, 50, 0.85)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.3)",overflow:"hidden"},children:[l.jsx("div",{style:{padding:"16px",borderBottom:"1px solid rgba(255,255,255,0.1)",backgroundColor:"rgba(0,0,0,0.2)"},children:l.jsxs("div",{style:{display:"flex",gap:"8px"},children:[l.jsx("input",{value:e,onChange:m=>r(m.target.value),onKeyPress:i,onFocus:a,onBlur:o,placeholder:"Ask Bob about car parts...",disabled:s,style:{flex:1,padding:"12px 16px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",color:"white",fontSize:"16px",outline:"none"}}),d&&l.jsx("button",{onClick:d,style:{flexShrink:0,padding:"12px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",cursor:"pointer",minHeight:"unset",minWidth:"unset"},title:u?"Unmute Bob's voice":"Mute Bob's voice",children:u?"🔇":"🔊"}),l.jsx("button",{onClick:n,disabled:s||!e.trim(),style:{flexShrink:0,padding:"12px 20px",background:s||!e.trim()?"rgba(0, 102, 204, 0.3)":"linear-gradient(135deg, rgba(0, 102, 204, 0.95), rgba(0, 73, 153, 1))",color:"white",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.2)",cursor:s||!e.trim()?"not-allowed":"pointer",opacity:s||!e.trim()?.5:1,minHeight:"unset",minWidth:"unset",fontWeight:600},children:"Send"})]})}),l.jsxs("div",{style:{overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px",height:"400px",background:"rgba(0,0,0,0.1)"},children:[[...t].reverse().map((m,_)=>{var k;return l.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:m.role==="user"?"flex-end":"flex-start"},children:l.jsxs("div",{style:{maxWidth:(k=m.suggestedProducts)!=null&&k.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&&l.jsx(ti,{products:m.suggestedProducts,title:m.suggestionsTitle,onAddToCart:f,onProductClick:y})]})},_)}),l.jsx("div",{ref:c})]})]})}),gd=768,md=1024;function nn(){const[t,e]=p.useState("mobile");return p.useEffect(()=>{const r=()=>{const s=window.innerWidth;s>=md?e("desktop"):s>=gd?e("tablet"):e("mobile")};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),t}function ri(){const t=nn();return bd(t)}function bd(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 an=({currentImage:t,animationState:e,counterOverlayUrl:r,counterHeightPercent:s=15,scale:n=100,position:i="center",verticalOffset:a=0,hasArrived:o=!0})=>{const c=ri(),d=95*n/100,h=550*n/100,g=()=>{switch(i){case"center":return"50%";case"partial-left":return`${c.partialLeftPosition}%`;case"hidden":return`${c.hiddenPosition}%`;default:return"50%"}},f=()=>i==="center"?"translateX(-50%)":"translateX(0)",y=s+a,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 l.jsxs("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"visible"},children:[l.jsx("div",{className:"absolute z-[60]",style:{bottom:`${y}%`,left:g(),maxHeight:`${100-s-2}%`,transform:f(),width:`${d}%`,maxWidth:`${h}px`,transition:m()+", opacity 0.6s ease-out",willChange:"transform, left, opacity",opacity:o?1:0},children:l.jsx("img",{src:t,alt:`Bob ${e}`,className:"w-full h-auto object-contain",style:{display:"block",maxHeight:"100%",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})}),r&&l.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-[70]",style:{height:`${s}%`,pointerEvents:"none"},children:l.jsx("img",{src:r,alt:"Shop counter",className:"w-full h-full",style:{objectFit:"fill",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})})]})},yd={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)"},vd={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)"},eo={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)"},hs={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},wd={background:"rgba(255, 255, 255, 0.12)",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.15)"},Gi={background:"rgba(255, 255, 255, 0.15)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"12px"},xd={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},to=({product:t,isSpotlighted:e=!1,onProductClick:r,onAddToCart:s})=>{const[n,i]=p.useState(!1),[a,o]=p.useState(0),c=()=>{r==null||r(t)},u=y=>{y.stopPropagation(),s==null||s(t)},d=()=>{a===0&&t.brandImageUrl?o(1):o(2)},h=a===0?t.image_url:a===1?t.brandImageUrl:void 0,g=e?vd:yd,f=t.webDescription||t.name;return l.jsxs("div",{onClick:c,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),className:"relative w-full cursor-pointer glass-card",style:{...g,padding:"16px",paddingBottom:"60px",position:"relative",transform:n?"scale(1.04) translateY(-4px)":"scale(1) translateY(0)",boxShadow:n?"0 16px 56px rgba(0, 0, 0, 0.4), 0 0 24px rgba(255,255,255,0.08)":g.boxShadow,transition:"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.3s ease-out"},children:[e&&l.jsxs("div",{className:"absolute -top-2.5 -right-2.5 z-10 flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.95) 0%, rgba(0, 73, 153, 1) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"20px",boxShadow:"0 8px 24px rgba(0, 102, 204, 0.5)",color:"white"},children:[l.jsx("svg",{className:"w-3.5 h-3.5",fill:"currentColor",viewBox:"0 0 20 20",children:l.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),"Bob's Pick"]}),l.jsxs("div",{className:"flex items-start gap-4",children:[l.jsx("div",{className:"flex-shrink-0 flex items-center justify-center overflow-hidden",style:{...wd,width:"92px",height:"92px",backgroundColor:"#ffffff"},children:h&&a<2?l.jsx("img",{src:h,alt:t.name,className:"w-full h-full object-contain p-2",loading:"lazy",onError:d}):l.jsx("div",{className:"flex flex-col items-center justify-center",style:{color:"rgba(255,255,255,0.4)"},children:l.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"font-bold leading-tight",style:{fontSize:"15px",letterSpacing:"-0.01em",...hs.primary},children:f}),t.partNumber&&l.jsx("p",{className:"mt-0.5 text-xs",style:{color:"rgba(255,255,255,0.5)"},children:t.partNumber}),l.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[t.brand&&l.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5",style:{...Gi,color:"rgba(255, 255, 255, 0.9)"},children:[l.jsx("svg",{className:"w-2.5 h-2.5",fill:"currentColor",viewBox:"0 0 20 20",children:l.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),t.brand]}),t.perCarQty&&t.perCarQty>1&&l.jsxs("span",{className:"inline-flex items-center text-xs font-semibold px-2 py-0.5",style:{...Gi,color:"rgba(255, 200, 50, 0.95)"},children:["Qty: ",t.perCarQty]})]}),(t.viscosity||t.volume)&&l.jsx("p",{className:"mt-1 text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.7)"},children:[t.viscosity,t.volume].filter(Boolean).join(" / ")}),l.jsx("p",{className:"font-extrabold mt-2",style:{fontSize:"22px",letterSpacing:"-0.02em",color:"#FFD700",textShadow:"0 2px 6px rgba(0, 0, 0, 0.5), 0 0 12px rgba(255, 215, 0, 0.3)"},children:t.price>0?`$${t.price.toFixed(2)}`:"POA"})]})]}),l.jsx("button",{onClick:u,className:"absolute flex items-center justify-center cursor-pointer",style:{bottom:"12px",right:"12px",background:"linear-gradient(135deg, #22C55E 0%, #16A34A 100%)",border:"1px solid rgba(255, 255, 255, 0.35)",borderRadius:"22px",boxShadow:"0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)",width:"44px",height:"44px",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease-out"},onMouseEnter:y=>{y.currentTarget.style.transform="scale(1.08) translateY(-2px)",y.currentTarget.style.boxShadow="0 14px 48px rgba(34, 197, 94, 0.5), inset 0 1px 0 rgba(255,255,255,0.4)"},onMouseLeave:y=>{y.currentTarget.style.transform="scale(1) translateY(0)",y.currentTarget.style.boxShadow="0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},children:l.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M12 4v16m8-8H4"})})}),t.partslotDescription&&l.jsx("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:l.jsx("span",{className:"text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.6)"},children:t.partslotDescription})})]})},ro=["SHOE","DRUM"],so=["PAD","ROTOR"];function no(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 io(t,e){const r=e==="disc"?ro:so;return t.filter(s=>{const n=s.partslotName.toUpperCase();return!r.some(i=>n.includes(i))})}function ao(t){return t.reduce((e,r)=>e+r.displayPrice,0)}function oo(t){const e=t.flatMap(n=>n.products),r=e.some(n=>{const i=n.partslotName.toUpperCase();return n.displayPrice>0&&so.some(a=>i.includes(a))}),s=e.some(n=>{const i=n.partslotName.toUpperCase();return n.displayPrice>0&&ro.some(a=>i.includes(a))});return{hasDisc:r,hasDrum:s}}const mn=(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))},_d=(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},kd=({product:t,isSpotlighted:e,spotlightedRef:r,onProductClick:s,onAddToCart:n})=>l.jsx("div",{ref:e?r:void 0,children:l.jsx(to,{product:t,isSpotlighted:e,onProductClick:s,onAddToCart:n})}),on=({products:t,servicePackages:e,highlightedPartType:r,highlightedProduct:s,scrollToCategory:n,onScrollToCategoryComplete:i,onProductClick:a,onPackageSelect:o,isResearching:c,visible:u=!0,counterHeightPercent:d=22,hasVehicle:h=!1,onAddToCart:g,vehicleMakeModel:f,pendingVariants:y,pendingVariantMake:m,pendingVariantModel:_,onVariantSelect:k})=>{const x=f||"Bob's Shelf",j=nn();ri();const w=p.useRef(null),A=p.useRef({}),T=p.useRef(null),[R,E]=p.useState(null),[O,S]=p.useState({}),[C,D]=p.useState({}),N=p.useMemo(()=>{const $={};return t.forEach(z=>{const I=z.partslotDescription||"Other Parts";$[I]||($[I]=[]),$[I].push(z)}),Object.keys($).sort((z,I)=>z.localeCompare(I)).map(z=>({name:z,products:$[z]}))},[t]);p.useEffect(()=>{if(!r)return;const $=setTimeout(()=>{const re=Object.entries(A.current);for(const[z,I]of re)if(I&&mn(z,r)){I.scrollIntoView({behavior:"smooth",block:"start"});break}},300);return()=>clearTimeout($)},[r]),p.useEffect(()=>{if(!n)return;const $=setTimeout(()=>{const re=Object.entries(A.current);for(const[z,I]of re)if(I&&mn(z,n)){I.scrollIntoView({behavior:"smooth",block:"start"});break}i==null||i()},300);return()=>clearTimeout($)},[n]);const[F,H]=p.useState(0),U=$=>{const re=$.currentTarget,z=re.scrollHeight-re.clientHeight;if(z>0){const I=re.scrollTop/z;H(Math.max(0,Math.min(1,I)))}},ie=((y==null?void 0:y.length)??0)>0,Y=t.length>0||e.length>0||ie,M=c&&!Y,G=Y&&!M,pe=u||Y,se=j==="mobile"?92:j==="tablet"?65:70,ne=j==="desktop"?"900px":j==="tablet"?"500px":"100%",_e=j==="mobile"?"calc(8px + env(safe-area-inset-top, 4px))":"6px";return l.jsxs(l.Fragment,{children:[Y&&u&&l.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${F*65+18}%)`,...xd,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),l.jsxs("div",{ref:w,onScroll:U,className:`absolute overflow-y-auto overflow-x-hidden flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${pe?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${se}%`,maxWidth:ne,right:"0",left:"auto",top:_e,bottom:j==="mobile"?"calc(100px + env(safe-area-inset-bottom, 0px))":"52px",paddingTop:"4px",paddingRight:"16px",paddingLeft:"16px",paddingBottom:"8px",zIndex:55,pointerEvents:"auto",touchAction:"pan-y",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"},children:[l.jsx("div",{className:"sticky top-0 z-10 -mx-1 px-3 py-2.5",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.85) 0%, rgba(0, 73, 153, 0.9) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4)",border:"1px solid rgba(255, 255, 255, 0.25)"},children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[c&&Y?l.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:l.jsx("div",{className:"w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"})}):l.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:l.jsx("svg",{className:"w-3.5 h-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),l.jsx("span",{style:{...hs.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:c&&Y?"Updating...":x})]}),l.jsxs("span",{style:{color:"rgba(255,255,255,0.8)",fontSize:"12px",fontWeight:500},children:[t.length+e.length," ",t.length+e.length===1?"item":"items"]})]})}),M&&l.jsx("div",{className:"p-5",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(0, 102, 204, 0.3)"},children:l.jsx("div",{className:"w-6 h-6 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"rgba(255,255,255,0.8)",borderTopColor:"transparent"}})}),l.jsxs("div",{children:[l.jsx("p",{style:{...hs.primary,fontWeight:600,fontSize:"14px"},children:"Loading parts..."}),l.jsx("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:"Bob's stocking the shelves"})]})]})}),ie&&y&&k&&l.jsxs("div",{className:"flex flex-col gap-3",children:[l.jsx("div",{className:"sticky top-0 z-10 px-4 py-3",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"20px",boxShadow:"0 8px 32px rgba(0, 102, 204, 0.35)",border:"1px solid rgba(255, 255, 255, 0.2)"},children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:l.jsx("svg",{className:"w-4 h-4 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),l.jsxs("div",{children:[l.jsxs("span",{className:"text-white font-semibold text-sm",children:["Which ",m," ",_,"?"]}),l.jsx("span",{className:"text-white/70 text-xs block",children:"Tap your variant to continue"})]})]})}),l.jsx("div",{className:"flex flex-col gap-2 px-1",children:(()=>{const $=(y||[]).map(z=>[z.engineCode,z.kw?`${z.kw}kW`:null,z.ccDisplay||(z.cc?`${z.cc}cc`:null),z.fuelType].filter(Boolean).join(" · ")||z.displayTitle),re=$.reduce((z,I)=>(z[I]=(z[I]||0)+1,z),{});return(y||[]).map((z,I)=>{const ke=$[I],ve=re[ke]>1&&z.displaySubtitle?z.displaySubtitle:ke;return l.jsx("button",{type:"button",onClick:()=>k(z),className:"w-full text-left transition-all duration-200 cursor-pointer rounded-2xl overflow-hidden focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 active:scale-[0.98]",style:{background:"linear-gradient(135deg, rgba(255, 255, 255, 0.92) 0%, rgba(255, 255, 255, 0.85) 100%)",backdropFilter:"blur(12px) saturate(150%)",WebkitBackdropFilter:"blur(12px) saturate(150%)",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.12)",border:"1px solid rgba(255, 255, 255, 0.4)",minHeight:"72px"},children:l.jsxs("div",{className:"flex items-center gap-3 p-4",children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0 font-bold text-lg text-white",style:{background:"linear-gradient(135deg, #0066CC 0%, #0052A3 100%)",boxShadow:"0 2px 8px rgba(0, 102, 204, 0.4)"},children:z.optionNumber}),l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("p",{className:"font-semibold text-gray-900 text-base leading-tight",children:ve})}),l.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{background:"rgba(0, 102, 204, 0.1)"},children:l.jsx("svg",{className:"w-4 h-4 text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M9 5l7 7-7 7"})})})]})},z.vehicle_id)})})()})]}),!M&&!Y&&l.jsx("div",{className:"p-5",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(255, 149, 0, 0.3)"},children:l.jsx("svg",{className:"w-5 h-5",style:{color:"#FF9500"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),l.jsxs("div",{children:[l.jsx("p",{style:{...hs.primary,fontWeight:600,fontSize:"14px"},children:"No products to display"}),l.jsxs("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:["Products: ",t.length," | Packages: ",e.length]})]})]})}),G&&e.length>0&&l.jsx("div",{className:"space-y-4",children:e.map($=>{var pt,We;const re=no($),z=($.preparedTiers||[]).filter(P=>!P.isHidden),{hasDisc:I,hasDrum:ke}=re?oo(z):{hasDisc:!1,hasDrum:!1},je=re&&I&&!ke?"disc":re&&ke&&!I?"drum":C[$.id]||"disc";let ve=z;re&&(ve=z.map(P=>{const ae=io(P.products,je);return{...P,products:ae,totalPrice:ao(ae),productCount:ae.length}}));const Se=((pt=ve.find(P=>P.isRecommended))==null?void 0:pt.tierName)||((We=ve[0])==null?void 0:We.tierName)||"",Ae=O[$.id]||Se,Ke=ve.find(P=>P.tierName===Ae),Ie=Xa($.title).split(".")[0]+".",Ve=R===$.id;return l.jsxs("div",{ref:P=>{A.current[$.title]=P},className:"overflow-hidden transition-all duration-300",style:{background:K.card,borderRadius:"16px",border:`1px solid ${K.border}`,boxShadow:"0 4px 20px rgba(0,0,0,0.08)"},children:[l.jsx("div",{className:"px-4 py-3",style:{background:`linear-gradient(135deg, ${K.primary} 0%, ${K.primaryHover} 100%)`},children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center flex-shrink-0",children:l.jsx("svg",{className:"h-5 w-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("h3",{className:"text-white font-bold text-base leading-tight truncate",children:$.title}),$.estimated_time&&l.jsx("div",{className:"flex items-center gap-3 mt-0.5",children:l.jsxs("span",{className:"text-white/70 text-xs flex items-center gap-1",children:[l.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),$.estimated_time]})})]})]})}),l.jsxs("div",{className:"px-4 py-3 border-b",style:{borderColor:K.border},children:[l.jsx("p",{className:"text-sm leading-relaxed",style:{color:K.mutedForeground},children:Ie}),re&&I&&ke&&l.jsxs("div",{className:"mt-2 mb-1",children:[l.jsx("p",{className:"text-[11px] mb-1.5",style:{color:K.mutedForeground},children:"Select your vehicle's rear brake type"}),l.jsxs("div",{className:"flex rounded-xl overflow-hidden border",style:{borderColor:K.border},children:[l.jsx("button",{onClick:()=>D(P=>({...P,[$.id]:"disc"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:je==="disc"?K.primary:"transparent",color:je==="disc"?"#FFFFFF":K.mutedForeground},children:"Disc Brakes (Pads + Rotors)"}),l.jsx("button",{onClick:()=>D(P=>({...P,[$.id]:"drum"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:je==="drum"?K.primary:"transparent",color:je==="drum"?"#FFFFFF":K.mutedForeground},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),ve.length>0&&l.jsxs("div",{className:"p-3",children:[l.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2 px-1",style:{color:K.mutedForeground},children:"Choose Your Value Level"}),l.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:`repeat(${Math.min(ve.length,4)}, 1fr)`},children:ve.map(P=>{const ae=Xs[P.tierName],Ce=P.tierName===Ae;return l.jsxs("div",{onClick:()=>S(J=>({...J,[$.id]:P.tierName})),className:"relative rounded-xl text-center transition-all cursor-pointer",style:{padding:ve.length>=4?"6px 4px":"8px",background:P.isRecommended?`${K.primary}10`:Ce?`${K.primary}05`:K.background,border:`2px solid ${P.isRecommended?K.primary:Ce?K.primary+"80":K.border}`},children:[P.isRecommended&&l.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wide whitespace-nowrap",style:{background:K.primary,color:"white"},children:"Carfix Value"}),l.jsxs("p",{className:"text-sm font-bold mt-1",style:{color:(ae==null?void 0:ae.textColor)||K.foreground},children:[ae==null?void 0:ae.emoji," ",P.displayName]}),l.jsx("div",{className:"flex flex-col items-center gap-1 mt-2",style:{minHeight:ve.length>=4?"40px":"48px"},children:P.brands.slice(0,1).map((J,Le)=>{const fe=`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${J.fullName.replace(/\s+/g,"")}.jpg`;return l.jsx("div",{className:"w-full bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{height:ve.length>=4?"36px":"44px",maxWidth:ve.length>=4?"64px":"80px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",border:"1px solid #F1F5F9"},children:l.jsx("img",{src:J.imageUrl,alt:J.fullName,className:"w-auto object-contain",style:{height:ve.length>=4?"26px":"32px"},onError:Ee=>{const ue=Ee.target;ue.src!==fe?ue.src=fe:(ue.style.display="none",ue.parentElement.innerHTML=`<span class="text-[10px] font-semibold text-gray-600 truncate px-1">${J.fullName}</span>`)}})},Le)})}),l.jsxs("p",{className:"text-[10px] mt-2",style:{color:K.mutedForeground},children:[P.productCount," ",P.productCount===1?"part":"parts"]}),P.savingsAmount&&P.savingsAmount>0?l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-[11px] line-through",style:{color:K.mutedForeground},children:st(P.originalTotalPrice)}),l.jsx("p",{className:"text-base font-bold",style:{color:K.success},children:st(P.totalPrice)}),l.jsxs("p",{className:"text-[9px] font-semibold px-1.5 py-0.5 rounded-full mt-0.5",style:{background:`${K.success}15`,color:K.success},children:["SAVE ",st(P.savingsAmount)," — ",P.bundleDiscountPercentage,"% Bundle Deal"]})]}):l.jsx("p",{className:"text-base font-bold mt-1",style:{color:K.foreground},children:st(P.totalPrice)}),l.jsx("p",{className:"text-[10px]",style:{color:K.mutedForeground},children:"inc GST"}),l.jsx("button",{onClick:J=>{J.stopPropagation();const Le=P.bundleDiscountPercentage||0,fe=1-Le/100,Ee=P.products.map(ue=>({id:ue.sku,name:ue.name,brand:ue.brand,price:Le>0?Math.round(ue.displayPrice*fe*100)/100:ue.displayPrice,sku:ue.sku,partNumber:ue.partNumber||void 0,image_url:ue.productImageUrl,partslotDescription:ue.partslotName,quantity:1,_bundleMeta:{is_bundle_item:!0,bundle_discount_percentage:Le,service_package_name:$.title,service_package_id:$.id,quality_tier:P.tierName}}));g==null||g(Ee)},className:"w-full mt-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all",style:{background:P.isRecommended?K.success:"#F1F5F9",color:P.isRecommended?"white":K.success,border:P.isRecommended?"none":"1px solid #E2E8F0",textAlign:"center"},children:"Add"})]},P.tierName)})})]}),l.jsxs("div",{onClick:()=>E(Ve?null:$.id),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-t",style:{borderColor:K.border},children:[l.jsx("span",{className:"text-xs",style:{color:K.mutedForeground},children:Ve?"Hide details":"Show details"}),l.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${Ve?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",style:{color:K.mutedForeground},children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),Ve&&Ke&&l.jsx("div",{className:"px-4 pb-4 border-t animate-in slide-in-from-top-2 duration-200",style:{borderColor:K.border},children:l.jsxs("div",{className:"pt-3",children:[l.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:K.mutedForeground},children:[Ke.displayName," Tier Products"]}),l.jsx("div",{className:"space-y-2",children:Ke.products.map(P=>l.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:K.background,border:`1px solid ${K.border}`},children:[l.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg overflow-hidden flex items-center justify-center",style:{width:"56px",height:"56px",minWidth:"56px",maxWidth:"56px"},children:P.productImageUrl?l.jsx("img",{src:P.productImageUrl,alt:P.name,className:"object-contain",style:{width:"100%",height:"100%",maxWidth:"56px",maxHeight:"56px",padding:"4px"}}):l.jsx("svg",{className:"w-6 h-6 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-xs font-medium truncate",style:{color:K.foreground},children:P.name}),l.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[l.jsx("span",{className:"text-[10px]",style:{color:K.mutedForeground},children:P.brand}),P.isRotor&&l.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 font-medium",children:"Pair"})]}),l.jsx("p",{className:"text-[10px] mt-0.5",style:{color:K.mutedForeground},children:P.partslotName})]}),l.jsxs("div",{className:"text-right flex-shrink-0",children:[l.jsx("p",{className:"text-sm font-bold",style:{color:K.primary},children:st(P.displayPrice)}),P.isRotor&&l.jsxs("p",{className:"text-[9px]",style:{color:K.mutedForeground},children:["$",P.price.toFixed(2)," ea"]})]})]},P.sku))})]})})]},$.id)})}),G&&N.map(({name:$,products:re})=>{const z=r&&mn($,r);return l.jsxs("section",{ref:I=>{A.current[$]=I},className:"transition-all duration-300",style:{background:"transparent",borderRadius:"24px"},children:[l.jsxs("div",{"data-testid":"partslot-header","data-partslot-name":$,className:"px-3 py-2.5 flex items-center justify-between",style:{background:z?"rgba(0, 102, 204, 0.95)":"rgba(0, 51, 102, 0.9)",borderRadius:"16px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",marginBottom:"8px"},children:[l.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l.jsx("div",{className:"w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0",style:{background:z?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 1) 100%)":"rgba(255,255,255,0.2)"},children:l.jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),l.jsx("span",{className:"text-xs font-bold truncate uppercase tracking-wide",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)"},children:$})]}),l.jsx("span",{className:"text-[10px] font-bold px-2.5 py-1 rounded-full flex-shrink-0",style:{background:"rgba(255, 149, 0, 0.9)",color:"white",boxShadow:"0 2px 8px rgba(255, 149, 0, 0.4)"},children:re.length})]}),l.jsx("div",{className:"flex flex-col gap-3",children:re.map((I,ke)=>{const je=!!(s&&_d(I,s));return l.jsx("div",{"data-testid":"partslot-product",children:l.jsx(kd,{product:I,isSpotlighted:je,spotlightedRef:T,onProductClick:a,onAddToCart:g,viewportSize:j})},`${I.id}-${ke}`)})})]},$)}),l.jsx("div",{className:"h-4"})]})]})},si=({onTranscript:t,onSpeechEnd:e,language:r="en-NZ",mode:s="toggle"}={})=>{const[n,i]=p.useState(!1),[a,o]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(null),[g,f]=p.useState(!1),y=p.useRef(null),m=p.useRef(""),_=p.useRef(t),k=p.useRef(e),x=p.useRef(null),j=15e3;p.useEffect(()=>{_.current=t,k.current=e},[t,e]),p.useEffect(()=>{if(typeof window<"u"&&window.location.protocol!=="https:"&&window.location.hostname!=="localhost"&&window.location.hostname!=="127.0.0.1"){console.warn("[BobWidget] Speech recognition requires HTTPS. PTT will not work on HTTP."),h("Voice input requires a secure connection (HTTPS)"),f(!1);return}const R=window.SpeechRecognition||window.webkitSpeechRecognition;if(R){f(!0);const E=new R;E.continuous=s==="ptt",E.interimResults=!0,E.lang=r,E.maxAlternatives=1,E.onstart=()=>{i(!0),h(null)},E.onresult=O=>{let S="",C="";for(let D=O.resultIndex;D<O.results.length;D++){const N=O.results[D][0].transcript;O.results[D].isFinal?C+=N:S+=N}C&&(m.current=C,o(C),_.current&&_.current(C)),u(S)},E.onerror=O=>{switch(i(!1),O.error){case"no-speech":h("No speech detected. Please try again.");break;case"audio-capture":h("No microphone found. Please check your device.");break;case"not-allowed":h("Microphone permission denied. Please allow access.");break;default:h("Speech recognition error. Please try again.")}},E.onend=()=>{x.current&&(clearTimeout(x.current),x.current=null),i(!1),u(""),m.current&&k.current&&k.current(m.current),m.current=""},y.current=E}return()=>{y.current&&y.current.stop()}},[r,s]);const w=()=>{if(y.current&&!n){o(""),u(""),h(null),x.current=setTimeout(()=>{console.warn("[SpeechRecognition] Safety timeout - forcing stop after 15s"),y.current&&y.current.abort(),i(!1),u("")},j);try{y.current.start()}catch(R){console.warn("[SpeechRecognition] start() failed (already running):",R),x.current&&(clearTimeout(x.current),x.current=null)}}},A=()=>{x.current&&(clearTimeout(x.current),x.current=null),y.current&&n&&y.current.stop()};return{isListening:n,transcript:a,interimTranscript:c,error:d,isSupported:g,startListening:w,stopListening:A,toggleListening:()=>{n?A():w()}}},lo=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:o,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onAddToCart:g,onProductClick:f,onQuickReply:y,onInterrupt:m,counterHeightPercent:_=22})=>{var _e;const[k,x]=p.useState(!1),j=p.useRef(null),w=p.useRef(!1),{bottomOffset:A,zIndexBase:T}=ei(),{isListening:R,interimTranscript:E,error:O,isSupported:S,startListening:C,stopListening:D}=si({onTranscript:$=>r($),language:"en-NZ",mode:"ptt"});p.useEffect(()=>{E&&r(E)},[E,r]);const N=h?"speaking":s?"processing":R?"listening":"idle",F=p.useCallback($=>{if($.preventDefault(),N==="speaking"){m==null||m();return}s||w.current||(w.current=!0,navigator.vibrate&&navigator.vibrate(30),C())},[N,s,C,m]),H=p.useCallback(()=>{w.current&&(w.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),D(),setTimeout(()=>{n()},150))},[D,n]),U=[...t].reverse().find($=>$.role==="assistant"),ie=((_e=U==null?void 0:U.suggestedProducts)==null?void 0:_e.length)||0,Y=U!=null&&U.content?U.content.length>50?U.content.slice(0,50)+"...":U.content:"Ask Bob about car parts...",M=ie>0?` (${ie} products)`:"",G={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)"}},se={idle:G.idle,listening:G.active,processing:G.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)"}}[N],ne={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return l.jsxs("div",{ref:j,style:{position:"fixed",bottom:A,left:0,right:0,...eo,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:k?"55vh":"90px",zIndex:T+80,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[l.jsx("button",{onClick:()=>x(!k),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:T+90,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":k?"Collapse chat":"Expand chat",children:k?l.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):l.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!k&&l.jsx("div",{onClick:()=>x(!0),style:{padding:"8px 12px 2px 12px",cursor:"pointer"},children:l.jsxs("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Y,M&&l.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:M})]})}),k&&l.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map(($,re)=>{var z;return l.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:$.role==="user"?"flex-end":"flex-start"},children:l.jsxs("div",{style:{maxWidth:(z=$.suggestedProducts)!=null&&z.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:$.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:[$.content,$.role==="assistant"&&$.suggestedProducts&&$.suggestedProducts.length>0&&l.jsx(ti,{products:$.suggestedProducts,title:$.suggestionsTitle,onAddToCart:g,onProductClick:f}),$.role==="assistant"&&$.quickReplies&&$.quickReplies.length>0&&l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:$.quickReplies.map((I,ke)=>l.jsx("button",{onClick:je=>{je.stopPropagation(),m==null||m(),y==null||y(I.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:I.label},ke))})]})},re)}),l.jsx("div",{ref:c})]}),S&&l.jsxs("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px",position:"relative"},children:[N==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),N!=="listening"&&ne[N]&&l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:ne[N].border,transform:"translate(-50%, -50%)",animation:ne[N].animation,pointerEvents:"none"}}),l.jsx("button",{onTouchStart:F,onTouchEnd:H,onTouchCancel:H,onMouseDown:F,onMouseUp:H,onMouseLeave:H,onClick:R?H:void 0,disabled:N==="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:N==="processing"?"not-allowed":"pointer",opacity:N==="processing"?.6:1,transform:N==="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:se.backdropFilter,WebkitBackdropFilter:se.WebkitBackdropFilter,"--bob-ptt-bg":se.background,"--bob-ptt-shadow":se.boxShadow,"--bob-ptt-border":se.border,"--bob-ptt-radius":"32px"},title:"Hold to talk",children:l.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...hs.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:N==="listening"?"LISTENING":N==="processing"?"THINKING":N==="speaking"?"TAP TO STOP":"TALK"})})]}),l.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[O&&l.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:O}),l.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[d&&l.jsx("button",{onClick:d,style:{flexShrink:0,height:"40px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"12px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?l.jsxs("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):l.jsx("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),l.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[l.jsx("input",{type:"text",value:e,onChange:$=>r($.target.value),onKeyPress:i,onFocus:a,onBlur:o,placeholder:"Message Bob...",disabled:N!=="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:N!=="idle"?0:1,transition:"opacity 0.15s ease"}}),N!=="idle"&&l.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[N==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),N==="processing"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),N==="speaking"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map(($,re)=>l.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${$}s infinite`}},re))}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&l.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]})]})]})]})},co=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:y,onToggleMute:m,isSpeaking:_,products:k,servicePackages:x,highlightedPartType:j,highlightedProduct:w,scrollToCategory:A,onScrollToCategoryComplete:T,onProductClick:R,onPackageSelect:E,isResearching:O,onAddToCart:S,onQuickReply:C,onInterrupt:D,vehicle:N,onChangeVehicle:F,pendingVariants:H,pendingVariantMake:U,pendingVariantModel:ie,onVariantSelect:Y,bobOffset:M=0,bobScale:G=100,embedded:pe=!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 se=nn(),[ne,_e]=p.useState("center"),[$,re]=p.useState("hidden"),z=k.length>0||x.length>0,I=((H==null?void 0:H.length)??0)>0,ke=z||I,Se=(()=>{switch(se){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*G/100;p.useEffect(()=>{if(O&&$!=="loading"&&$!=="visible")re("loading"),ne==="center"&&_e("partial-left");else if(ke&&$!=="visible")if(ne==="center"){_e("partial-left"),re("transitioning");const Ke=setTimeout(()=>{re("visible")},400);return()=>clearTimeout(Ke)}else re("visible");else!ke&&!O&&$!=="hidden"&&(re("hidden"),_e("center"))},[ke,O,$,ne]);const Ae=$!=="hidden";return l.jsxs("div",{className:pe?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:pe?"100%":"100dvh",touchAction:"manipulation"},children:[r&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)",transform:"scale(1.02)"}}),l.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))"}})]}),l.jsx(an,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:Se,position:ne,verticalOffset:M}),l.jsx(on,{products:k,servicePackages:x,highlightedPartType:j,highlightedProduct:w,scrollToCategory:A,onScrollToCategoryComplete:T,onProductClick:R,onPackageSelect:E,isResearching:O,visible:Ae,counterHeightPercent:n,hasVehicle:!!N,onAddToCart:S,pendingVariants:H,pendingVariantMake:U,pendingVariantModel:ie,onVariantSelect:Y}),l.jsx(lo,{messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:y,onToggleMute:m,isSpeaking:_,onAddToCart:S,onProductClick:R,onQuickReply:C,onInterrupt:D,counterHeightPercent:n})]})};function Sd(t){const[e,r]=p.useState(null);return p.useEffect(()=>{const s=t.current;if(!s||(r(s.getBoundingClientRect().height),typeof ResizeObserver>"u"))return;const n=new ResizeObserver(i=>{var a,o;for(const c of i){const u=((o=(a=c.borderBoxSize)==null?void 0:a[0])==null?void 0:o.blockSize)??c.contentRect.height;u>0&&r(u)}});return n.observe(s),()=>n.disconnect()},[t]),e}const uo=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:o,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onQuickReply:g,onInterrupt:f,counterHeightPercent:y=22})=>{const[m,_]=p.useState(!1),k=p.useRef(null),x=p.useRef(!1),{bottomOffset:j,zIndexBase:w}=ei(),{isListening:A,interimTranscript:T,error:R,isSupported:E,startListening:O,stopListening:S}=si({onTranscript:G=>r(G),language:"en-NZ",mode:"ptt"});p.useEffect(()=>{T&&r(T)},[T,r]);const C=h?"speaking":s?"processing":A?"listening":"idle",D=p.useCallback(G=>{if(G.preventDefault(),C==="speaking"){f==null||f();return}s||x.current||(x.current=!0,navigator.vibrate&&navigator.vibrate(30),O())},[C,s,O,f]),N=p.useCallback(()=>{x.current&&(x.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),S(),setTimeout(()=>{n()},150))},[S,n]),F=[...t].reverse().find(G=>G.role==="assistant"),H=F!=null&&F.content?F.content.length>50?F.content.slice(0,50)+"...":F.content:"Ask Bob about car parts...",U={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 8px 32px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"50%",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},Y={idle:U.idle,listening:U.active,processing:U.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)"}}[C],M={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return l.jsxs("div",{ref:k,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",willChange:"transform, height",...eo,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:m?"55%":"110px",overflow:"visible",zIndex:w+30,paddingBottom:"calc(8px + env(safe-area-inset-bottom, 0px))",pointerEvents:"none"},children:[l.jsx("button",{onClick:()=>_(!m),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:w+40,cursor:"pointer",minHeight:"32px",minWidth:"32px",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto"},"aria-label":m?"Collapse chat":"Expand chat",children:m?l.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 9l-7 7-7-7"})}):l.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M5 15l7-7 7 7"})})}),!m&&l.jsx("div",{onClick:()=>_(!0),style:{padding:"6px 12px 4px 12px",height:"26px",overflow:"hidden",cursor:"pointer",pointerEvents:"auto"},children:l.jsx("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:H})}),m&&l.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px",pointerEvents:"auto"},className:"glass-scroll",children:[[...t].reverse().map((G,pe)=>l.jsx("div",{style:{display:"flex",justifyContent:G.role==="user"?"flex-end":"flex-start"},children:l.jsxs("div",{style:{maxWidth:"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:G.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:[G.content,G.role==="assistant"&&G.quickReplies&&G.quickReplies.length>0&&l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:G.quickReplies.map((se,ne)=>l.jsx("button",{onClick:_e=>{_e.stopPropagation(),f==null||f(),g==null||g(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},ne))})]})},pe)),l.jsx("div",{ref:c})]}),l.jsxs("div",{style:{padding:m?"8px 12px 4px 12px":"4px 12px 4px 12px",borderTop:m?"1px solid rgba(255, 255, 255, 0.15)":"none",pointerEvents:"auto"},children:[R&&l.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:R}),l.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&m&&l.jsx("button",{onClick:d,style:{flexShrink:0,height:"36px",width:"36px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"10px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#22c55e":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?l.jsxs("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):l.jsx("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),l.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[l.jsx("input",{type:"text",value:e,onChange:G=>r(G.target.value),onKeyPress:i,onFocus:a,onBlur:o,placeholder:"Message Bob...",disabled:C!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:C!=="idle"?0:1,transition:"opacity 0.15s ease"}}),C!=="idle"&&l.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[C==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),C==="processing"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),C==="speaking"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map((G,pe)=>l.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${G}s infinite`}},pe))}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&l.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]}),E&&l.jsxs("div",{style:{position:"relative",marginLeft:"4px"},children:[C==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),C!=="listening"&&M[C]&&l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:M[C].border,transform:"translate(-50%, -50%)",animation:M[C].animation,pointerEvents:"none"}}),l.jsxs("button",{onTouchStart:D,onTouchEnd:N,onTouchCancel:N,onMouseDown:D,onMouseUp:N,onMouseLeave:N,disabled:C==="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:C==="processing"?"not-allowed":"pointer",opacity:C==="processing"?.6:1,transform:C==="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:w+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:[l.jsx("svg",{style:{height:"28px",width:"28px",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2))"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})}),C==="listening"&&l.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",width:"12px",height:"12px",borderRadius:"50%",backgroundColor:"#fef3c7",animation:"ptt-dot 0.6s ease-in-out infinite alternate"}})]})]})]})]})]})},Ed=({product:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{const n=t.productUrl||t.product_url,i=t.partNumber||t.part_number,a=!!n||!!s;return l.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-white/95 backdrop-blur-md overflow-hidden",children:[l.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-gray-200 bg-white/80 backdrop-blur-sm",children:l.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-blue-600 font-medium text-sm hover:text-blue-700 active:scale-95 transition-all",children:[l.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back to Products"]})}),l.jsxs("div",{className:"flex-1 overflow-y-auto",children:[l.jsx("div",{className:"aspect-square bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center",children:t.image_url?l.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):l.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[l.jsx("svg",{className:"h-16 w-16 mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),l.jsx("span",{className:"text-sm font-medium uppercase tracking-wide",children:"No Image Available"})]})}),l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("div",{children:[l.jsx("h1",{className:"text-xl font-bold text-gray-900 mb-1",children:t.name}),t.brand&&l.jsx("p",{className:"text-sm text-gray-600 font-medium",children:t.brand})]}),l.jsxs("div",{className:"bg-blue-50 rounded-xl p-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-1",children:"Price"}),l.jsx("p",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"Price on Request"}),t.price>0&&l.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Inc. GST"})]}),l.jsxs("div",{className:"space-y-3",children:[t.partslotDescription&&l.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"Category"}),l.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.partslotDescription})]}),t.sku&&l.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"SKU"}),l.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.sku})]}),i&&l.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"Part Number"}),l.jsx("span",{className:"text-sm font-medium text-gray-900",children:i})]})]}),a&&l.jsx("a",{href:n||"#",onClick:o=>{s&&(o.preventDefault(),s(t))},target:n&&!s?"_blank":void 0,rel:n&&!s?"noopener noreferrer":void 0,className:"block text-center text-blue-600 text-sm font-medium hover:underline py-2",children:"View Full Details on CARFIX →"})]})]}),l.jsx("div",{className:"p-4 border-t border-gray-200 bg-white/95 backdrop-blur-sm",children:l.jsx("button",{onClick:()=>r==null?void 0:r(t),className:"w-full bg-blue-600 text-white text-base font-semibold py-3 rounded-xl hover:bg-blue-700 active:bg-blue-800 transition-colors shadow-lg",children:"Add to Cart"})})]})},ho=({package:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{var j;const[n,i]=p.useState(!1),a=p.useMemo(()=>no(t),[t.id,t.title]),{hasDisc:o,hasDrum:c}=p.useMemo(()=>{if(!a||!t.preparedTiers)return{hasDisc:!1,hasDrum:!1};const w=t.preparedTiers.filter(A=>!A.isHidden);return oo(w)},[a,t.preparedTiers]),[u,d]=p.useState("disc"),h=p.useMemo(()=>!a||o&&!c?"disc":c&&!o?"drum":u,[a,o,c,u]),g=a&&o&&c,f=p.useMemo(()=>{if(!t.preparedTiers||t.preparedTiers.length===0)return[];const w=t.preparedTiers.filter(A=>!A.isHidden);return a?w.map(A=>{const T=io(A.products,h);return{...A,products:T,totalPrice:ao(T),productCount:T.length}}):w},[t.preparedTiers,a,h]),y=f.length>0,m=w=>{const A=w.bundleDiscountPercentage||0,T=1-A/100,R=w.products.map(E=>({...E,displayPrice:A>0?Math.round(E.displayPrice*T*100)/100:E.displayPrice,_bundleMeta:{is_bundle_item:!0,bundle_discount_percentage:A,service_package_name:t.title,service_package_id:t.id,quality_tier:w.tierName}}));r==null||r(R)},_=w=>w===2?"grid-cols-2":w===3?"grid-cols-3":"grid-cols-2",k=Xa(t.title),x=((j=f[0])==null?void 0:j.productCount)||0;return l.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-[#FAFAFA] overflow-hidden",children:[l.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#E2E8F0] bg-white shadow-sm",children:l.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-[#0052CC] font-medium text-sm hover:text-[#0047B3] active:scale-95 transition-all",children:[l.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]})}),l.jsxs("div",{className:"flex-1 overflow-y-auto",children:[l.jsxs("div",{className:"px-4 pt-4 pb-4",style:{background:"linear-gradient(135deg, rgba(0,82,204,0.05) 0%, rgba(56,189,248,0.05) 100%)"},children:[l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 bg-white shadow-md",children:t.icon_url?l.jsx("img",{src:t.icon_url,alt:"",className:"w-8 h-8 object-contain"}):l.jsx("svg",{className:"w-7 h-7 text-[#0052CC]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("h1",{className:"text-xl font-bold text-[#0F172A]",children:t.title}),l.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#64748B]",children:[t.estimated_time&&l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),t.estimated_time]}),t.difficulty_level&&l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085"})}),t.difficulty_level]})]})]})]}),l.jsx("p",{className:"text-sm text-[#64748B] mt-3 leading-relaxed",children:k}),g&&l.jsxs("div",{className:"mt-3",children:[l.jsx("p",{className:"text-[11px] text-[#94A3B8] mb-1.5",children:"Select your vehicle's rear brake type"}),l.jsxs("div",{className:"flex rounded-xl overflow-hidden border border-[#E2E8F0] bg-white",children:[l.jsx("button",{onClick:()=>d("disc"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:u==="disc"?K.primary:"transparent",color:u==="disc"?"#FFFFFF":"#64748B"},children:"Disc Brakes (Pads + Rotors)"}),l.jsx("button",{onClick:()=>d("drum"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:u==="drum"?K.primary:"transparent",color:u==="drum"?"#FFFFFF":"#64748B"},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),l.jsxs("div",{className:"px-4 py-3 flex items-center justify-center gap-2 border-b border-[#E2E8F0] bg-white",children:[l.jsx("span",{className:"font-semibold text-[#0F172A] text-sm",children:"Choose Your Value Level"}),l.jsx("span",{className:"text-[#64748B] text-xs cursor-help",title:"Select the quality tier that suits your needs",children:"ⓘ"})]}),l.jsx("div",{className:"p-4",children:y?l.jsx("div",{className:`grid ${_(f.length)} gap-3`,children:f.map(w=>{const A=Xs[w.tierName];return l.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:w.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[w.isRecommended&&l.jsx("div",{className:"absolute top-0 left-0 right-0 px-2 py-1 text-[9px] font-bold text-white text-center",style:{background:K.primary},children:"★ CARFIX VALUE"}),l.jsxs("div",{className:`p-3 flex-1 flex flex-col ${w.isRecommended?"pt-7":""}`,children:[l.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[l.jsx("span",{className:"text-lg",children:A==null?void 0:A.emoji}),l.jsxs("div",{children:[l.jsx("span",{className:"font-bold text-sm block",style:{color:(A==null?void 0:A.textColor)||K.foreground},children:w.displayName}),l.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:w.description||(A==null?void 0:A.description)})]})]}),l.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:w.brands.slice(0,3).map(T=>l.jsx("div",{className:"h-10 px-2 bg-white rounded-xl flex items-center justify-center shadow-md border border-[#F1F5F9]",children:l.jsx("img",{src:T.imageUrl,alt:T.fullName,className:"h-6 w-auto object-contain",onError:R=>{const E=R.target,O=`${ks.storageBase}/brand_images/${T.fullName.replace(/\s+/g,"")}.jpg`;if(E.src!==O)E.src=O;else{const S=E.parentElement;S&&(S.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${T.name}</span>`)}}})},T.name))}),l.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[w.productCount," part",w.productCount!==1?"s":""," included"]}),l.jsx("div",{className:"mt-auto",children:w.savingsAmount&&w.savingsAmount>0?l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-xs line-through text-[#94A3B8]",children:st(w.originalTotalPrice)}),l.jsx("p",{className:"text-xl font-bold",style:{color:"#22C55E"},children:st(w.totalPrice)}),l.jsxs("p",{className:"text-[10px] font-semibold text-[#22C55E] bg-[#22C55E]/10 inline-block px-1.5 py-0.5 rounded-full mt-0.5",children:["SAVE ",st(w.savingsAmount)," — ",w.bundleDiscountPercentage,"% Bundle Deal"]})]}):l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-xl font-bold",style:{color:w.isRecommended?"#0052CC":"#0F172A"},children:st(w.totalPrice)}),l.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]})}),l.jsx("button",{onClick:()=>m(w),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 ${w.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"})]})]},w.tierName)})}):l.jsxs("div",{className:"rounded-2xl p-6 bg-white border border-[#E2E8F0] shadow-md text-center",children:[l.jsx("svg",{className:"w-12 h-12 mx-auto text-[#94A3B8] mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),l.jsx("p",{className:"text-sm font-medium text-[#64748B]",children:"Package details not available for this vehicle"}),l.jsx("p",{className:"text-xs text-[#94A3B8] mt-1",children:"Please try refreshing or contact support"})]})}),y&&l.jsxs("div",{className:"px-4 pb-4",children:[l.jsxs("button",{onClick:()=>i(!n),className:"w-full flex items-center justify-between p-3 rounded-xl bg-white border border-[#E2E8F0] hover:bg-slate-50 transition-all shadow-sm",children:[l.jsxs("span",{className:"text-sm font-medium text-[#0F172A]",children:[n?"▼":"▶"," View Product Details"]}),l.jsxs("span",{className:"text-xs text-[#64748B]",children:[x," product",x!==1?"s":""]})]}),n&&l.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:f.map(w=>{if(w.products.length===0)return null;const A=Xs[w.tierName];return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2 pb-1 border-b border-[#E2E8F0]",children:[l.jsx("span",{className:"text-lg",children:A==null?void 0:A.emoji}),l.jsx("span",{className:"font-semibold text-sm",style:{color:A==null?void 0:A.textColor},children:w.displayName}),l.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",w.products.length," parts)"]})]}),l.jsx("div",{className:"space-y-2",children:w.products.map((T,R)=>{var S;const E=(S=t.carfixValueProducts)==null?void 0:S.includes(T.sku),O=T.unitPrice??T.price;return l.jsxs("div",{className:"flex items-center gap-3 p-2.5 rounded-xl transition-all hover:bg-slate-50 cursor-pointer border border-[#E2E8F0]",onClick:()=>s==null?void 0:s(T.sku),children:[l.jsx("div",{className:"flex-shrink-0 rounded-lg bg-white overflow-hidden border border-[#E2E8F0]",style:{width:"56px",height:"56px",minWidth:"56px",maxWidth:"56px"},children:l.jsx("img",{src:T.productImageUrl||ks.productImage(T.sku),alt:T.name,className:"object-contain",style:{width:"100%",height:"100%",maxWidth:"56px",maxHeight:"56px",padding:"6px"},onError:C=>{C.target.src="/placeholder.svg"}})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[l.jsx("span",{className:"text-xs font-semibold text-[#0F172A]",children:T.brandFullName||T.brand}),E&&l.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"rgba(0, 82, 204, 0.1)",color:"#0052CC"},children:"CFX VALUE"}),T.isMultiQty&&T.perCarQty>1&&l.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",T.perCarQty]}),T.isRotor&&l.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#EFF6FF",color:"#1D4ED8"},children:"Pair"})]}),l.jsx("p",{className:"text-xs text-[#64748B] line-clamp-1",children:T.name})]}),l.jsxs("div",{className:"text-right flex-shrink-0",children:[l.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:st(T.displayPrice)}),T.isMultiQty&&T.perCarQty>1&&l.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[T.perCarQty,"× ",st(O)," each"]}),T.isRotor&&!T.isMultiQty&&l.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[st(O)," each"]})]})]},`${T.sku}-${R}`)})})]},w.tierName)})})]}),t.bundle_discount_percentage&&t.bundle_discount_percentage>0&&l.jsx("div",{className:"px-4 pb-4",children:l.jsx("div",{className:"rounded-xl p-3 text-center",style:{background:"rgba(34,197,94,0.1)",border:"1px solid rgba(34,197,94,0.2)"},children:l.jsxs("span",{className:"text-sm font-semibold text-[#22C55E]",children:["Bundle saves you ",t.bundle_discount_percentage,"%"]})})})]})]})},fo=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:y,onToggleMute:m,isSpeaking:_,products:k,servicePackages:x,highlightedPartType:j,highlightedProduct:w,scrollToCategory:A,onScrollToCategoryComplete:T,onProductClick:R,onPackageSelect:E,isResearching:O,onAddToCart:S,onNavigateToProductPage:C,onQuickReply:D,onInterrupt:N,vehicle:F,onChangeVehicle:H,pendingVariants:U,pendingVariantMake:ie,pendingVariantModel:Y,onVariantSelect:M,bobOffset:G=0,bobScale:pe=100})=>{const se=p.useRef(null),ne=Sd(se),[_e,$]=p.useState("center"),[re,z]=p.useState("hidden"),[I,ke]=p.useState("products"),[je,ve]=p.useState(null),[Se,Ae]=p.useState(null),Ke=k.length>0||x.length>0,Ye=((U==null?void 0:U.length)??0)>0,Ie=Ke||Ye,We=(I==="productDetail"?70:_e==="center"&&!Ie?140:98)*pe/100;p.useEffect(()=>{if(O&&re!=="loading"&&re!=="visible")z("loading"),_e==="center"&&$("partial-left");else if(Ie&&re!=="visible")if(_e==="center"){$("partial-left"),z("transitioning");const fe=setTimeout(()=>{z("visible")},400);return()=>clearTimeout(fe)}else z("visible");else!Ie&&!O&&re!=="hidden"&&(z("hidden"),$("center"))},[Ie,O,re,_e]);const P=fe=>{if(C){C(fe),R==null||R(fe);return}ve(fe),ke("productDetail"),R==null||R(fe)},ae=()=>{ve(null),Ae(null),ke("products")},Ce=fe=>{console.log("[ContainedMobileBobLayout] Package selected:",fe.title),Ae(fe),ke("packageDetail"),E==null||E(fe)},J=re!=="hidden"&&I==="products",Le=re!=="hidden";return l.jsxs("div",{ref:se,className:"absolute inset-0",style:{height:ne?`${ne}px`:"100%",overflow:"clip",isolation:"isolate",willChange:"height",WebkitUserSelect:"none",userSelect:"none",WebkitTouchCallout:"none"},onContextMenu:fe=>fe.preventDefault(),children:[r&&l.jsx("div",{className:"absolute inset-0 z-0 transition-all duration-500 ease-out",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:Le?"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)":"none",transform:Le?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}}),l.jsx(an,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:We,position:_e,verticalOffset:G}),l.jsx(on,{products:k,servicePackages:x,highlightedPartType:j,highlightedProduct:w,scrollToCategory:A,onScrollToCategoryComplete:T,onProductClick:P,onPackageSelect:Ce,isResearching:O,visible:J,counterHeightPercent:n,hasVehicle:!!F,onAddToCart:S,vehicleMakeModel:F?`${F.make||""} ${F.model||""}`.trim():void 0,pendingVariants:U,pendingVariantMake:ie,pendingVariantModel:Y,onVariantSelect:M}),I==="productDetail"&&je&&l.jsx(Ed,{product:je,onBack:ae,onAddToCart:S,onNavigateToProductPage:C}),I==="packageDetail"&&Se&&l.jsx(ho,{package:Se,onBack:ae,onAddToCart:fe=>{fe.forEach(Ee=>{var ue;S==null||S({id:Ee.sku||((ue=Ee.partslotId)==null?void 0:ue.toString())||"unknown",name:Ee.name||Ee.partslotName||"Unknown Part",brand:Ee.brand,price:Ee.displayPrice,sku:Ee.sku,partNumber:Ee.partNumber,image_url:Ee.productImageUrl,partslotDescription:Ee.partslotName})})},onNavigateToProductPage:fe=>{const Ee=k.find(ue=>ue.sku===fe);Ee&&C&&C(Ee)}}),I==="products"&&l.jsx(uo,{messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:y,onToggleMute:m,isSpeaking:_,onQuickReply:D,onInterrupt:N,counterHeightPercent:n})]})},ni=({variant:t="inline",initialState:e="idle",showChat:r=!0,className:s="",backdropUrl:n,counterOverlayUrl:i,counterHeightPercent:a,defaultBobImage:o,verticalOffset:c=0,scale:u=100,sessionToken:d,embedded:h=!1,initialVehicle:g})=>{var pt,We;const{callbacks:f}=$t(),[y,m]=p.useState(!1),{animationState:_,setAnimationState:k,getCurrentImage:x,getCurrentOffset:j,getCurrentScale:w,availableStates:A}=Ka({isSpeaking:y}),{activeBackdrop:T}=Va(),[R,E]=p.useState([]),[O,S]=p.useState([]),[C,D]=p.useState(null),[N,F]=p.useState(null),[H,U]=p.useState(!1),[ie,Y]=p.useState(null),M=p.useRef(new Set);p.useEffect(()=>{const P=new Set(R.map(ae=>ae.partslotDescription||"Other Parts").filter(Boolean));M.current=P},[R]),p.useEffect(()=>{if(O.length>0){const P=new Set(M.current);O.forEach(ae=>{ae.title&&P.add(ae.title)}),M.current=P}},[O]);const[G,pe]=p.useState([]),[se,ne]=p.useState(""),[_e,$]=p.useState(""),re=p.useRef(null),z=p.useRef(null);p.useEffect(()=>{re.current=P=>{if(U(!1),!P||P.length===0){console.log("[Bob] Clearing products (empty array received)"),E([]);return}const ae=P[0];console.log("[Bob] First part raw keys:",Object.keys(ae));const Ce=P.map((J,Le)=>{const fe=J.Brand||J.brand||"";return{id:J.SKU||J.sku||`part-${Le}`,name:J["Part Product Type"]||J.partslot_description||J.name||"Unknown Part",brand:fe,price:J["Metro Retail Price"]||J.price||0,sku:J.SKU||J.sku,partNumber:J["Part Number"]||J.part_number||null,partslotDescription:J["Part Product Type"]||J.partslot_description||J.partslotDescription||J.part_type||J.category||"General Parts",image_url:J.image_url||(J.SKU||J.sku?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${J.SKU||J.sku}.jpg`:void 0),webDescription:J["Web Part Description"]||J.web_description||null,brandDescription:J["Brand Description"]||J.brand_description||null,perCarQty:J["Per Car Qty"]||J.per_car_qty||1,volume:J.volume||null,viscosity:J.viscosity||null,brandImageUrl:fe?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${fe.replace(/\s+/g,"")}.jpg`:void 0}});E(J=>{var tr;const Le=new Set(J.map($e=>$e.sku).filter(Boolean)),fe=new Set(J.map($e=>$e.partslotDescription||"Other Parts")),Ee=new Set,ue=Ce.filter($e=>!$e.sku||Ee.has($e.sku)||Le.has($e.sku)?!1:(Ee.add($e.sku),!0));if(console.log("[Bob] Products mapped:",Ce.length,"-> new unique:",ue.length,"-> existing:",J.length),ue.length>0&&J.length>0){const $e=(tr=ue.find(rr=>!fe.has(rr.partslotDescription||"Other Parts")))==null?void 0:tr.partslotDescription;$e&&setTimeout(()=>Y($e),100)}return[...J,...ue]})},z.current=P=>{if(!P||P.length===0){console.log("[Bob] Clearing service packages (empty array received)"),S([]);return}console.log("[Bob] Service packages received via stable ref:",P.length),S(P)}},[]);const I=Ha({setAnimationState:k,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{k(A.find(P=>P.includes("idle"))||"idle")},onResearchStart:()=>{},onPartsResearchStart:()=>{U(!0)},onVariantSelectionRequired:(P,ae,Ce)=>{U(!1),pe(P),ne(ae),$(Ce)},onHighlightPart:P=>{D(P),setTimeout(()=>D(null),8e3)},onHighlightProduct:P=>{F(P),setTimeout(()=>F(null),8e3)},onAutoFetchComplete:()=>{U(!1)},shelfCategoriesRef:M,initialVehicle:g});p.useEffect(()=>{I.identifiedVehicle&&(pe([]),ne(""),$(""))},[(pt=I.identifiedVehicle)==null?void 0:pt.vehicle_id,(We=I.identifiedVehicle)==null?void 0:We.id]);const ke=P=>{I.sendDirectMessage(`Option ${P.optionNumber}`)};p.useEffect(()=>{m(I.isSpeaking)},[I.isSpeaking]),p.useEffect(()=>{const P=f.onPartsFound,ae=f.onServicePackagesFound;return f.onPartsFound=Ce=>{var J;(J=re.current)==null||J.call(re,Ce),P==null||P(Ce)},f.onServicePackagesFound=Ce=>{var J;(J=z.current)==null||J.call(z,Ce),ae==null||ae(Ce)},()=>{f.onPartsFound=P,f.onServicePackagesFound=ae}},[f]);const je=n||(T==null?void 0:T.image_url),ve=i||(T==null?void 0:T.counter_overlay_url)||void 0,Se=a||(T==null?void 0:T.counter_height_percent)||12,Ae=x()||o||"",Ke=j(),Ye=w(),Ie=p.useCallback(P=>{var J,Le,fe,Ee;const ae=Array.isArray(P)?P:[P],Ce=((Le=(J=I.identifiedVehicle)==null?void 0:J.vehicle_id)==null?void 0:Le.toString())||((Ee=(fe=I.identifiedVehicle)==null?void 0:fe.id)==null?void 0:Ee.toString());ae.forEach(ue=>{var $e;const tr={product_id:ue.id||ue.sku||"",product_name:ue.name,quantity:ue.quantity||1,unit_price:ue.price,sku:ue.sku,brand:ue.brand,image_url:ue.image_url,vehicle_id:Ce,...ue._bundleMeta||{}};($e=f.onAddToCart)==null||$e.call(f,tr)})},[I.identifiedVehicle,f]);if(t==="mobile"||t==="fullscreen")return l.jsx(co,{currentImage:Ae,animationState:_,backdropUrl:je,counterOverlayUrl:ve,counterHeightPercent:Se,bobOffset:Ke,bobScale:Ye,embedded:h,messages:I.messages,input:I.input,setInput:I.setInput,isLoading:I.isLoading,onSend:I.handleSend,onKeyPress:I.handleKeyPress,onInputFocus:I.handleInputFocus,onInputBlur:I.handleInputBlur,chatEndRef:I.chatEndRef,isMuted:I.isMuted,onToggleMute:I.toggleMute,isSpeaking:I.isSpeaking,products:R,servicePackages:O,highlightedPartType:C,highlightedProduct:N,scrollToCategory:ie,onScrollToCategoryComplete:()=>Y(null),onAddToCart:Ie,onNavigateToProductPage:P=>{var ae;return(ae=f.onNavigateToProductPage)==null?void 0:ae.call(f,P)},onQuickReply:P=>{var ae;return(ae=f.onNavigateToProductPage)==null?void 0:ae.call(f,{url:P})},onPackageSelect:P=>console.log("[BobWidget] Package selected:",P),isResearching:H,vehicle:I.identifiedVehicle,pendingVariants:G,pendingVariantMake:se,pendingVariantModel:_e,onVariantSelect:ke,onInterrupt:I.stopAllAudio});if(t==="inline"&&r)return l.jsx("div",{className:`relative w-full h-full ${s}`,children:l.jsx(fo,{currentImage:Ae,animationState:_,backdropUrl:je,counterOverlayUrl:ve,counterHeightPercent:Se,bobOffset:Ke,bobScale:Ye,messages:I.messages,input:I.input,setInput:I.setInput,isLoading:I.isLoading,onSend:I.handleSend,onKeyPress:I.handleKeyPress,onInputFocus:I.handleInputFocus,onInputBlur:I.handleInputBlur,chatEndRef:I.chatEndRef,isMuted:I.isMuted,onToggleMute:I.toggleMute,isSpeaking:I.isSpeaking,products:R,servicePackages:O,highlightedPartType:C,highlightedProduct:N,scrollToCategory:ie,onScrollToCategoryComplete:()=>Y(null),onAddToCart:Ie,onNavigateToProductPage:P=>{var ae;return(ae=f.onNavigateToProductPage)==null?void 0:ae.call(f,P)},onQuickReply:P=>{var ae;return(ae=f.onNavigateToProductPage)==null?void 0:ae.call(f,{url:P})},onPackageSelect:P=>console.log("[BobWidget] Package selected:",P),isResearching:H,vehicle:I.identifiedVehicle,pendingVariants:G,pendingVariantMake:se,pendingVariantModel:_e,onVariantSelect:ke,onInterrupt:I.stopAllAudio})});const Ve={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return l.jsxs("div",{className:`${Ve[t]||""} ${s}`,children:[Ae&&l.jsx(Ga,{currentImage:Ae,animationState:_,backdropUrl:je,counterOverlayUrl:ve,counterHeightPercent:Se,verticalOffset:Ke,scale:Ye}),r&&l.jsx(Za,{messages:I.messages,input:I.input,setInput:I.setInput,isLoading:I.isLoading,onSend:I.handleSend,onKeyPress:I.handleKeyPress,onInputFocus:I.handleInputFocus,onInputBlur:I.handleInputBlur,chatEndRef:I.chatEndRef,isMuted:I.isMuted,onToggleMute:I.toggleMute,isSpeaking:I.isSpeaking})]})},po=(t=!0)=>{const[e,r]=p.useState("prompt"),s=p.useRef(!1);return p.useEffect(()=>{if(!t)return;navigator.permissions?navigator.permissions.query({name:"microphone"}).then(i=>{r(i.state),i.state!=="granted"&&(i.state==="prompt"&&!s.current&&(s.current=!0,navigator.mediaDevices.getUserMedia({audio:!0}).then(a=>{a.getTracks().forEach(o=>o.stop()),r("granted")}).catch(()=>r("denied"))),i.addEventListener("change",()=>{r(i.state)}))}).catch(()=>{n()}):n();function n(){var i;if(!s.current){if(!((i=navigator.mediaDevices)!=null&&i.getUserMedia)){r("unsupported");return}s.current=!0,navigator.mediaDevices.getUserMedia({audio:!0}).then(a=>{a.getTracks().forEach(o=>o.stop()),r("granted")}).catch(()=>r("denied"))}}},[t]),{micPermission:e}},jd=({bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,variant:n="mobile",initialState:i,showChat:a,className:o,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:g,scale:f,ga4Config:y,analyticsEnabled:m=!0,bottomOffset:_=0,zIndexBase:k=50,embedded:x=!1})=>{const{micPermission:j}=po(!0),w=p.useRef(null);return p.useEffect(()=>Ma(w.current),[]),p.useEffect(()=>{console.log("[BobWidget] Initialized",{version:Ft,variant:n,bottomOffset:_,zIndexBase:k,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:m,micPermission:j})},[n,_,k,t.supabaseUrl,e.baseUrl,m,j]),l.jsx("div",{ref:w,className:"bob-widget-root",style:{width:"100%",height:"100%"},children:l.jsx(Zn,{bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,ga4Config:y,analyticsEnabled:m,bottomOffset:_,zIndexBase:k,children:l.jsx(ni,{variant:n,initialState:i,showChat:a,className:o,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:g,scale:f,embedded:x})})})};function Td(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function Rd(){const t=[];if(typeof window>"u")return t;const e=document.querySelector(".bob-widget-root");if(!e)return t.push("bob-widget-root not found in DOM"),t;const r=window.getComputedStyle(e),s=e.parentElement;return s&&window.getComputedStyle(s).overflow==="hidden"&&t.push("Parent has overflow:hidden - may clip Bob"),r.transform!=="none"&&r.transform!=="matrix(1, 0, 0, 1, 0, 0)"&&t.push(`Unexpected transform on root: ${r.transform}`),r.isolation!=="isolate"&&t.push("Isolation not properly set"),t}const go=({partnerConfig:t,sessionToken:e})=>{const[r,s]=p.useState(null),[n,i]=p.useState([]),[a,o]=p.useState(!1);if(p.useEffect(()=>{const u=()=>{var g;const d=window.innerWidth,h=window.innerHeight;s({viewport:{width:d,height:h,deviceType:Td(d)},origin:window.location.origin,originAllowed:((g=t==null?void 0:t.allowed_origins)==null?void 0:g.some(f=>f===window.location.origin||f.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),i(Rd())};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[t]),!r)return null;const c=({ok:u,label:d})=>l.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,background:u?"rgba(34, 197, 94, 0.2)":"rgba(239, 68, 68, 0.2)",color:u?"#22c55e":"#ef4444"},children:[u?"✓":"✗"," ",d]});return l.jsxs("div",{style:{position:"fixed",top:"8px",right:"8px",zIndex:99999,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace',fontSize:"11px",lineHeight:1.4},children:[l.jsx("button",{onClick:()=>o(!a),style:{position:"absolute",top:0,right:0,width:"24px",height:"24px",background:"rgba(0, 0, 0, 0.8)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:a?"🔍":"✕"}),!a&&l.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"8px",padding:"12px",color:"#fff",maxWidth:"320px",backdropFilter:"blur(8px)"},children:[l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"12px",paddingBottom:"8px",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[l.jsx("span",{style:{fontSize:"14px"},children:"🔧"}),l.jsxs("span",{style:{fontWeight:600},children:["Bob Debug v",Ft]})]}),l.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginBottom:"12px"},children:[l.jsx(c,{ok:!!t,label:`Partner: ${(t==null?void 0:t.partner_code)||"none"}`}),l.jsx(c,{ok:!!e,label:e?"Session":"No Session"}),l.jsx(c,{ok:r.originAllowed,label:"Origin"})]}),l.jsxs("div",{style:{display:"grid",gap:"6px"},children:[l.jsx(Br,{label:"Viewport",value:`${r.viewport.width}×${r.viewport.height} (${r.viewport.deviceType})`}),l.jsx(Br,{label:"Origin",value:r.origin}),l.jsx(Br,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),l.jsx(Br,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),l.jsx(Br,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),l.jsx(Br,{label:"Overlay",value:`${(((t==null?void 0:t.backdrop_overlay_opacity)??.15)*100).toFixed(0)}%`})]}),(t==null?void 0:t.feature_flags)&&l.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[l.jsx("div",{style:{color:"rgba(255,255,255,0.5)",marginBottom:"4px"},children:"Features:"}),l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Object.entries(t.feature_flags).map(([u,d])=>l.jsx(c,{ok:!!d,label:u.replace(/([A-Z])/g," $1").trim()},u))})]}),n.length>0&&l.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[l.jsx("div",{style:{color:"#ef4444",marginBottom:"4px"},children:"⚠️ CSS Conflicts:"}),n.map((u,d)=>l.jsxs("div",{style:{color:"#fca5a5",fontSize:"10px"},children:["• ",u]},d))]}),l.jsx("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.4)",fontSize:"10px"},children:r.timestamp})]})]})},Br=({label:t,value:e})=>l.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px"},children:[l.jsxs("span",{style:{color:"rgba(255,255,255,0.5)"},children:[t,":"]}),l.jsx("span",{style:{color:"#fff",textAlign:"right",wordBreak:"break-all"},children:e})]}),Ji="https://gjoguxzstsihhxvdgpto.supabase.co",Qi="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function Cd(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 mo(t){const[e,r]=p.useState(null),[s,n]=p.useState(!0),[i,a]=p.useState(null),[o,c]=p.useState(!1),[u,d]=p.useState(null),h=p.useCallback(async()=>{if(!t){n(!1),a(new Error("Partner code is required"));return}n(!0),a(null);try{const g=On(Ji,Qi);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:f,error:y}=await g.from("bob_partners").select("*").eq("partner_code",t).eq("is_active",!0).maybeSingle();if(y)throw new Error(`Failed to load partner config: ${y.message}`);if(!f)throw new Error(`Partner "${t}" not found or inactive`);const m=f,_=typeof window<"u"?window.location.origin:"",k=Cd(m.allowed_origins||[],_);!k&&_&&(console.warn(`[BobWidget] Origin "${_}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",m.allowed_origins));const x=On(m.bob_supabase_url||Ji,m.bob_supabase_key||Qi,{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:k}),r(m),c(k),d(x)}catch(g){const f=g instanceof Error?g:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",f),a(f)}finally{n(!1)}},[t]);return p.useEffect(()=>{h()},[h]),{config:e,isLoading:s,error:i,isOriginAllowed:o,supabaseClient:u,reload:h}}function bo(t,e,r){return t!=null&&t.feature_flags?t.feature_flags[e]??r:r}const Ad=()=>l.jsxs("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #0a1628 0%, #0f2137 100%)"},children:[l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[l.jsx("div",{style:{width:"48px",height:"48px",border:"4px solid rgba(0, 102, 204, 0.3)",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"}}),l.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"14px"},children:"Loading Bob..."})]}),l.jsx("style",{children:`
|
|
69
|
+
Request ID: ${c}`),u){let w=`
|
|
70
|
+
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}`);w+=`
|
|
71
|
+
- ${S}`}k+=w}return`${m}
|
|
72
|
+
${k}`}class Fe extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}}class Ys extends Fe{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function qc({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 Fe({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 Fe({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 Fe({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 Fe({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 Fe({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Fe({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new Fe({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Fe({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 Fe({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Fe({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 Fe({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 Fe({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 Fe({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function zc({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 Fe({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Fe({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 Fe({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Fe({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Fe({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 Fe({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class Hc{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Kc=new Hc;function Vc(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:s}=t,n=rn(t,["challenge","user","excludeCredentials"]),i=qr(e).buffer,a=Object.assign(Object.assign({},r),{id:qr(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let c=0;c<s.length;c++){const u=s[c];o.excludeCredentials[c]=Object.assign(Object.assign({},u),{id:qr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function Gc(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,s=rn(t,["challenge","allowCredentials"]),n=qr(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const o=r[a];i.allowCredentials[a]=Object.assign(Object.assign({},o),{id:qr(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return i}function Jc(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:mr(new Uint8Array(t.response.attestationObject)),clientDataJSON:mr(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Qc(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:mr(new Uint8Array(n.authenticatorData)),clientDataJSON:mr(new Uint8Array(n.clientDataJSON)),signature:mr(new Uint8Array(n.signature)),userHandle:n.userHandle?mr(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 Ni(){var t,e;return!!(He()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Yc(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ys("Browser returned unexpected credential type",e)}:{data:null,error:new Ys("Empty credential response",e)}}catch(e){return{data:null,error:qc({error:e,options:t})}}}async function Xc(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ys("Browser returned unexpected credential type",e)}:{data:null,error:new Ys("Empty credential response",e)}}catch(e){return{data:null,error:zc({error:e,options:t})}}}const Zc={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},eu={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Xs(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const i in n){const a=n[i];if(a!==void 0)if(Array.isArray(a))s[i]=a;else if(r(a))s[i]=a;else if(e(a)){const o=s[i];e(o)?s[i]=Xs(o,a):s[i]=Xs(a)}else s[i]=a}return s}function tu(t,e){return Xs(Zc,t,e||{})}function ru(t,e){return Xs(eu,t,e||{})}class su{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},i){var a;try{const{data:o,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:c};const u=n??Kc.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:d}=o.webauthn.credential_options.publicKey;if(!d.name){const h=s;if(h)d.name=`${d.id}:${h}`;else{const f=(await this.client.getUser()).data.user,y=((a=f==null?void 0:f.user_metadata)===null||a===void 0?void 0:a.name)||(f==null?void 0:f.email)||(f==null?void 0:f.id)||"User";d.name=`${d.id}:${y}`}}d.displayName||(d.displayName=d.name)}switch(o.webauthn.type){case"create":{const d=tu(o.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:h,error:p}=await Yc({publicKey:d,signal:u});return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:p}}case"request":{const d=ru(o.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:p}=await Xc(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:d,signal:u}));return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:p}}}}catch(o){return q(o)?{data:null,error:o}:{data:null,error:new br("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new vs("rpId is required for WebAuthn authentication")};try{if(!Ni())return{data:null,error:new br("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!a)return{data:null,error:o};const{webauthn:c}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:s,credential_response:c.credential_response}})}catch(a){return q(a)?{data:null,error:a}:{data:null,error:new br("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 vs("rpId is required for WebAuthn registration")};try{if(!Ni())return{data:null,error:new br("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(d=>{var h;return(h=d.data)===null||h===void 0?void 0:h.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&p.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d==null?void 0:d.id}):void 0),{data:null,error:o};const{data:c,error:u}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return c?this._verify({factorId:a.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(a){return q(a)?{data:null,error:a}:{data:null,error:new br("Unexpected error in register",a)}}}}Dc();const nu={url:tc,storageKey:rc,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:sc,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Fi(t,e,r){return await r()}const Br={};class ws{get jwks(){var e,r;return(r=(e=Br[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Br[this.storageKey]=Object.assign(Object.assign({},Br[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Br[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Br[this.storageKey]=Object.assign(Object.assign({},Br[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({},nu),e);if(this.storageKey=i.storageKey,this.instanceID=(r=ws.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,ws.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&He()){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 Lc({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ja(i.fetch),this.lock=i.lock||Fi,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&&He()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=$c:this.lock=Fi,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 su(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:Ea()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Pi(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Pi(this.memoryStorage)),He()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}i.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${_a}) ${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(He()&&(r=mc(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),He()&&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),lc(i)){const c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:a,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return q(r)?this._returnResult({error:r}):this._returnResult({error:new br("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await J(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:Et}),{data:a,error:o}=i;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(q(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){const{email:d,password:h,options:p}=e;let f=null,y=null;this.flowType==="pkce"&&([f,y]=await Nr(this.storage,this.storageKey)),i=await J(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p==null?void 0:p.emailRedirectTo,body:{email:d,password:h,data:(r=p==null?void 0:p.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken},code_challenge:f,code_challenge_method:y},xform:Et})}else if("phone"in e){const{phone:d,password:h,options:p}=e;i=await J(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(s=p==null?void 0:p.data)!==null&&s!==void 0?s:{},channel:(n=p==null?void 0:p.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken}},xform:Et})}else throw new qs("You must provide either an email or phone number and a password");const{data:a,error:o}=i;if(o||!a)return await ze(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(await ze(this.storage,`${this.storageKey}-code-verifier`),q(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:o}=e;r=await J(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Ai})}else if("phone"in e){const{phone:i,password:a,options:o}=e;r=await J(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Ai})}else throw new qs("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const i=new Ir;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,a,o,c,u,d,h,p;let f,y;if("message"in e)f=e.message,y=e.signature;else{const{chain:b,wallet:m,statement:k,options:w}=e;let S;if(He())if(typeof m=="object")S=m;else{const O=window;if("ethereum"in O&&typeof O.ethereum=="object"&&"request"in O.ethereum&&typeof O.ethereum.request=="function")S=O.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof m!="object"||!(w!=null&&w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=m}const x=new URL((r=w==null?void 0:w.url)!==null&&r!==void 0?r:window.location.href),A=await S.request({method:"eth_requestAccounts"}).then(O=>O).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!A||A.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const T=Ra(A[0]);let R=(s=w==null?void 0:w.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!R){const O=await S.request({method:"eth_chainId"});R=Uc(O)}const E={domain:x.host,address:T,statement:k,uri:x.href,version:"1",chainId:R,nonce:(n=w==null?void 0:w.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=w==null?void 0:w.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=w==null?void 0:w.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(c=w==null?void 0:w.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=w==null?void 0:w.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=w==null?void 0:w.signInWithEthereum)===null||d===void 0?void 0:d.resources};f=Wc(E),y=await S.request({method:"personal_sign",params:[Mc(f),T]})}try{const{data:b,error:m}=await J(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:y},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:Et});if(m)throw m;if(!b||!b.session||!b.user){const k=new Ir;return this._returnResult({data:{user:null,session:null},error:k})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:m})}catch(b){if(q(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async signInWithSolana(e){var r,s,n,i,a,o,c,u,d,h,p,f;let y,b;if("message"in e)y=e.message,b=e.signature;else{const{chain:m,wallet:k,statement:w,options:S}=e;let x;if(He())if(typeof k=="object")x=k;else{const T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))x=T.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof k!="object"||!(S!=null&&S.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=k}const A=new URL((r=S==null?void 0:S.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in x&&x.signIn){const T=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},S==null?void 0:S.signInWithSolana),{version:"1",domain:A.host,uri:A.href}),w?{statement:w}:null));let R;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")R=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)R=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in R&&"signature"in R&&(typeof R.signedMessage=="string"||R.signedMessage instanceof Uint8Array)&&R.signature instanceof Uint8Array)y=typeof R.signedMessage=="string"?R.signedMessage:new TextDecoder().decode(R.signedMessage),b=R.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${A.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...w?["",w,""]:[""],"Version: 1",`URI: ${A.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}`]:[],...!((o=S==null?void 0:S.signInWithSolana)===null||o===void 0)&&o.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(R=>`- ${R}`)]:[]].join(`
|
|
73
|
+
`);const T=await x.signMessage(new TextEncoder().encode(y),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");b=T}}try{const{data:m,error:k}=await J(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:mr(b)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:Et});if(k)throw k;if(!m||!m.session||!m.user){const w=new Ir;return this._returnResult({data:{user:null,session:null},error:w})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:k})}catch(m){if(q(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e){const r=await pr(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new cc;const{data:i,error:a}=await J(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:Et});if(await ze(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const o=new Ir;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:a})}catch(i){if(await ze(this.storage,`${this.storageKey}-code-verifier`),q(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,o=await J(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:Et}),{data:c,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){const d=new Ir;return this._returnResult({data:{user:null,session:null},error:d})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(r){if(q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;try{if("email"in e){const{email:o,options:c}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Nr(this.storage,this.storageKey));const{error:h}=await J(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(s=c==null?void 0:c.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:o,options:c}=e,{data:u,error:d}=await J(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:d})}throw new qs("You must provide either an email or phone number.")}catch(o){if(await ze(this.storage,`${this.storageKey}-code-verifier`),q(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:o}=await J(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Et});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const c=a.session,u=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(n){if(q(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,a;try{let o=null,c=null;this.flowType==="pkce"&&([o,c]=await Nr(this.storage,this.storageKey));const u=await J(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:c}),headers:this.headers,xform:Nc});return!((i=u.data)===null||i===void 0)&&i.url&&He()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await ze(this.storage,`${this.storageKey}-code-verifier`),q(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new ht;const{error:n}=await J(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(q(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e,{error:a}=await J(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:a,error:o}=await J(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o})}throw new qs("You must provide either an email or phone number and a type")}catch(r){if(q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await pr(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()<pn:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await pr(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=mn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Ac(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 J(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:tr}):await this._useSession(async r=>{var s,n,i;const{data:a,error:o}=r;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ht}:await J(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:tr})})}catch(r){if(q(r))return gn(r)&&(await this._removeSession(),await ze(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 ht;const a=n.session;let o=null,c=null;this.flowType==="pkce"&&e.email!=null&&([o,c]=await Nr(this.storage,this.storageKey));const{data:u,error:d}=await J(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:c}),jwt:a.access_token,xform:tr});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 ze(this.storage,`${this.storageKey}-code-verifier`),q(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ht;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Hs(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:o,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(q(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:a,error:o}=r;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new ht;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!He())throw new zs("No browser detected.");if(e.error||e.error_description||e.error_code)throw new zs(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 ki("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new zs("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 ki("No code detected.");const{data:w,error:S}=await this._exchangeCodeForSession(e.code);if(S)throw S;const x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:w.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:a,expires_in:o,expires_at:c,token_type:u}=e;if(!i||!o||!a||!u)throw new zs("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(o);let p=d+h;c&&(p=parseInt(c));const f=p-d;f*1e3<=Ur&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const y=p-h;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,p,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,p,d);const{data:b,error:m}=await this._getUser(i);if(m)throw m;const k={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:h,expires_at:p,refresh_token:a,token_type:u,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(s){if(q(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await pr(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&&!gn(i))return this._returnResult({error:i});const a=(s=n.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!(oc(o)&&(o.status===404||o.status===401||o.status===403)||gn(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await ze(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=bc(),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 Nr(this.storage,this.storageKey,!0));try{return await J(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 ze(this.storage,`${this.storageKey}-code-verifier`),q(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(q(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async i=>{var a,o,c,u,d;const{data:h,error:p}=i;if(p)throw p;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await J(this.fetch,"GET",f,{headers:this.headers,jwt:(d=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return He()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(q(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:o,token:c,access_token:u,nonce:d}=e,h=await J(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:c,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Et}),{data:p,error:f}=h;return f?this._returnResult({data:{user:null,session:null},error:f}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new Ir}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:f}))}catch(n){if(await ze(this.storage,`${this.storageKey}-code-verifier`),q(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)throw a;return await J(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(q(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await wc(async n=>(n>0&&await vc(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await J(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Et})),(n,i)=>{const a=200*Math.pow(2,n);return i&&bn(i)&&Date.now()+a-s<Ur})}catch(s){if(this._debug(r,"error",s),q(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),He()&&!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 pr(this.storage,this.storageKey);if(n&&this.userStorage){let a=await pr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await Mr(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:mn()}else if(n&&!n.user&&!n.user){const a=await pr(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await ze(this.storage,this.storageKey+"-user"),await Mr(this.storage,this.storageKey,n)):n.user=mn()}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()<pn;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${pn}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),bn(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(n.access_token);!o&&(a!=null&&a.user)?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new ht;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new an;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new ht;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const o={data:i.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(i){if(this._debug(n,"error",i),q(i)){const a={data:null,error:i};return bn(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(c){i.push(c)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await ze(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 Mr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=Ri(n);await Mr(this.storage,this.storageKey,i)}else{const n=Ri(r);await Mr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await ze(this.storage,this.storageKey),await ze(this.storage,this.storageKey+"-code-verifier"),await ze(this.storage,this.storageKey+"-user"),this.userStorage&&await ze(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&He()&&(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(),Ur);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)/Ur);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Ur}ms, refresh threshold is ${On} ticks`),n<=On&&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 Ta)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!He()||!(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 Nr(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});n.push(o.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await J(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(q(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await J(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c==null?void 0:c.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(q(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Jc(e.webauthn.credential_response):Qc(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:c}=await J(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:c}))})}catch(r){if(q(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=await J(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:o}=a;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Vc(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Gc(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(q(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:f}=Hs(e);let y=null;f.aal&&(y=f.aal);let b=y;const{data:{user:m},error:k}=await this.getUser(e);if(k)return this._returnResult({data:null,error:k});((s=(r=m==null?void 0:m.factors)===null||r===void 0?void 0:r.filter(x=>x.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(b="aal2");const S=f.amr||[];return{data:{currentLevel:y,nextLevel:b,currentAuthenticationMethods:S},error:null}}catch(f){if(q(f))return this._returnResult({data:null,error:f});throw f}const{data:{session:a},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=Hs(a.access_token);let u=null;c.aal&&(u=c.aal);let d=u;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const p=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await J(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 ht})})}catch(r){if(q(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new ht});const a=await J(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&He()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(q(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new ht});const a=await J(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&He()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(q(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await J(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 ht})})}catch(e){if(q(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await J(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 ht})})}catch(r){if(q(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+ic>n)return s;const{data:i,error:a}=await J(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:f,error:y}=await this.getSession();if(y||!f.session)return this._returnResult({data:null,error:y});s=f.session.access_token}const{header:n,payload:i,signature:a,raw:{header:o,payload:c}}=Hs(s);r!=null&&r.allowExpired||Tc(i.exp);const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!u){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:n,signature:a},error:null}}const d=Rc(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,pc(`${o}.${c}`)))throw new Nn("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(q(s))return this._returnResult({data:null,error:s});throw s}}}ws.nextInstanceID={};const iu=ws,au="2.101.1";let cs="";typeof Deno<"u"?cs="deno":typeof document<"u"?cs="web":typeof navigator<"u"&&navigator.product==="ReactNative"?cs="react-native":cs="node";const ou={"X-Client-Info":`supabase-js-${cs}/${au}`},lu={headers:ou},cu={schema:"public"},uu={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},du={};function xs(t){"@babel/helpers - typeof";return xs=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},xs(t)}function hu(t,e){if(xs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(xs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function fu(t){var e=hu(t,"string");return xs(e)=="symbol"?e:e+""}function pu(t,e,r){return(e=fu(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Bi(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?Bi(Object(r),!0).forEach(function(s){pu(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Bi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const gu=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),bu=()=>Headers,mu=(t,e,r)=>{const s=gu(r),n=bu();return async(i,a)=>{var o;const c=(o=await e())!==null&&o!==void 0?o:t;let u=new n(a==null?void 0:a.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(i,Oe(Oe({},a),{},{headers:u}))}};function yu(t){return t.endsWith("/")?t:t+"/"}function vu(t,e){var r,s;const{db:n,auth:i,realtime:a,global:o}=t,{db:c,auth:u,realtime:d,global:h}=e,p={db:Oe(Oe({},c),n),auth:Oe(Oe({},u),i),realtime:Oe(Oe({},d),a),storage:{},global:Oe(Oe(Oe({},h),o),{},{headers:Oe(Oe({},(r=h==null?void 0:h.headers)!==null&&r!==void 0?r:{}),(s=o==null?void 0:o.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?p.accessToken=t.accessToken:delete p.accessToken,p}function wu(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(yu(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var xu=class extends iu{constructor(t){super(t)}},_u=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=wu(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:cu,realtime:du,auth:Oe(Oe({},uu),{},{storageKey:a}),global:lu},c=vu(r??{},o);if(this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=c.auth)!==null&&u!==void 0?u:{},this.headers,c.global.fetch)}this.fetch=mu(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 zo(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 ec(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new Bo(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:c,throwOnError:u},d,h){const p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new xu({url:this.authUrl.href,headers:Oe(Oe({},p),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:c,throwOnError:u,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Sl(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 Fn=(t,e,r)=>new _u(t,e,r);function ku(){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}ku()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var Os=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},vr,rr,zr,sa,Su=(sa=class extends Os{constructor(){super();X(this,vr);X(this,rr);X(this,zr);M(this,zr,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){_(this,rr)||this.setEventListener(_(this,zr))}onUnsubscribe(){var e;this.hasListeners()||((e=_(this,rr))==null||e.call(this),M(this,rr,void 0))}setEventListener(e){var r;M(this,zr,e),(r=_(this,rr))==null||r.call(this),M(this,rr,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){_(this,vr)!==e&&(M(this,vr,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof _(this,vr)=="boolean"?_(this,vr):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},vr=new WeakMap,rr=new WeakMap,zr=new WeakMap,sa),ei=new Su,Eu={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Nt,wr,na,ju=(na=class{constructor(){X(this,Nt,Eu);X(this,wr,!1)}setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&_(this,wr)&&t!==_(this,Nt)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:_(this,Nt),provider:t}),M(this,Nt,t),process.env.NODE_ENV!=="production"&&M(this,wr,!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&M(this,wr,!0),_(this,Nt).setTimeout(t,e)}clearTimeout(t){_(this,Nt).clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&M(this,wr,!0),_(this,Nt).setInterval(t,e)}clearInterval(t){_(this,Nt).clearInterval(t)}},Nt=new WeakMap,wr=new WeakMap,na),yr=new ju;function Tu(t){setTimeout(t,0)}var Ru=typeof window>"u"||"Deno"in globalThis;function ot(){}function Cu(t,e){return typeof t=="function"?t(e):t}function Bn(t){return typeof t=="number"&&t>=0&&t!==1/0}function Aa(t,e){return Math.max(t+(e||0)-Date.now(),0)}function cr(t,e){return typeof t=="function"?t(e):t}function wt(t,e){return typeof t=="function"?t(e):t}function Li(t,e){const{type:r="all",exact:s,fetchStatus:n,predicate:i,queryKey:a,stale:o}=t;if(a){if(s){if(e.queryHash!==ti(a,e.options))return!1}else if(!ks(e.queryKey,a))return!1}if(r!=="all"){const c=e.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof o=="boolean"&&e.isStale()!==o||n&&n!==e.state.fetchStatus||i&&!i(e))}function $i(t,e){const{exact:r,status:s,predicate:n,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(r){if(_s(e.options.mutationKey)!==_s(i))return!1}else if(!ks(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||n&&!n(e))}function ti(t,e){return((e==null?void 0:e.queryKeyHashFn)||_s)(t)}function _s(t){return JSON.stringify(t,(e,r)=>Dn(r)?Object.keys(r).sort().reduce((s,n)=>(s[n]=r[n],s),{}):r)}function ks(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>ks(t[r],e[r])):!1}var Au=Object.prototype.hasOwnProperty;function Ln(t,e,r=0){if(t===e)return t;if(r>500)return e;const s=Di(t)&&Di(e);if(!s&&!(Dn(t)&&Dn(e)))return e;const i=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),o=a.length,c=s?new Array(o):{};let u=0;for(let d=0;d<o;d++){const h=s?d:a[d],p=t[h],f=e[h];if(p===f){c[h]=p,(s?d<i:Au.call(t,h))&&u++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){c[h]=f;continue}const y=Ln(p,f,r+1);c[h]=y,y===p&&u++}return i===o&&u===i?t:c}function $n(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 Di(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function Dn(t){if(!Ui(t))return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(!Ui(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function Ui(t){return Object.prototype.toString.call(t)==="[object Object]"}function Ou(t){return new Promise(e=>{yr.setTimeout(e,t)})}function Un(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 Ln(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 Ln(t,e)}return e}function Pu(t,e,r=0){const s=[...t,e];return r&&s.length>r?s.slice(1):s}function Iu(t,e,r=0){const s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}var Zs=Symbol();function Oa(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===Zs&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${t.queryHash}'`),!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===Zs?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function Pa(t,e){return typeof t=="function"?t(...e):!!t}function Nu(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 Ss=(()=>{let t=()=>Ru;return{isServer(){return t()},setIsServer(e){t=e}}})();function Mn(){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 Fu=Tu;function Bu(){let t=[],e=0,r=o=>{o()},s=o=>{o()},n=Fu;const i=o=>{e?t.push(o):n(()=>{r(o)})},a=()=>{const o=t;t=[],o.length&&n(()=>{s(()=>{o.forEach(c=>{r(c)})})})};return{batch:o=>{let c;e++;try{c=o()}finally{e--,e||a()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{r=o},setBatchNotifyFunction:o=>{s=o},setScheduler:o=>{n=o}}}var Ke=Bu(),Hr,sr,Kr,ia,Lu=(ia=class extends Os{constructor(){super();X(this,Hr,!0);X(this,sr);X(this,Kr);M(this,Kr,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",s)}}})}onSubscribe(){_(this,sr)||this.setEventListener(_(this,Kr))}onUnsubscribe(){var e;this.hasListeners()||((e=_(this,sr))==null||e.call(this),M(this,sr,void 0))}setEventListener(e){var r;M(this,Kr,e),(r=_(this,sr))==null||r.call(this),M(this,sr,e(this.setOnline.bind(this)))}setOnline(e){_(this,Hr)!==e&&(M(this,Hr,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return _(this,Hr)}},Hr=new WeakMap,sr=new WeakMap,Kr=new WeakMap,ia),en=new Lu;function $u(t){return Math.min(1e3*2**t,3e4)}function Ia(t){return(t??"online")==="online"?en.isOnline():!0}var Wn=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function Na(t){let e=!1,r=0,s;const n=Mn(),i=()=>n.status!=="pending",a=b=>{var m;if(!i()){const k=new Wn(b);p(k),(m=t.onCancel)==null||m.call(t,k)}},o=()=>{e=!0},c=()=>{e=!1},u=()=>ei.isFocused()&&(t.networkMode==="always"||en.isOnline())&&t.canRun(),d=()=>Ia(t.networkMode)&&t.canRun(),h=b=>{i()||(s==null||s(),n.resolve(b))},p=b=>{i()||(s==null||s(),n.reject(b))},f=()=>new Promise(b=>{var m;s=k=>{(i()||u())&&b(k)},(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(k){b=Promise.reject(k)}Promise.resolve(b).then(h).catch(k=>{var T;if(i())return;const w=t.retry??(Ss.isServer()?0:3),S=t.retryDelay??$u,x=typeof S=="function"?S(r,k):S,A=w===!0||typeof w=="number"&&r<w||typeof w=="function"&&w(r,k);if(e||!A){p(k);return}r++,(T=t.onFail)==null||T.call(t,r,k),Ou(x).then(()=>u()?void 0:f()).then(()=>{e?p(k):y()})})};return{promise:n,status:()=>n.status,cancel:a,continue:()=>(s==null||s(),n),cancelRetry:o,continueRetry:c,canStart:d,start:()=>(d()?y():f().then(y),n)}}var xr,aa,Fa=(aa=class{constructor(){X(this,xr)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Bn(this.gcTime)&&M(this,xr,yr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(Ss.isServer()?1/0:5*60*1e3))}clearGcTimeout(){_(this,xr)&&(yr.clearTimeout(_(this,xr)),M(this,xr,void 0))}},xr=new WeakMap,aa),_r,Vr,vt,kr,We,Es,Sr,ft,Ba,Wt,oa,Du=(oa=class extends Fa{constructor(e){super();X(this,ft);X(this,_r);X(this,Vr);X(this,vt);X(this,kr);X(this,We);X(this,Es);X(this,Sr);M(this,Sr,!1),M(this,Es,e.defaultOptions),this.setOptions(e.options),this.observers=[],M(this,kr,e.client),M(this,vt,_(this,kr).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,M(this,_r,Wi(this.options)),this.state=e.state??_(this,_r),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=_(this,We))==null?void 0:e.promise}setOptions(e){if(this.options={..._(this,Es),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=Wi(this.options);r.data!==void 0&&(this.setState(Mi(r.data,r.dataUpdatedAt)),M(this,_r,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&_(this,vt).remove(this)}setData(e,r){const s=Un(this.state.data,e,this.options);return le(this,ft,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){le(this,ft,Wt).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var s,n;const r=(s=_(this,We))==null?void 0:s.promise;return(n=_(this,We))==null||n.cancel(e),r?r.then(ot).catch(ot):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return _(this,_r)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>wt(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Zs||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>cr(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:!Aa(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=_(this,We))==null||r.continue()}onOnline(){var r;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=_(this,We))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),_(this,vt).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(_(this,We)&&(_(this,Sr)||le(this,ft,Ba).call(this)?_(this,We).cancel({revert:!0}):_(this,We).cancelRetry()),this.scheduleGc()),_(this,vt).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||le(this,ft,Wt).call(this,{type:"invalidate"})}async fetch(e,r){var c,u,d,h,p,f,y,b,m,k,w,S;if(this.state.fetchStatus!=="idle"&&((c=_(this,We))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(_(this,We))return _(this,We).continueRetry(),_(this,We).promise}if(e&&this.setOptions(e),!this.options.queryFn){const x=this.observers.find(A=>A.options.queryFn);x&&this.setOptions(x.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,n=x=>{Object.defineProperty(x,"signal",{enumerable:!0,get:()=>(M(this,Sr,!0),s.signal)})},i=()=>{const x=Oa(this.options,r),T=(()=>{const R={client:_(this,kr),queryKey:this.queryKey,meta:this.meta};return n(R),R})();return M(this,Sr,!1),this.options.persister?this.options.persister(x,T,this):x(T)},o=(()=>{const x={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:_(this,kr),state:this.state,fetchFn:i};return n(x),x})();(u=this.options.behavior)==null||u.onFetch(o,this),M(this,Vr,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=o.fetchOptions)==null?void 0:d.meta))&&le(this,ft,Wt).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta}),M(this,We,Na({initialPromise:r==null?void 0:r.initialPromise,fn:o.fetchFn,onCancel:x=>{x instanceof Wn&&x.revert&&this.setState({..._(this,Vr),fetchStatus:"idle"}),s.abort()},onFail:(x,A)=>{le(this,ft,Wt).call(this,{type:"failed",failureCount:x,error:A})},onPause:()=>{le(this,ft,Wt).call(this,{type:"pause"})},onContinue:()=>{le(this,ft,Wt).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const x=await _(this,We).start();if(x===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(x),(f=(p=_(this,vt).config).onSuccess)==null||f.call(p,x,this),(b=(y=_(this,vt).config).onSettled)==null||b.call(y,x,this.state.error,this),x}catch(x){if(x instanceof Wn){if(x.silent)return _(this,We).promise;if(x.revert){if(this.state.data===void 0)throw x;return this.state.data}}throw le(this,ft,Wt).call(this,{type:"error",error:x}),(k=(m=_(this,vt).config).onError)==null||k.call(m,x,this),(S=(w=_(this,vt).config).onSettled)==null||S.call(w,this.state.data,x,this),x}finally{this.scheduleGc()}}},_r=new WeakMap,Vr=new WeakMap,vt=new WeakMap,kr=new WeakMap,We=new WeakMap,Es=new WeakMap,Sr=new WeakMap,ft=new WeakSet,Ba=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},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,...La(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...Mi(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return M(this,Vr,e.manual?n:void 0),n;case"error":const i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=r(this.state),Ke.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),_(this,vt).notify({query:this,type:"updated",action:e})})},oa);function La(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ia(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Mi(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Wi(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 at,ue,js,et,Er,Gr,Ht,nr,Ts,Jr,Qr,jr,Tr,ir,Yr,be,us,qn,zn,Hn,Kn,Vn,Gn,Jn,$a,la,Uu=(la=class extends Os{constructor(e,r){super();X(this,be);X(this,at);X(this,ue);X(this,js);X(this,et);X(this,Er);X(this,Gr);X(this,Ht);X(this,nr);X(this,Ts);X(this,Jr);X(this,Qr);X(this,jr);X(this,Tr);X(this,ir);X(this,Yr,new Set);this.options=r,M(this,at,e),M(this,nr,null),M(this,Ht,Mn()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(_(this,ue).addObserver(this),qi(_(this,ue),this.options)?le(this,be,us).call(this):this.updateResult(),le(this,be,Kn).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Qn(_(this,ue),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Qn(_(this,ue),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,le(this,be,Vn).call(this),le(this,be,Gn).call(this),_(this,ue).removeObserver(this)}setOptions(e){const r=this.options,s=_(this,ue);if(this.options=_(this,at).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof wt(this.options.enabled,_(this,ue))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");le(this,be,Jn).call(this),_(this,ue).setOptions(this.options),r._defaulted&&!$n(this.options,r)&&_(this,at).getQueryCache().notify({type:"observerOptionsUpdated",query:_(this,ue),observer:this});const n=this.hasListeners();n&&zi(_(this,ue),s,this.options,r)&&le(this,be,us).call(this),this.updateResult(),n&&(_(this,ue)!==s||wt(this.options.enabled,_(this,ue))!==wt(r.enabled,_(this,ue))||cr(this.options.staleTime,_(this,ue))!==cr(r.staleTime,_(this,ue)))&&le(this,be,qn).call(this);const i=le(this,be,zn).call(this);n&&(_(this,ue)!==s||wt(this.options.enabled,_(this,ue))!==wt(r.enabled,_(this,ue))||i!==_(this,ir))&&le(this,be,Hn).call(this,i)}getOptimisticResult(e){const r=_(this,at).getQueryCache().build(_(this,at),e),s=this.createResult(r,e);return Wu(this,s)&&(M(this,et,s),M(this,Gr,this.options),M(this,Er,_(this,ue).state)),s}getCurrentResult(){return _(this,et)}trackResult(e,r){return new Proxy(e,{get:(s,n)=>(this.trackProp(n),r==null||r(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&_(this,Ht).status==="pending"&&_(this,Ht).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){_(this,Yr).add(e)}getCurrentQuery(){return _(this,ue)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=_(this,at).defaultQueryOptions(e),s=_(this,at).getQueryCache().build(_(this,at),r);return s.fetch().then(()=>this.createResult(s,r))}fetch(e){return le(this,be,us).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),_(this,et)))}createResult(e,r){var O;const s=_(this,ue),n=this.options,i=_(this,et),a=_(this,Er),o=_(this,Gr),u=e!==s?e.state:_(this,js),{state:d}=e;let h={...d},p=!1,f;if(r._optimisticResults){const j=this.hasListeners(),C=!j&&qi(e,r),L=j&&zi(e,s,r,n);(C||L)&&(h={...h,...La(d.data,e.options)}),r._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:y,errorUpdatedAt:b,status:m}=h;f=h.data;let k=!1;if(r.placeholderData!==void 0&&f===void 0&&m==="pending"){let j;i!=null&&i.isPlaceholderData&&r.placeholderData===(o==null?void 0:o.placeholderData)?(j=i.data,k=!0):j=typeof r.placeholderData=="function"?r.placeholderData((O=_(this,Qr))==null?void 0:O.state.data,_(this,Qr)):r.placeholderData,j!==void 0&&(m="success",f=Un(i==null?void 0:i.data,j,r),p=!0)}if(r.select&&f!==void 0&&!k)if(i&&f===(a==null?void 0:a.data)&&r.select===_(this,Ts))f=_(this,Jr);else try{M(this,Ts,r.select),f=r.select(f),f=Un(i==null?void 0:i.data,f,r),M(this,Jr,f),M(this,nr,null)}catch(j){M(this,nr,j)}_(this,nr)&&(y=_(this,nr),f=_(this,Jr),b=Date.now(),m="error");const w=h.fetchStatus==="fetching",S=m==="pending",x=m==="error",A=S&&w,T=f!==void 0,E={status:m,fetchStatus:h.fetchStatus,isPending:S,isSuccess:m==="success",isError:x,isInitialLoading:A,isLoading:A,data:f,dataUpdatedAt:h.dataUpdatedAt,error:y,errorUpdatedAt:b,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:w,isRefetching:w&&!S,isLoadingError:x&&!T,isPaused:h.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:x&&T,isStale:ri(e,r),refetch:this.refetch,promise:_(this,Ht),isEnabled:wt(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const j=E.data!==void 0,C=E.status==="error"&&!j,L=B=>{C?B.reject(E.error):j&&B.resolve(E.data)},P=()=>{const B=M(this,Ht,E.promise=Mn());L(B)},F=_(this,Ht);switch(F.status){case"pending":e.queryHash===s.queryHash&&L(F);break;case"fulfilled":(C||E.data!==F.value)&&P();break;case"rejected":(!C||E.error!==F.reason)&&P();break}}return E}updateResult(){const e=_(this,et),r=this.createResult(_(this,ue),this.options);if(M(this,Er,_(this,ue).state),M(this,Gr,this.options),_(this,Er).data!==void 0&&M(this,Qr,_(this,ue)),$n(r,e))return;M(this,et,r);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,i=typeof n=="function"?n():n;if(i==="all"||!i&&!_(this,Yr).size)return!0;const a=new Set(i??_(this,Yr));return this.options.throwOnError&&a.add("error"),Object.keys(_(this,et)).some(o=>{const c=o;return _(this,et)[c]!==e[c]&&a.has(c)})};le(this,be,$a).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&le(this,be,Kn).call(this)}},at=new WeakMap,ue=new WeakMap,js=new WeakMap,et=new WeakMap,Er=new WeakMap,Gr=new WeakMap,Ht=new WeakMap,nr=new WeakMap,Ts=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,jr=new WeakMap,Tr=new WeakMap,ir=new WeakMap,Yr=new WeakMap,be=new WeakSet,us=function(e){le(this,be,Jn).call(this);let r=_(this,ue).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(ot)),r},qn=function(){le(this,be,Vn).call(this);const e=cr(this.options.staleTime,_(this,ue));if(Ss.isServer()||_(this,et).isStale||!Bn(e))return;const s=Aa(_(this,et).dataUpdatedAt,e)+1;M(this,jr,yr.setTimeout(()=>{_(this,et).isStale||this.updateResult()},s))},zn=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(_(this,ue)):this.options.refetchInterval)??!1},Hn=function(e){le(this,be,Gn).call(this),M(this,ir,e),!(Ss.isServer()||wt(this.options.enabled,_(this,ue))===!1||!Bn(_(this,ir))||_(this,ir)===0)&&M(this,Tr,yr.setInterval(()=>{(this.options.refetchIntervalInBackground||ei.isFocused())&&le(this,be,us).call(this)},_(this,ir)))},Kn=function(){le(this,be,qn).call(this),le(this,be,Hn).call(this,le(this,be,zn).call(this))},Vn=function(){_(this,jr)&&(yr.clearTimeout(_(this,jr)),M(this,jr,void 0))},Gn=function(){_(this,Tr)&&(yr.clearInterval(_(this,Tr)),M(this,Tr,void 0))},Jn=function(){const e=_(this,at).getQueryCache().build(_(this,at),this.options);if(e===_(this,ue))return;const r=_(this,ue);M(this,ue,e),M(this,js,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},$a=function(e){Ke.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(_(this,et))}),_(this,at).getQueryCache().notify({query:_(this,ue),type:"observerResultsUpdated"})})},la);function Mu(t,e){return wt(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function qi(t,e){return Mu(t,e)||t.state.data!==void 0&&Qn(t,e,e.refetchOnMount)}function Qn(t,e,r){if(wt(e.enabled,t)!==!1&&cr(e.staleTime,t)!=="static"){const s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&ri(t,e)}return!1}function zi(t,e,r,s){return(t!==e||wt(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&ri(t,r)}function ri(t,e){return wt(e.enabled,t)!==!1&&t.isStaleByTime(cr(e.staleTime,t))}function Wu(t,e){return!$n(t.getCurrentResult(),e)}function Hi(t){return{onFetch:(e,r)=>{var d,h,p,f,y;const s=e.options,n=(p=(h=(d=e.fetchOptions)==null?void 0:d.meta)==null?void 0:h.fetchMore)==null?void 0:p.direction,i=((f=e.state.data)==null?void 0:f.pages)||[],a=((y=e.state.data)==null?void 0:y.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const u=async()=>{let b=!1;const m=S=>{Nu(S,()=>e.signal,()=>b=!0)},k=Oa(e.options,e.fetchOptions),w=async(S,x,A)=>{if(b)return Promise.reject();if(x==null&&S.pages.length)return Promise.resolve(S);const R=(()=>{const C={client:e.client,queryKey:e.queryKey,pageParam:x,direction:A?"backward":"forward",meta:e.options.meta};return m(C),C})(),E=await k(R),{maxPages:O}=e.options,j=A?Iu:Pu;return{pages:j(S.pages,E,O),pageParams:j(S.pageParams,x,O)}};if(n&&i.length){const S=n==="backward",x=S?qu:Ki,A={pages:i,pageParams:a},T=x(s,A);o=await w(A,T,S)}else{const S=t??i.length;do{const x=c===0?a[0]??s.initialPageParam:Ki(s,o);if(c>0&&x==null)break;o=await w(o,x),c++}while(c<S)}return o};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 Ki(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 qu(t,{pages:e,pageParams:r}){var s;return e.length>0?(s=t.getPreviousPageParam)==null?void 0:s.call(t,e[0],e,r[0],r):void 0}var Rs,Ft,Je,Rr,Bt,Zt,ca,zu=(ca=class extends Fa{constructor(e){super();X(this,Bt);X(this,Rs);X(this,Ft);X(this,Je);X(this,Rr);M(this,Rs,e.client),this.mutationId=e.mutationId,M(this,Je,e.mutationCache),M(this,Ft,[]),this.state=e.state||Hu(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){_(this,Ft).includes(e)||(_(this,Ft).push(e),this.clearGcTimeout(),_(this,Je).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){M(this,Ft,_(this,Ft).filter(r=>r!==e)),this.scheduleGc(),_(this,Je).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){_(this,Ft).length||(this.state.status==="pending"?this.scheduleGc():_(this,Je).remove(this))}continue(){var e;return((e=_(this,Rr))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,o,c,u,d,h,p,f,y,b,m,k,w,S,x,A,T,R;const r=()=>{le(this,Bt,Zt).call(this,{type:"continue"})},s={client:_(this,Rs),meta:this.options.meta,mutationKey:this.options.mutationKey};M(this,Rr,Na({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(E,O)=>{le(this,Bt,Zt).call(this,{type:"failed",failureCount:E,error:O})},onPause:()=>{le(this,Bt,Zt).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>_(this,Je).canRun(this)}));const n=this.state.status==="pending",i=!_(this,Rr).canStart();try{if(n)r();else{le(this,Bt,Zt).call(this,{type:"pending",variables:e,isPaused:i}),_(this,Je).config.onMutate&&await _(this,Je).config.onMutate(e,this,s);const O=await((o=(a=this.options).onMutate)==null?void 0:o.call(a,e,s));O!==this.state.context&&le(this,Bt,Zt).call(this,{type:"pending",context:O,variables:e,isPaused:i})}const E=await _(this,Rr).start();return await((u=(c=_(this,Je).config).onSuccess)==null?void 0:u.call(c,E,e,this.state.context,this,s)),await((h=(d=this.options).onSuccess)==null?void 0:h.call(d,E,e,this.state.context,s)),await((f=(p=_(this,Je).config).onSettled)==null?void 0:f.call(p,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)),le(this,Bt,Zt).call(this,{type:"success",data:E}),E}catch(E){try{await((k=(m=_(this,Je).config).onError)==null?void 0:k.call(m,E,e,this.state.context,this,s))}catch(O){Promise.reject(O)}try{await((S=(w=this.options).onError)==null?void 0:S.call(w,E,e,this.state.context,s))}catch(O){Promise.reject(O)}try{await((A=(x=_(this,Je).config).onSettled)==null?void 0:A.call(x,void 0,E,this.state.variables,this.state.context,this,s))}catch(O){Promise.reject(O)}try{await((R=(T=this.options).onSettled)==null?void 0:R.call(T,void 0,E,e,this.state.context,s))}catch(O){Promise.reject(O)}throw le(this,Bt,Zt).call(this,{type:"error",error:E}),E}finally{_(this,Je).runNext(this)}}},Rs=new WeakMap,Ft=new WeakMap,Je=new WeakMap,Rr=new WeakMap,Bt=new WeakSet,Zt=function(e){const r=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=r(this.state),Ke.batch(()=>{_(this,Ft).forEach(s=>{s.onMutationUpdate(e)}),_(this,Je).notify({mutation:this,type:"updated",action:e})})},ca);function Hu(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Kt,Rt,Cs,ua,Ku=(ua=class extends Os{constructor(e={}){super();X(this,Kt);X(this,Rt);X(this,Cs);this.config=e,M(this,Kt,new Set),M(this,Rt,new Map),M(this,Cs,0)}build(e,r,s){const n=new zu({client:e,mutationCache:this,mutationId:++$s(this,Cs)._,options:e.defaultMutationOptions(r),state:s});return this.add(n),n}add(e){_(this,Kt).add(e);const r=Ks(e);if(typeof r=="string"){const s=_(this,Rt).get(r);s?s.push(e):_(this,Rt).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(_(this,Kt).delete(e)){const r=Ks(e);if(typeof r=="string"){const s=_(this,Rt).get(r);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&_(this,Rt).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=Ks(e);if(typeof r=="string"){const s=_(this,Rt).get(r),n=s==null?void 0:s.find(i=>i.state.status==="pending");return!n||n===e}else return!0}runNext(e){var s;const r=Ks(e);if(typeof r=="string"){const n=(s=_(this,Rt).get(r))==null?void 0:s.find(i=>i!==e&&i.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ke.batch(()=>{_(this,Kt).forEach(e=>{this.notify({type:"removed",mutation:e})}),_(this,Kt).clear(),_(this,Rt).clear()})}getAll(){return Array.from(_(this,Kt))}find(e){const r={exact:!0,...e};return this.getAll().find(s=>$i(r,s))}findAll(e={}){return this.getAll().filter(r=>$i(e,r))}notify(e){Ke.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return Ke.batch(()=>Promise.all(e.map(r=>r.continue().catch(ot))))}},Kt=new WeakMap,Rt=new WeakMap,Cs=new WeakMap,ua);function Ks(t){var e;return(e=t.options.scope)==null?void 0:e.id}var Lt,da,Vu=(da=class extends Os{constructor(e={}){super();X(this,Lt);this.config=e,M(this,Lt,new Map)}build(e,r,s){const n=r.queryKey,i=r.queryHash??ti(n,r);let a=this.get(i);return a||(a=new Du({client:e,queryKey:n,queryHash:i,options:e.defaultQueryOptions(r),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(a)),a}add(e){_(this,Lt).has(e.queryHash)||(_(this,Lt).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=_(this,Lt).get(e.queryHash);r&&(e.destroy(),r===e&&_(this,Lt).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ke.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return _(this,Lt).get(e)}getAll(){return[..._(this,Lt).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(s=>Li(r,s))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(s=>Li(e,s)):r}notify(e){Ke.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){Ke.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ke.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Lt=new WeakMap,da),Ae,ar,or,Xr,Zr,lr,es,ts,ha,Gu=(ha=class{constructor(t={}){X(this,Ae);X(this,ar);X(this,or);X(this,Xr);X(this,Zr);X(this,lr);X(this,es);X(this,ts);M(this,Ae,t.queryCache||new Vu),M(this,ar,t.mutationCache||new Ku),M(this,or,t.defaultOptions||{}),M(this,Xr,new Map),M(this,Zr,new Map),M(this,lr,0)}mount(){$s(this,lr)._++,_(this,lr)===1&&(M(this,es,ei.subscribe(async t=>{t&&(await this.resumePausedMutations(),_(this,Ae).onFocus())})),M(this,ts,en.subscribe(async t=>{t&&(await this.resumePausedMutations(),_(this,Ae).onOnline())})))}unmount(){var t,e;$s(this,lr)._--,_(this,lr)===0&&((t=_(this,es))==null||t.call(this),M(this,es,void 0),(e=_(this,ts))==null||e.call(this),M(this,ts,void 0))}isFetching(t){return _(this,Ae).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return _(this,ar).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=_(this,Ae).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=_(this,Ae).build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(cr(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return _(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=_(this,Ae).get(s.queryHash),i=n==null?void 0:n.state.data,a=Cu(e,i);if(a!==void 0)return _(this,Ae).build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return Ke.batch(()=>_(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=_(this,Ae).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=_(this,Ae);Ke.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=_(this,Ae);return Ke.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},s=Ke.batch(()=>_(this,Ae).findAll(t).map(n=>n.cancel(r)));return Promise.all(s).then(ot).catch(ot)}invalidateQueries(t,e={}){return Ke.batch(()=>(_(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=Ke.batch(()=>_(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(ot)),n.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(ot)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=_(this,Ae).build(this,e);return r.isStaleByTime(cr(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(ot).catch(ot)}fetchInfiniteQuery(t){return t.behavior=Hi(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(ot).catch(ot)}ensureInfiniteQueryData(t){return t.behavior=Hi(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return en.isOnline()?_(this,ar).resumePausedMutations():Promise.resolve()}getQueryCache(){return _(this,Ae)}getMutationCache(){return _(this,ar)}getDefaultOptions(){return _(this,or)}setDefaultOptions(t){M(this,or,t)}setQueryDefaults(t,e){_(this,Xr).set(_s(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[..._(this,Xr).values()],r={};return e.forEach(s=>{ks(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){_(this,Zr).set(_s(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[..._(this,Zr).values()],r={};return e.forEach(s=>{ks(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={..._(this,or).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ti(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===Zs&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{..._(this,or).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){_(this,Ae).clear(),_(this,ar).clear()}},Ae=new WeakMap,ar=new WeakMap,or=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,lr=new WeakMap,es=new WeakMap,ts=new WeakMap,ha),Da=xt.createContext(void 0),Ua=t=>{const e=xt.useContext(Da);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Ju=({client:t,children:e})=>(xt.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),l.jsx(Da.Provider,{value:t,children:e})),Ma=xt.createContext(!1),Qu=()=>xt.useContext(Ma);Ma.Provider;function Yu(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Xu=xt.createContext(Yu()),Zu=()=>xt.useContext(Xu),ed=(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))},td=t=>{xt.useEffect(()=>{t.clearReset()},[t])},rd=({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])),sd=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))}},nd=(t,e)=>t.isLoading&&t.isFetching&&!e,id=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,Vi=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function ad(t,e,r){var p,f,y,b;if(process.env.NODE_ENV!=="production"&&(typeof t!="object"||Array.isArray(t)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const s=Qu(),n=Zu(),i=Ua(),a=i.defaultQueryOptions(t);(f=(p=i.getDefaultOptions().queries)==null?void 0:p._experimental_beforeQuery)==null||f.call(p,a);const o=i.getQueryCache().get(a.queryHash);process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),a._optimisticResults=s?"isRestoring":"optimistic",sd(a),ed(a,n,o),td(n);const c=!i.getQueryCache().get(a.queryHash),[u]=xt.useState(()=>new e(i,a)),d=u.getOptimisticResult(a),h=!s&&t.subscribed!==!1;if(xt.useSyncExternalStore(xt.useCallback(m=>{const k=h?u.subscribe(Ke.batchCalls(m)):ot;return u.updateResult(),k},[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),xt.useEffect(()=>{u.setOptions(a)},[a,u]),id(a,d))throw Vi(a,u,n);if(rd({result:d,errorResetBoundary:n,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw d.error;if((b=(y=i.getDefaultOptions().queries)==null?void 0:y._experimental_afterQuery)==null||b.call(y,a,d),a.experimental_prefetchInRender&&!Ss.isServer()&&nd(d,s)){const m=c?Vi(a,u,n):o==null?void 0:o.promise;m==null||m.catch(ot).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?d:u.trackResult(d)}function Ps(t,e){return ad(t,Uu)}const od=5e3,ld=()=>`bob_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;function Wa({ga4Config:t,hostContext:e,callbacks:r,enabled:s=!0,bobSupabaseUrl:n,bobSupabaseKey:i}){const a=g.useRef(ld()),o=g.useRef(!1),c=g.useRef(null),u=g.useRef(!1),d=g.useCallback((E,O)=>{if(!(!(t!=null&&t.measurementId)||typeof window>"u")&&window.gtag){const j={...O,send_to:t.measurementId};t.debug&&console.log("[BobAnalytics] GA4 event:",E,j),window.gtag("event",E,j)}},[t]),h=g.useCallback((E,O={})=>{var C,L,P,F,B,N,H,Z;if(!s)return;const j={event_name:E,timestamp:new Date().toISOString(),session_id:a.current,user_email:(C=e==null?void 0:e.user)==null?void 0:C.email,user_id:(L=e==null?void 0:e.user)==null?void 0:L.id,vehicle_id:(B=(F=(P=e==null?void 0:e.vehicle)==null?void 0:P.selectedVehicle)==null?void 0:F.vehicle_id)==null?void 0:B.toString(),rego:(H=(N=e==null?void 0:e.vehicle)==null?void 0:N.selectedVehicle)==null?void 0:H.rego,parameters:O};d(E,{session_id:j.session_id,user_email:j.user_email,vehicle_id:j.vehicle_id,...O}),(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]),p=g.useCallback(()=>{var E,O,j;o.current||(o.current=!0,h("bob_session_start",{widget_version:Vt,has_vehicle:!!((E=e==null?void 0:e.vehicle)!=null&&E.selectedVehicle),has_user:!!((O=e==null?void 0:e.user)!=null&&O.id)||!!((j=e==null?void 0:e.user)!=null&&j.email)}))},[h,e]),f=g.useCallback((E,O)=>{h("bob_message_sent",{message_length:E,has_vehicle:O})},[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,O)=>{h("bob_parts_viewed",{part_count:E,vehicle_id:O})},[h]),m=g.useCallback(E=>{h("bob_product_clicked",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),k=g.useCallback(E=>{h("bob_product_viewed",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),w=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,O)=>{h("bob_checkout_started",{cart_value:E,item_count:O})},[h]),x=g.useCallback(E=>{const O=Math.ceil(E/5/150*60);h("bob_speech_played",{text_length:E,duration_estimate:O})},[h]),A=g.useCallback(E=>{h("bob_speech_failed",{text_length:E})},[h]),T=g.useCallback((E,O)=>{h("bob_error",{error_type:E,error_message:O})},[h]),R=g.useCallback(E=>{if(!s||!n||!i)return;const O=(E==null?void 0:E.led_to_cart)||(E==null?void 0:E.had_product_match),j=()=>{var L,P,F,B,N,H;u.current=!1;const C={session_id:a.current,user_id:((L=e==null?void 0:e.user)==null?void 0:L.id)||null,channel:"web",vehicle_id:(E==null?void 0:E.vehicle_id)||((B=(F=(P=e==null?void 0:e.vehicle)==null?void 0:P.selectedVehicle)==null?void 0:F.vehicle_id)==null?void 0:B.toString())||null,rego:(E==null?void 0:E.rego)||((H=(N=e==null?void 0:e.vehicle)==null?void 0:N.selectedVehicle)==null?void 0:H.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(C)}).catch(Z=>{console.warn("[BobAnalytics] Conversation track failed:",Z)})};if(O){c.current&&(clearTimeout(c.current),c.current=null),j();return}u.current||(u.current=!0,c.current=setTimeout(j,od))},[s,n,i,e]);return g.useEffect(()=>{p()},[p]),g.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]),{trackEvent:h,sessionId:a.current,trackSessionStart:p,trackMessageSent:f,trackVehicleIdentified:y,trackPartsViewed:b,trackProductClicked:m,trackProductViewed:k,trackAddToCart:w,trackCheckoutStarted:S,trackSpeechPlayed:x,trackSpeechFailed:A,trackError:T,trackConversationActivity:R}}const on=g.createContext(null);function si({children:t,bobConfig:e,hostApiConfig:r,hostContext:s={},callbacks:n={},queryClient:i,ga4Config:a,analyticsEnabled:o=!0,bottomOffset:c=0,zIndexBase:u=50}){const d=g.useMemo(()=>new Gu({defaultOptions:{queries:{retry:1,staleTime:3e5}}}),[]),h=i||d,p=!!i;g.useEffect(()=>{console.log(`[BobWidget] v${Vt} initialized`),console.log(`[BobWidget] QueryClient: ${p?"external (shared)":"internal"}`),console.log(`[BobWidget] Analytics: ${o?"enabled":"disabled"}`),a!=null&&a.measurementId&&console.log(`[BobWidget] GA4: ${a.measurementId}`)},[p,o,a==null?void 0:a.measurementId]);const f=g.useMemo(()=>Fn(e.supabaseUrl,e.supabaseKey),[e.supabaseUrl,e.supabaseKey]),[y,b]=g.useState(s);g.useEffect(()=>{b(s)},[s]);const m=g.useCallback(w=>{b(S=>({...S,...w}))},[]),k=g.useMemo(()=>({bobSupabase:f,bobConfig:e,hostApiConfig:r,hostContext:y,callbacks:n,updateHostContext:m,ga4Config:a,analyticsEnabled:o,bottomOffset:c,zIndexBase:u}),[f,e,r,y,n,m,a,o,c,u]);return l.jsx(Ju,{client:h,children:l.jsx(on.Provider,{value:k,children:t})})}function Jt(){const t=g.useContext(on);if(!t)throw new Error("useBobContext must be used within a BobProvider");return t}function cd(){const{bobSupabase:t}=Jt();return t}function Ar(){const t=g.useContext(on);return(t==null?void 0:t.bobSupabase)||null}function ud(){const{hostContext:t}=Jt();return t}function dd(){const{hostApiConfig:t}=Jt();return t}function hd(){const{callbacks:t}=Jt();return t}function fd(){const{ga4Config:t,analyticsEnabled:e}=Jt();return{ga4Config:t,enabled:e}}function ni(){const t=g.useContext(on);return t?{bottomOffset:t.bottomOffset,zIndexBase:t.zIndexBase}:{bottomOffset:0,zIndexBase:50}}let Vs=null;const Gi=typeof window<"u"?window.AudioContext||window.webkitAudioContext:null,qa=()=>(!Vs&&Gi&&(Vs=new Gi,console.log("[BobWidget] AudioContext created, initial state:",Vs.state)),Vs),za=async()=>{const t=qa();if(!t)return!1;if(t.state==="running")return!0;try{return await t.resume(),console.log("[BobWidget] AudioContext resumed →",t.state),t.state==="running"}catch(r){return console.warn("[BobWidget] AudioContext resume failed:",r),!1}},pd=async(t,e,r)=>{const s=qa();s.state!=="running"&&await s.resume();const n=await s.decodeAudioData(t),i=s.createBufferSource();i.buffer=n,i.connect(s.destination);let a=!1;return i.onended=()=>{a||(a=!0,r==null||r())},i.start(0),e==null||e(),{source:i,stop:()=>{try{i.stop()}catch{}}}};let Ji=!1;const Ha=t=>{if(!t||Ji)return()=>{};const e=async()=>{await za()&&(Ji=!0,t.removeEventListener("touchstart",e,!0),t.removeEventListener("pointerdown",e,!0),t.removeEventListener("click",e,!0))};return t.addEventListener("touchstart",e,{capture:!0,passive:!0}),t.addEventListener("pointerdown",e,{capture:!0}),t.addEventListener("click",e,{capture:!0}),()=>{t.removeEventListener("touchstart",e,!0),t.removeEventListener("pointerdown",e,!0),t.removeEventListener("click",e,!0)}},gd=15e3,bd=t=>t.replace(/\bya\b/gi,"you"),Ka=({onStart:t,onEnd:e,onFailed:r}={})=>{const{bobConfig:s,bobSupabase:n}=Jt(),[i,a]=g.useState(!1),o=g.useRef(null),c=g.useRef(null),u=g.useRef(!1),d=g.useRef([]),h=g.useRef(!1),p=g.useRef(!1),f=g.useRef(null),y=g.useRef(null),b=g.useRef(t),m=g.useRef(e),k=g.useRef(r);g.useEffect(()=>{b.current=t,m.current=e,k.current=r},[t,e,r]);const w=g.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),S=g.useCallback(()=>{var j;u.current||(u.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(j=b.current)==null||j.call(b))},[]),x=g.useCallback(async()=>{var P,F;if(h.current||d.current.length===0)return;h.current=!0;const j=d.current.shift();if(!j){h.current=!1;return}const{text:C,isGreeting:L}=j;L&&(p.current=!0),u.current=!1,w(),o.current&&(o.current.stop(),o.current=null),c.current=setTimeout(()=>{var B,N;console.warn("[BobWidget TTS] Timeout - triggering fallback callbacks"),S(),a(!1),p.current=!1,(B=m.current)==null||B.call(m),(N=k.current)==null||N.call(k),o.current=null,h.current=!1,x()},gd);try{console.log("[BobWidget TTS] Using ElevenLabs TTS");const B=bd(C),N=await fetch(`${s.supabaseUrl}/functions/v1/bob-tts-elevenlabs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.supabaseKey}`},body:JSON.stringify({text:B})});if(!N.ok){const W=await N.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",W),new Error("TTS request failed")}const H=await N.arrayBuffer();await za();const Z=await pd(H,()=>{var W;w(),f.current=null,u.current||(u.current=!0,a(!0),console.log("[BobWidget TTS] Audio playing via AudioContext, triggering onStart"),(W=b.current)==null||W.call(b))},()=>{var W;w(),a(!1),p.current=!1,console.log("[BobWidget TTS] Audio ended, triggering onEnd"),(W=m.current)==null||W.call(m),o.current=null,h.current=!1,x()});o.current=Z}catch(B){w(),L&&(f.current=C,console.log("[BobWidget TTS] Greeting stored for retry on user interaction")),console.error("[BobWidget TTS] Speech synthesis error:",B),S(),a(!1),p.current=!1,(P=m.current)==null||P.call(m),(F=k.current)==null||F.call(k),h.current=!1,x()}},[s.supabaseUrl,s.supabaseKey,w,S]),A=g.useCallback((j,C=!1)=>{if(j.trim()){if(C){if(y.current===j){console.log(`[BobWidget TTS] Ignoring duplicate greeting: "${j.substring(0,30)}..."`);return}y.current=j,f.current=null}if(p.current&&!C){console.log("[BobWidget TTS] Greeting playing - queueing message"),d.current.push({text:j,isGreeting:C});return}C?d.current.unshift({text:j,isGreeting:C}):d.current.push({text:j,isGreeting:C}),x()}},[x]),T=g.useCallback(()=>{if(f.current&&!o.current&&!h.current){console.log("[BobWidget TTS] Retrying pending greeting on user interaction");const j=f.current;f.current=null,A(j,!0)}},[A]),R=g.useCallback((j=!1)=>{var C;w(),d.current=[],o.current&&(o.current.stop(),o.current=null),a(!1),p.current=!1,h.current=!1,j||(C=m.current)==null||C.call(m)},[w]),E=g.useCallback(()=>{o.current&&o.current.stop()},[]),O=g.useCallback(()=>{},[]);return g.useEffect(()=>()=>{w(),d.current=[],o.current&&(o.current.stop(),o.current=null)},[w]),{speak:A,stop:R,pause:E,resume:O,isSpeaking:i,isSupported:!0,retryPendingGreeting:T}},Qi="bob_last_visit",md=30;function Va(t=md){const[e,r]=g.useState(!1),[s,n]=g.useState(null);return g.useEffect(()=>{try{const i=localStorage.getItem(Qi),a=Date.now();if(i){const o=parseInt(i,10),c=(a-o)/(1e3*60*60*24);c<=t?(r(!0),n(new Date(o)),console.log(`[BobWidget] Returning user detected - last visit ${Math.round(c)} days ago`)):console.log(`[BobWidget] Previous visit was ${Math.round(c)} days ago - treating as new user`)}else console.log("[BobWidget] First time visitor detected");localStorage.setItem(Qi,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 Yn=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},yd=t=>{let e=Yn(t);return e=e.replace(/[\[\]{}]/g,""),e=e.replace(/https?:\/\/[^\s]+/g,""),e=e.replace(/\bSKU\s*:?\s*\w+/gi,""),e},vd=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],Yi=["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"],Ga=({setAnimationState:t,manualMode:e=!1,talkingState:r="talking",thinkingState:s="researching",completeState:n="idle",idleState:i="idle",listenState:a="listening",onStreamStart:o,onStreamComplete:c,onShowingProduct:u,onResearchStart:d,onPartsResearchStart:h,onReadyToSpeak:p,onHighlightPart:f,onHighlightProduct:y,onNoPartsFound:b,onAutoFetchComplete:m,onVariantSelectionRequired:k,shelfCategoriesRef:w,initialVehicle:S})=>{var Ns,Fs,Bs,Ls;const{bobConfig:x,hostApiConfig:A,hostContext:T,callbacks:R,ga4Config:E,analyticsEnabled:O}=Jt(),j=Wa({ga4Config:E,hostContext:T,callbacks:R,enabled:O}),{isReturningUser:C}=Va(),[L,P]=g.useState([]),[F,B]=g.useState(""),[N,H]=g.useState(!1),[Z,W]=g.useState(!1),[z,fe]=g.useState(null),re=g.useRef(null),se=g.useRef(!1),Ee=g.useRef(!1),te=g.useRef(""),ge=g.useRef(!1),je=g.useRef(null);g.useRef(null);const U="carfix_bob_session",$e=4*60*60*1e3,Ve=g.useRef(!1),tt=(K,de)=>{try{const ae={messages:K??L,vehicleCandidates:_e.current,conversationState:De.current,identifiedVehicle:de!==void 0?de:z,savedAt:Date.now()};sessionStorage.setItem(U,JSON.stringify(ae))}catch(ae){console.warn("[BobWidget] Failed to save session:",ae)}},_e=g.useRef([]),De=g.useRef("AWAITING_REGO");g.useEffect(()=>{var K;if(!Ve.current){if(Ve.current=!0,S){console.log("[BobWidget] Applying initialVehicle:",S.make,S.model),_e.current=[S],De.current="VEHICLE_CONFIRMED",fe(S);return}try{const de=sessionStorage.getItem(U);if(de){const ae=JSON.parse(de);Date.now()-(ae.savedAt??0)<$e?((K=ae.messages)!=null&&K.length&&P(ae.messages),ae.identifiedVehicle&&fe(ae.identifiedVehicle),ae.vehicleCandidates&&(_e.current=ae.vehicleCandidates),ae.conversationState&&(De.current=ae.conversationState),console.log("[BobWidget] Session restored from sessionStorage")):(sessionStorage.removeItem(U),console.log("[BobWidget] Session expired (4h TTL) — starting fresh"))}}catch(de){console.warn("[BobWidget] Failed to restore session:",de)}}},[]),g.useEffect(()=>{L.length>0&&tt(L)},[L]);const ct=()=>{gt()},rt=()=>{je.current&&(clearTimeout(je.current),je.current=null)},{speak:Be,stop:gt,isSpeaking:ur,retryPendingGreeting:st}=Ka({onStart:()=>{rt(),ge.current=!0,console.log("[BobWidget STATE] Speech STARTED - transitioning to TALK state"),j.trackSpeechPlayed(te.current.length),p==null||p(),e||(console.log("[BobWidget STATE] Setting state to:",r),qe(r))},onEnd:()=>{rt(),console.log("[BobWidget STATE] Speech ENDED - transitioning out of TALK state");const K=Yi.some(de=>te.current.toLowerCase().includes(de.toLowerCase()));e||(K&&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),qe(n),setTimeout(()=>{console.log("[BobWidget STATE] Post-complete transition to:",a),qe(a)},2e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered"),j.trackSpeechFailed(te.current.length)}});g.useEffect(()=>{var K;(K=R.onStopSpeechReady)==null||K.call(R,ct)},[]),g.useEffect(()=>{var K;(K=re.current)==null||K.scrollIntoView({behavior:"smooth"})},[L]),g.useEffect(()=>{var de,ae;const K=(de=T.vehicle)==null?void 0:de.selectedVehicle;K&&!z&&(console.log("[BobWidget] Setting vehicle from host context:",K),fe(K),(ae=R.onVehicleIdentified)==null||ae.call(R,K),j.trackVehicleIdentified({make:K.make,model:K.model,year:K.year,rego:K.rego}))},[(Ns=T.vehicle)==null?void 0:Ns.selectedVehicle]),g.useEffect(()=>{var K;if(L.length===0&&!Ee.current){Ee.current=!0;const de=(K=T.vehicle)==null?void 0:K.selectedVehicle;let ae;C?(ae="Ah hey... you again! What you after this time?",console.log("[BobWidget] Using returning user greeting")):de?ae=`G'day! Saw you've got the ${`${de.year} ${de.make} ${de.model}`} - choice wagon! What can I help you find for it today?`:ae="Hey Bro, welcome to CARFIX - what can I get ya?",P([{role:"assistant",content:ae}]),Z||setTimeout(()=>{console.log("[BobWidget] Speaking initial greeting (priority)"),Be(ae,!0)},500)}},[(Fs=T.vehicle)==null?void 0:Fs.selectedVehicle,L.length,Z,Be]),g.useEffect(()=>{const K=()=>{console.log("[BobWidget] User interaction detected - retrying pending greeting"),st(),document.removeEventListener("click",K),document.removeEventListener("touchstart",K)};return document.addEventListener("click",K,{once:!0}),document.addEventListener("touchstart",K,{once:!0}),()=>{document.removeEventListener("click",K),document.removeEventListener("touchstart",K)}},[st]),g.useEffect(()=>{var bt,_t;const K=(bt=T.vehicle)==null?void 0:bt.selectedVehicle;if(!K||se.current)return;const de=K.vehicle_id??K.id,ae=Number.parseInt(String(de),10);if(!Number.isFinite(ae)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",K);return}se.current=!0;const Le={...K,vehicle_id:String(ae)},Ye=(_t=T.user)==null?void 0:_t.email;(async()=>{var At,Ut;const ut=`${x.supabaseUrl}/functions/v1/bob-chat`;try{const Me=await fetch(ut,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:Le,customerEmail:Ye,autoFetchParts:!0,hostConfig:A,hostContext:T})});if(!Me.ok||!Me.body){console.error("[BobWidget] Auto-fetch failed:",Me.status);return}const Mt=Me.body.getReader(),Qt=new TextDecoder;let nt="";for(;;){const{done:Xe,value:Ot}=await Mt.read();if(Xe)break;nt+=Qt.decode(Ot,{stream:!0});let Ze;for(;(Ze=nt.indexOf(`
|
|
74
|
+
`))!==-1;){let mt=nt.slice(0,Ze);if(nt=nt.slice(Ze+1),mt.endsWith("\r")&&(mt=mt.slice(0,-1)),mt.startsWith(":")||mt.trim()===""||!mt.startsWith("data: "))continue;const dr=mt.slice(6).trim();if(dr==="[DONE]")break;try{const Ge=JSON.parse(dr);Ge.type==="service_packages_found"&&Ge.packages&&(console.log("[useBobChat autoFetch] Received service_packages_found:",Ge.packages.length,"packages"),(At=R.onServicePackagesFound)==null||At.call(R,Ge.packages),w!=null&&w.current&&Ge.packages.forEach(v=>{v.title&&w.current.set(v.title,"package")})),Ge.type==="parts_found"&&Ge.parts&&(console.log("[useBobChat autoFetch] Received parts_found:",Ge.parts.length,"parts"),(Ut=R.onPartsFound)==null||Ut.call(R,Ge.parts),j.trackPartsViewed(Array.isArray(Ge.parts)?Ge.parts.length:0,String(ae)))}catch{}}}m==null||m()}catch(Me){console.error("[BobWidget] Auto-fetch error:",Me)}})()},[(Bs=T.vehicle)==null?void 0:Bs.selectedVehicle,(Ls=T.user)==null?void 0:Ls.email]);const qe=K=>{try{t(K)}catch{console.warn(`[BobWidget] State "${K}" not available`)}},V=async K=>{var Ye,Ct,bt,_t,ut,At,Ut,Me,Mt,Qt,nt,Xe,Ot,Ze,mt,dr,Ge,v;const de=`${x.supabaseUrl}/functions/v1/bob-chat`,ae=(Ye=T.user)==null?void 0:Ye.email;let Le=!1;try{const I={messages:[...L,K],hostConfig:A,hostContext:T};w!=null&&w.current&&w.current.size>0&&(I.shelfContext=Array.from(w.current).join(", ")),z&&(I.vehicleContext=z),ae&&(I.customerEmail=ae),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current:",JSON.stringify((Ct=_e.current)==null?void 0:Ct.slice(0,2))),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current.length:",(bt=_e.current)==null?void 0:bt.length),console.log("[useBobChat DEBUG] conversationStateRef.current:",De.current),_e.current&&_e.current.length>0?(I.vehicleCandidates=_e.current,console.log("[useBobChat] ✅ Including",_e.current.length,"vehicle candidates in request")):console.log("[useBobChat] ⚠️ No vehicle candidates to include - ref is empty");const $=await fetch(de,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x.supabaseKey}`},body:JSON.stringify(I)});if(!$.ok){if($.status===429){(_t=R.onError)==null||_t.call(R,new Error("Rate limit exceeded"));return}if($.status===402){(ut=R.onError)==null||ut.call(R,new Error("Payment required"));return}throw new Error("Failed to start stream")}if(!$.body)throw new Error("No response body");const ee=$.body.getReader(),he=new TextDecoder;let ce="",oe=!1,ne="";for(;!oe;){const{done:Re,value:yt}=await ee.read();if(Re)break;ce+=he.decode(yt,{stream:!0});let dt;for(;(dt=ce.indexOf(`
|
|
75
|
+
`))!==-1;){let ve=ce.slice(0,dt);if(ce=ce.slice(dt+1),ve.endsWith("\r")&&(ve=ve.slice(0,-1)),ve.startsWith(":")||ve.trim()===""||!ve.startsWith("data: "))continue;const kt=ve.slice(6).trim();if(kt==="[DONE]"){oe=!0;break}try{const D=JSON.parse(kt);if(D.type==="conversation_state"){console.log("[useBobChat] 🔄 conversation_state event received:",D.state),De.current=D.state,D.candidates&&Array.isArray(D.candidates)?(_e.current=D.candidates,console.log("[useBobChat] ✅ Stored",D.candidates.length,"vehicle candidates from state event"),console.log("[useBobChat] First candidate:",JSON.stringify(D.candidates[0]))):console.log("[useBobChat] ⚠️ conversation_state had no candidates array"),tt();continue}if(D.type==="variant_selection_required"){const pe=Array.isArray(D.candidates)?D.candidates.length:0;console.log("[useBobChat] 🎴 variant_selection_required event received:",pe,"cards"),Array.isArray(D.candidates)?k==null||k(D.candidates,typeof D.make=="string"?D.make:"",typeof D.model=="string"?D.model:""):console.warn("[useBobChat] ⚠️ variant_selection_required had no candidates array");continue}if(D.type==="vehicle_identified"&&D.vehicle){fe(D.vehicle),_e.current=[],De.current="VEHICLE_CONFIRMED",tt(void 0,D.vehicle),(At=R.onVehicleIdentified)==null||At.call(R,D.vehicle),h==null||h(),j.trackVehicleIdentified({make:D.vehicle.make,model:D.vehicle.model,year:D.vehicle.year,rego:D.vehicle.rego});continue}if(D.type==="researching_parts"){console.log("[useBobChat] 🔍 researching_parts event — showing shelf spinner"),h==null||h();continue}if(D.type==="vehicle_candidates_found"&&D.candidates){console.log("[useBobChat] 📦 vehicle_candidates_found event received:",D.candidates.length,"candidates"),_e.current=D.candidates,console.log("[useBobChat] ✅ Candidates stored in ref. First:",JSON.stringify(D.candidates[0])),tt();continue}if(D.type==="service_packages_found"&&D.packages){(Ut=R.onServicePackagesFound)==null||Ut.call(R,D.packages),w!=null&&w.current&&(D.packages.forEach(pe=>{pe.title&&w.current.set(pe.title,"package")}),console.log("[useBobChat] Eagerly added service package titles to shelfCategories:",Array.from(w.current.entries())));continue}if(D.type==="parts_found"&&D.parts){console.log("[useBobChat] Received parts_found event:",D.parts.length,"parts"),(Me=R.onPartsFound)==null||Me.call(R,D.parts),w!=null&&w.current&&Array.isArray(D.parts)&&D.parts.forEach(pe=>{const Se=pe.partslot_description||"Other Parts";Se&&w.current.set(Se,"partslot")}),j.trackPartsViewed(Array.isArray(D.parts)?D.parts.length:0,(Mt=z==null?void 0:z.vehicle_id)==null?void 0:Mt.toString());continue}if(D.type==="bob_suggestions"&&D.products){console.log("[useBobChat] Received bob_suggestions:",D.products.length,"products",D.title),P(pe=>{var St;const Se=[...pe],Pe=Se[Se.length-1];return console.log("[useBobChat] Attaching to message:",Pe==null?void 0:Pe.role,(St=Pe==null?void 0:Pe.content)==null?void 0:St.slice(0,40)),(Pe==null?void 0:Pe.role)==="assistant"?Se.map((we,hr)=>hr===Se.length-1?{...we,suggestedProducts:D.products,suggestionsTitle:D.title}:we):Se}),console.log("[useBobChat] bob_suggestions processed for inline display only");continue}if(D.type==="no_parts_found"){(Qt=R.onPartsFound)==null||Qt.call(R,[]),(nt=R.onServicePackagesFound)==null||nt.call(R,[]),b==null||b();continue}if(D.type==="highlight_category"&&D.category){console.log("[useBobChat] highlight_category event:",D.category),Le=!0,f==null||f(D.category);continue}if(D.type==="navigate_url"&&D.url){console.log("[useBobChat] navigate_url event:",D.url),gt(),(Xe=R.onNavigateToProductPage)==null||Xe.call(R,{sku:D.sku,url:D.url});continue}if(D.type==="quick_replies"&&Array.isArray(D.replies)){console.log("[useBobChat] quick_replies event:",D.replies.length,"buttons"),P(pe=>{var St;const Se=[...pe],Pe=Se.length-1;return((St=Se[Pe])==null?void 0:St.role)==="assistant"?Se.map((we,hr)=>hr===Pe?{...we,quickReplies:D.replies}:we):Se});continue}if(D.type==="cart_updated"&&D.items){if((Ot=R.onCartUpdated)==null||Ot.call(R,D.items),R.onAddToCart)for(const pe of D.items)R.onAddToCart({product_id:pe.product_id||pe.productName||"",product_name:pe.product_name||pe.productName||"",quantity:pe.quantity||1,unit_price:pe.unit_price||0,vehicle_id:pe.vehicle_id,sku:pe.sku,brand:pe.brand});continue}const Yt=(dr=(mt=(Ze=D.choices)==null?void 0:Ze[0])==null?void 0:mt.delta)==null?void 0:dr.content;if(Yt){ne+=Yt;let pe=ne.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");pe=Yn(pe),P(Se=>{const Pe=Se[Se.length-1];return(Pe==null?void 0:Pe.role)==="assistant"?Se.map((St,we)=>we===Se.length-1?{...St,content:pe}:St):[...Se,{role:"assistant",content:pe}]}),(Ge=R.onBobMessage)==null||Ge.call(R,pe)}}catch{ce=ve+`
|
|
76
|
+
`+ce;break}}}let Ne=ne.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");Ne=Yn(Ne),te.current=Ne;const Te=Yi.some(Re=>ne.toLowerCase().includes(Re.toLowerCase()));if(console.log("[useBobChat] v3.3.0 scroll debug: highlightCategoryReceived=",Le,"shelfCategories=",w!=null&&w.current?Array.from(w.current.entries()):"none"),!Le&&(w!=null&&w.current)&&w.current.size>0){const Re=Ne.toLowerCase(),yt=["service pack","package","bundle","service","complete","kit"],dt=["individual","just the","single","grab a"],ve=yt.some(we=>Re.includes(we)),kt=dt.some(we=>Re.includes(we)),D=[],Yt=[];for(const[we,hr]of w.current)hr==="package"?D.push(we):Yt.push(we);let pe;ve&&!kt?pe=D.map(we=>({name:we,type:"package"})):kt&&!ve?pe=Yt.map(we=>({name:we,type:"partslot"})):pe=[...D.map(we=>({name:we,type:"package"})),...Yt.map(we=>({name:we,type:"partslot"}))];let Se=null,Pe=0,St=0;for(const{name:we,type:hr}of pe){const li=we.toLowerCase().split(/\s+/).filter(Boolean),ss=li.filter(Ro=>Re.includes(Ro)).length;if(ss<li.length)continue;const To=hr==="package"&&!kt&&ss>=2?.5:0,hn=ss+To;(hn>Pe||hn===Pe&&ss>St)&&(Pe=hn,Se=we,St=ss)}if(Se){const we=w.current.get(Se);console.log(`[useBobChat] v3.3.0 shelf match: "${Se}" (type=${we}, score=${Pe}, packageIntent=${ve}, partIntent=${kt})`),f==null||f(Se)}}const Ce=ne.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(Ce){const[,Re,yt]=Ce;y==null||y({brand:Re,price:parseFloat(yt)})}if(!Z&&te.current.trim()){ge.current=!1,rt();const Re=yd(te.current);console.log("[BobWidget] Playing TTS"),Be(Re),je.current=setTimeout(()=>{ge.current||(console.warn("[BobWidget] Speech fallback after 5s"),p==null||p(),e||(Te&&u?u():c?c():(qe(n),setTimeout(()=>qe(a),3e3))))},5e3)}else p==null||p(),e||(Te&&u?u():c?c():(qe(n),setTimeout(()=>qe(a),3e3)))}catch(I){console.error("[BobWidget] Chat error:",I);const $=I instanceof Error?I:new Error("Unknown error");(v=R.onError)==null||v.call(R,$),j.trackError($.name||"ChatError",$.message||"Unknown chat error"),e||qe(i)}},ie=async()=>{if(!F.trim()||N)return;st(),gt();const K={role:"user",content:F};P(Le=>[...Le,K]),B(""),j.trackMessageSent(F.length,!!z);const de=F.toLowerCase();if(vd.some(Le=>de.includes(Le))){const Le=`G'day mate! I'm running Bob v${Vt} - she's running sweet as! Anything else I can help ya with?`;P(Ye=>[...Ye,{role:"assistant",content:Le}]),Z||Be(Le);return}H(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",s),d==null||d(),z&&(h==null||h()),e||qe(s),await V(K),H(!1)},ke=()=>{W(K=>!K),Z||gt()},Q=K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),ie())},me=()=>{st()},ye=()=>{},Qe=()=>{sessionStorage.removeItem(U),_e.current=[],De.current="AWAITING_REGO",P([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},Ue=()=>{fe(null)},Dt=K=>{if(!K.trim())return;console.log("[BobWidget] sendDirectMessage:",K),gt(),H(!1),B("");const de={role:"user",content:K};P(ae=>[...ae,de]),d==null||d(),z&&(h==null||h()),e||qe(s),H(!0),V(de).finally(()=>H(!1))},Ie=g.useRef(!1);return{messages:L,input:F,setInput:B,isLoading:N,handleSend:ie,handleKeyPress:Q,handleInputFocus:me,handleInputBlur:ye,chatEndRef:re,clearMessages:Qe,isMuted:Z,toggleMute:ke,isSpeaking:ur,identifiedVehicle:z,clearVehicle:Ue,sendDirectMessage:Dt,stopAllAudio:ct,refetchPartsForVehicle:async()=>{var Ct,bt,_t;if(!z||Ie.current)return;Ie.current=!0;const K=z.vehicle_id??z.id,de=Number.parseInt(String(K),10);if(!Number.isFinite(de)){console.warn("[BobWidget] refetchPartsForVehicle: invalid vehicle_id");return}console.log("[BobWidget] refetchPartsForVehicle: re-fetching for vehicle",de),h==null||h();const ae=`${x.supabaseUrl}/functions/v1/bob-chat`,Le={...z,vehicle_id:String(de)},Ye=(Ct=T.user)==null?void 0:Ct.email;try{const ut=await fetch(ae,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:Le,customerEmail:Ye,autoFetchParts:!0,hostConfig:A,hostContext:T})});if(!ut.ok||!ut.body){console.error("[BobWidget] refetchPartsForVehicle failed:",ut.status),m==null||m();return}const At=ut.body.getReader(),Ut=new TextDecoder;let Me="";for(;;){const{done:Mt,value:Qt}=await At.read();if(Mt)break;Me+=Ut.decode(Qt,{stream:!0});let nt;for(;(nt=Me.indexOf(`
|
|
77
|
+
`))!==-1;){let Xe=Me.slice(0,nt);if(Me=Me.slice(nt+1),Xe.endsWith("\r")&&(Xe=Xe.slice(0,-1)),Xe.startsWith(":")||Xe.trim()===""||!Xe.startsWith("data: "))continue;const Ot=Xe.slice(6).trim();if(Ot==="[DONE]")break;try{const Ze=JSON.parse(Ot);Ze.type==="service_packages_found"&&Ze.packages&&((bt=R.onServicePackagesFound)==null||bt.call(R,Ze.packages)),Ze.type==="parts_found"&&Ze.parts&&((_t=R.onPartsFound)==null||_t.call(R,Ze.parts))}catch{}}}m==null||m()}catch(ut){console.error("[BobWidget] refetchPartsForVehicle error:",ut),m==null||m()}}}},wd={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},Ja=t=>{const e=Ua(),r=Ar();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]),Ps({queryKey:["bob-animation-data",t],queryFn:async()=>{var S;if(!r)return console.log("[BobAnimation] No supabase client, returning empty data"),wd;const{data:s,error:n}=await r.from("bob_looks").select("*").order("display_order");if(n)throw n;const i=(s||[]).find(x=>x.is_active),a=t||(i==null?void 0:i.id)||s&&((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:o,error:c}=await r.from("animation_states").select("*").eq("is_active",!0).eq("look_id",a).order("display_order");if(c)throw c;const{data:u,error:d}=await r.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",a).order("animation_state").order("sequence_order");if(d)throw d;const h=(o||[]).map(x=>x.state_key);console.log(`[BobAnimation] Loaded ${h.length} states: ${h.join(", ")}`);const f=["idle","talking","listening"].filter(x=>{const A=[x,x.replace("ing",""),x+"ing"];return!h.some(T=>A.includes(T))});f.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${f.join(", ")}`);const y=new Set(h),b=(u||[]).filter(x=>y.has(x.animation_state));console.log(`[BobAnimation] Loaded ${b.length} animation frames`);const{data:m,error:k}=await r.storage.from("bob-images").list();if(k)throw k;const w=(m||[]).map(x=>{const{data:A}=r.storage.from("bob-images").getPublicUrl(x.name);return A.publicUrl});return b.forEach(x=>{const A=new Image;A.src=x.image_url}),{states:o||[],configs:b,uploadedImages:w,looks:s||[],activeLookId:a}},staleTime:30*1e3,gcTime:5*60*1e3})},Qa=(t={})=>{const{isSpeaking:e=!1}=t,[r,s]=g.useState(""),[n,i]=g.useState(0),[a,o]=g.useState(400),[c,u]=g.useState(!1),d=g.useRef(null),h=g.useRef(0),p=g.useRef(e),f=g.useRef(0),y=g.useRef(0),b=g.useRef(!1),m=g.useRef(0),{data:k,isLoading:w}=Ja(),S=g.useRef({}),{imageUrlsMap:x,alternateImages:A,offsetsMap:T,scalesMap:R,availableStates:E}=g.useMemo(()=>{if(!k)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const P={},F={},B={},N={},H=k.states.map(Z=>Z.state_key);return H.forEach(Z=>{const W=k.configs.filter(se=>se.animation_state===Z),z=W.map(se=>se.image_url),fe=W.map(se=>se.vertical_offset||0),re=W.map(se=>se.scale||100);if(z.length>0){const se=k.states.find(Ee=>Ee.state_key===Z);P[Z]={url:z[0],animation_speed:(se==null?void 0:se.animation_speed)||400,pause_duration:(se==null?void 0:se.pause_duration)||0,loop_count:(se==null?void 0:se.loop_count)||0},F[Z]=z,B[Z]=fe,N[Z]=re}}),{imageUrlsMap:P,alternateImages:F,offsetsMap:B,scalesMap:N,availableStates:H}},[k]);g.useEffect(()=>{S.current=x},[x]),g.useEffect(()=>{const P=p.current;if(p.current=e,P&&!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 O=g.useCallback(P=>{s(F=>F===P?F:(f.current=0,y.current=0,b.current=!1,i(0),P))},[]);g.useEffect(()=>{E.length>0&&!r&&s(E[0])},[E,r]),g.useEffect(()=>{const P=A[r];if(d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),f.current=0,y.current=0,b.current=!1,h.current=0,i(0),!P||P.length<=1)return;const F=S.current[r],B=(F==null?void 0:F.animation_speed)||a||400,N=(F==null?void 0:F.loop_count)||0,H=(F==null?void 0:F.pause_duration)||0,Z=r.toLowerCase().includes("talk"),W=z=>{if(h.current===0&&(h.current=z),b.current){z-m.current>=H&&(b.current=!1,y.current=0,h.current=z),d.current=requestAnimationFrame(W);return}if(z-h.current>=B){h.current=z;const re=(f.current+1)%P.length;re===0?(y.current++,Z&&p.current?(f.current=re,i(re)):N>0&&y.current>=N?H>0&&(b.current=!0,m.current=z):(f.current=re,i(re))):(f.current=re,i(re))}d.current=requestAnimationFrame(W)};return d.current=requestAnimationFrame(W),()=>{d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)}},[r,A,a]);const j=g.useCallback(()=>{const P=A[r];if(!P||P.length===0){const F=E.find(B=>{var N;return((N=A[B])==null?void 0:N.length)>0});return F?(console.warn(`[useBobAnimation] No images for "${r}", using fallback: ${F}`),A[F][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return P[n]||P[0]},[A,r,E,n]),C=g.useCallback(()=>{const P=T[r];if(!P||P.length===0){const F=E.find(B=>{var N;return((N=T[B])==null?void 0:N.length)>0});return F?T[F][0]:0}return P[n]||P[0]},[T,r,E,n]),L=g.useCallback(()=>{const P=R[r];if(!P||P.length===0){const F=E.find(B=>{var N;return((N=R[B])==null?void 0:N.length)>0});return F?R[F][0]:100}return P[n]||P[0]},[R,r,E,n]);return{animationState:r,setAnimationState:O,getCurrentImage:j,getCurrentOffset:C,getCurrentScale:L,imageUrls:x,availableStates:E,setTalkSpeed:o,manualMode:c,setManualMode:u,isLoading:w}},Ya=()=>{const t=Ar(),{data:e=[],isLoading:r}=Ps({queryKey:["bob-backdrops"],queryFn:async()=>{if(!t)return console.log("[useBobBackdrop] No supabase client, returning empty"),[];const{data:n,error:i}=await t.from("bob_backdrops").select("*").order("display_order",{ascending:!0});if(i)throw i;return n},staleTime:5*60*1e3,gcTime:10*60*1e3}),s=e.find(n=>n.is_active);return{backdrops:e,activeBackdrop:s,isLoading:r}},Xa=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=12,className:i="",verticalOffset:a=0,scale:o=100})=>{const c=a+n,u=55*(o/100);return l.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${i}`,children:l.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[r&&l.jsx("img",{src:r,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),l.jsx("img",{src:t,alt:`Bob ${e}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${c}%`,width:`${u}%`,maxWidth:`${220*(o/100)}px`,transformOrigin:"center bottom"}}),s&&l.jsx("img",{src:s,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${n}%`}})]})})},G={primary:"#0052CC",primaryHover:"#0047B3",secondary:"#38BDF8",foreground:"#0F172A",accent:"#FF8C00",success:"#22C55E",destructive:"#EF4444",performanceRed:"#DC2626",mutedForeground:"#64748B",background:"#FAFAFA",card:"#FFFFFF",border:"#E2E8F0",slateEconomy:"#475569"},tn={Economy:{icon:"DollarSign",emoji:"💰",textColor:"#475569",background:"#F1F5F9",border:"#CBD5E1",description:"Smart savings"},Standard:{icon:"Star",emoji:"⭐",textColor:"#0052CC",background:"rgba(0,82,204,0.1)",border:"rgba(0,82,204,0.3)",description:"Best value",isRecommended:!0},Premium:{icon:"Award",emoji:"🏆",textColor:"#D97706",background:"#FEF3C7",border:"#FCD34D",description:"Superior quality"},Performance:{icon:"Zap",emoji:"⚡",textColor:"#DC2626",background:"#FEE2E2",border:"#FCA5A5",description:"Maximum power"}},vn={"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."},xd="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.",Cr={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`},Za={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"}},Tt={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 eo(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 to(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function lt(t){return`$${t.toFixed(2)}`}function ro(t){if(vn[t])return vn[t];const e=t.toLowerCase();for(const[r,s]of Object.entries(vn))if(e.includes(r.toLowerCase())||r.toLowerCase().includes(e))return s;return xd}const ds=({type:t,value:e,className:r=""})=>{const s=Za[t],n=e||("label"in s?s.label:""),i=()=>{if(!("icon"in s))return null;const a={width:12,height:12};switch(s.icon){case"Check":return l.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})});case"Sparkles":return l.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("path",{d:"M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"}),l.jsx("path",{d:"M5 19l1 3 1-3 3-1-3-1-1-3-1 3-3 1 3 1z"})]});case"Gauge":return l.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("circle",{cx:"12",cy:"12",r:"10"}),l.jsx("path",{d:"M12 6v6l4 2"})]});case"Droplets":return l.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 11-11.31 0z"})});default:return null}};return l.jsxs("span",{className:r,style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:500,background:s.background,color:s.text,border:`1px solid ${s.border}`,whiteSpace:"nowrap"},children:[i(),n]})},ii=({products:t,title:e,onProductClick:r,onAddToCart:s})=>!t||t.length===0?null:l.jsxs("div",{style:{marginTop:"16px",width:"100%"},children:[e&&l.jsxs("div",{style:{marginBottom:"12px",fontSize:Tt.partslotName.fontSize,fontWeight:Tt.partslotName.fontWeight,color:G.foreground,display:"flex",alignItems:"center",gap:"8px"},children:[l.jsx("span",{style:{fontSize:"18px"},children:"🚗"}),e]}),l.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.slice(0,6).map((n,i)=>l.jsx(_d,{product:n,onProductClick:r,onAddToCart:s,isRecommended:i===0},n.id||n.sku||i))}),t.length>6&&l.jsxs("div",{style:{marginTop:"12px",fontSize:"13px",color:G.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),_d=({product:t,onProductClick:e,onAddToCart:r,isRecommended:s=!1})=>{const[n,i]=g.useState(!1),[a,o]=g.useState(!1),c=t.image_url||t.image||(t.sku?Cr.productImage(t.sku):null),u=t.brand?Cr.brandLogo(t.brand):null,d=t.brand||"Quality Part",h=t.name||"Product",p=t.price??0,f=t.partNumber||t.part_number,y=eo({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:b,unitPriceLabel:m}=to(p,y);return l.jsxs("div",{style:{background:G.card,borderRadius:"12px",border:`2px solid ${G.border}`,overflow:"hidden",cursor:e?"pointer":"default",transition:"all 0.2s ease"},onClick:()=>e==null?void 0:e(t),onMouseEnter:k=>{k.currentTarget.style.borderColor=`${G.primary}80`,k.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:k=>{k.currentTarget.style.borderColor=G.border,k.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&l.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${G.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[l.jsx("span",{style:{fontSize:Tt.partslotName.fontSize,fontWeight:Tt.partslotName.fontWeight,color:G.foreground},children:t.partslotDescription}),s&&l.jsx(ds,{type:"carfixValue"})]}),l.jsxs("div",{style:{padding:"16px",display:"flex",gap:"16px"},children:[l.jsx("div",{style:{width:"96px",minWidth:"96px",height:"96px",borderRadius:"8px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",border:`1px solid ${G.border}`},children:c&&!n?l.jsx("img",{src:c,alt:h,style:{width:"100%",height:"100%",objectFit:"contain",padding:"4px"},onError:()=>i(!0)}):l.jsx("span",{style:{fontSize:"32px",opacity:.5},children:"🔧"})}),l.jsxs("div",{style:{flex:1,minWidth:0},children:[l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[u&&!a&&l.jsx("img",{src:u,alt:d,style:{height:"16px",width:"auto",objectFit:"contain"},onError:()=>o(!0)}),l.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:G.foreground,textTransform:"uppercase"},children:d})]}),l.jsx("div",{style:{fontSize:Tt.productName.fontSize,fontWeight:Tt.productName.fontWeight,color:G.foreground,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",lineHeight:"1.4",marginBottom:"8px"},children:h}),l.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"12px"},children:[l.jsx(ds,{type:"fitsVehicle"}),y&&l.jsx(ds,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!y&&l.jsx(ds,{type:"quantity",value:`Qty: ${t.quantity}`}),f&&l.jsxs("span",{style:{fontSize:"12px",color:G.mutedForeground},children:["#",f]})]})]}),l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",justifyContent:"space-between",minWidth:"100px"},children:[l.jsxs("div",{style:{textAlign:"right"},children:[l.jsx("div",{style:{fontSize:Tt.priceMain.fontSize,fontWeight:Tt.priceMain.fontWeight,color:G.foreground},children:lt(b)}),m&&l.jsx("div",{style:{fontSize:Tt.priceSecondary.fontSize,color:G.mutedForeground},children:m}),l.jsx("div",{style:{fontSize:Tt.priceSecondary.fontSize,color:G.mutedForeground},children:"inc GST"})]}),r&&l.jsx("button",{onClick:k=>{k.stopPropagation(),r(t)},style:{background:G.primary,color:"#FFFFFF",border:"none",borderRadius:"8px",padding:"8px 16px",fontSize:"13px",fontWeight:600,cursor:"pointer",transition:"all 0.2s ease",whiteSpace:"nowrap"},onMouseEnter:k=>{k.currentTarget.style.background=G.primaryHover},onMouseLeave:k=>{k.currentTarget.style.background=G.primary},onMouseDown:k=>{k.currentTarget.style.transform="scale(0.98)"},onMouseUp:k=>{k.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},so=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:o,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,className:p="",onAddToCart:f,onProductClick:y})=>l.jsx("div",{className:p,style:{width:"100%",maxWidth:"72rem",margin:"0 auto",padding:"0 16px 32px 16px"},children:l.jsxs("div",{style:{backgroundColor:"rgba(20, 30, 50, 0.85)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.3)",overflow:"hidden"},children:[l.jsx("div",{style:{padding:"16px",borderBottom:"1px solid rgba(255,255,255,0.1)",backgroundColor:"rgba(0,0,0,0.2)"},children:l.jsxs("div",{style:{display:"flex",gap:"8px"},children:[l.jsx("input",{value:e,onChange:b=>r(b.target.value),onKeyPress:i,onFocus:a,onBlur:o,placeholder:"Ask Bob about car parts...",disabled:s,style:{flex:1,padding:"12px 16px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",color:"white",fontSize:"16px",outline:"none"}}),d&&l.jsx("button",{onClick:d,style:{flexShrink:0,padding:"12px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",cursor:"pointer",minHeight:"unset",minWidth:"unset"},title:u?"Unmute Bob's voice":"Mute Bob's voice",children:u?"🔇":"🔊"}),l.jsx("button",{onClick:n,disabled:s||!e.trim(),style:{flexShrink:0,padding:"12px 20px",background:s||!e.trim()?"rgba(0, 102, 204, 0.3)":"linear-gradient(135deg, rgba(0, 102, 204, 0.95), rgba(0, 73, 153, 1))",color:"white",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.2)",cursor:s||!e.trim()?"not-allowed":"pointer",opacity:s||!e.trim()?.5:1,minHeight:"unset",minWidth:"unset",fontWeight:600},children:"Send"})]})}),l.jsxs("div",{style:{overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px",height:"400px",background:"rgba(0,0,0,0.1)"},children:[[...t].reverse().map((b,m)=>{var k;return l.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:b.role==="user"?"flex-end":"flex-start"},children:l.jsxs("div",{style:{maxWidth:(k=b.suggestedProducts)!=null&&k.length?"100%":"80%",borderRadius:"16px",padding:"12px 16px",fontSize:"14px",backgroundColor:b.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.1)",background:b.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.08)",color:"white",border:"1px solid rgba(255,255,255,0.15)",boxShadow:"0 2px 8px rgba(0,0,0,0.2)"},children:[b.content,b.role==="assistant"&&b.suggestedProducts&&b.suggestedProducts.length>0&&l.jsx(ii,{products:b.suggestedProducts,title:b.suggestionsTitle,onAddToCart:f,onProductClick:y})]})},m)}),l.jsx("div",{ref:c})]})]})}),kd=768,Sd=1024;function ln(){const[t,e]=g.useState("mobile");return g.useEffect(()=>{const r=()=>{const s=window.innerWidth;s>=Sd?e("desktop"):s>=kd?e("tablet"):e("mobile")};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),t}function no(){const t=ln();return Ed(t)}function Ed(t){switch(t){case"mobile":return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-30,hiddenPosition:-100};case"tablet":return{bobOffset:.7,productWidth:.85,uiScale:1.1,partialLeftPosition:-25,hiddenPosition:-80};case"desktop":return{bobOffset:.5,productWidth:.7,uiScale:1.2,partialLeftPosition:-5,hiddenPosition:-60};default:return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-20,hiddenPosition:-100}}}const cn=({currentImage:t,animationState:e,counterOverlayUrl:r,counterHeightPercent:s=15,scale:n=100,position:i="center",verticalOffset:a=0,hasArrived:o=!0})=>{const c=no(),d=95*n/100,h=550*n/100,p=()=>{switch(i){case"center":return"50%";case"partial-left":return`${c.partialLeftPosition}%`;case"hidden":return`${c.hiddenPosition}%`;default:return"50%"}},f=()=>i==="center"?"translateX(-50%)":"translateX(0)",y=s+a,b=()=>i==="hidden"?"all 0.35s cubic-bezier(0.4, 0, 0.2, 1)":"all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)";return l.jsxs("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"visible",zIndex:60},children:[l.jsx("div",{className:"absolute",style:{zIndex:60,bottom:`${y}%`,left:p(),maxHeight:`${100-s-2}%`,transform:f(),width:`${d}%`,maxWidth:`${h}px`,transition:b()+", opacity 0.6s ease-out",willChange:"transform, left, opacity",opacity:o?1:0},children:l.jsx("img",{src:t,alt:`Bob ${e}`,className:"w-full h-auto object-contain",style:{display:"block",maxHeight:"100%",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})}),r&&l.jsx("div",{className:"absolute bottom-0 left-0 right-0",style:{zIndex:70,height:`${s}%`,pointerEvents:"none"},children:l.jsx("img",{src:r,alt:"Shop counter",className:"w-full h-full",style:{objectFit:"fill",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})})]})},io={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)"},un={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},jd={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},Td=({vehicleDisplayName:t,itemCount:e,isUpdating:r})=>l.jsx("div",{className:"sticky top-0 z-10 -mx-1 px-3 py-2.5",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.85) 0%, rgba(0, 73, 153, 0.9) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4)",border:"1px solid rgba(255, 255, 255, 0.25)"},children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[r?l.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:l.jsx("div",{className:"w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"})}):l.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:l.jsx("svg",{className:"w-3.5 h-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),l.jsx("span",{style:{...un.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:r?"Updating...":t})]}),l.jsxs("span",{style:{color:"rgba(255,255,255,0.8)",fontSize:"12px",fontWeight:500},children:[e," ",e===1?"item":"items"]})]})}),Rd=()=>l.jsx("div",{className:"p-5",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(0, 102, 204, 0.3)"},children:l.jsx("div",{className:"w-6 h-6 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"rgba(255,255,255,0.8)",borderTopColor:"transparent"}})}),l.jsxs("div",{children:[l.jsx("p",{style:{...un.primary,fontWeight:600,fontSize:"14px"},children:"Loading parts..."}),l.jsx("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:"Bob's stocking the shelves"})]})]})}),Cd=({productCount:t,packageCount:e})=>l.jsx("div",{className:"p-5",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(255, 149, 0, 0.3)"},children:l.jsx("svg",{className:"w-5 h-5",style:{color:"#FF9500"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),l.jsxs("div",{children:[l.jsx("p",{style:{...un.primary,fontWeight:600,fontSize:"14px"},children:"No products to display"}),l.jsxs("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:["Products: ",t," | Packages: ",e]})]})]})}),Ad=({variants:t,make:e,model:r,onSelect:s})=>{const n=t.map(a=>[a.engineCode,a.kw?`${a.kw}kW`:null,a.ccDisplay||(a.cc?`${a.cc}cc`:null),a.fuelType].filter(Boolean).join(" · ")||a.displayTitle),i=n.reduce((a,o)=>(a[o]=(a[o]||0)+1,a),{});return l.jsxs("div",{className:"flex flex-col gap-3",children:[l.jsx("div",{className:"sticky top-0 z-10 px-4 py-3",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"20px",boxShadow:"0 8px 32px rgba(0, 102, 204, 0.35)",border:"1px solid rgba(255, 255, 255, 0.2)"},children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:l.jsx("svg",{className:"w-4 h-4 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),l.jsxs("div",{children:[l.jsxs("span",{className:"text-white font-semibold text-sm",children:["Which ",e," ",r,"?"]}),l.jsx("span",{className:"text-white/70 text-xs block",children:"Tap your variant to continue"})]})]})}),l.jsx("div",{className:"flex flex-col gap-2 px-1",children:t.map((a,o)=>{const c=n[o],d=i[c]>1&&a.displaySubtitle?a.displaySubtitle:c;return l.jsx("button",{type:"button",onClick:()=>s(a),className:"w-full text-left transition-all duration-200 cursor-pointer rounded-2xl overflow-hidden focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 active:scale-[0.98]",style:{background:"linear-gradient(135deg, rgba(255, 255, 255, 0.92) 0%, rgba(255, 255, 255, 0.85) 100%)",backdropFilter:"blur(12px) saturate(150%)",WebkitBackdropFilter:"blur(12px) saturate(150%)",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.12)",border:"1px solid rgba(255, 255, 255, 0.4)",minHeight:"72px"},children:l.jsxs("div",{className:"flex items-center gap-3 p-4",children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0 font-bold text-lg text-white",style:{background:"linear-gradient(135deg, #0066CC 0%, #0052A3 100%)",boxShadow:"0 2px 8px rgba(0, 102, 204, 0.4)"},children:a.optionNumber}),l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("p",{className:"font-semibold text-gray-900 text-base leading-tight",children:d})}),l.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{background:"rgba(0, 102, 204, 0.1)"},children:l.jsx("svg",{className:"w-4 h-4 text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M9 5l7 7-7 7"})})})]})},a.vehicle_id)})})]})},ao=({children:t,viewportSize:e,className:r="",style:s})=>{const n=g.useRef(null),[i,a]=g.useState(!1),[o,c]=g.useState(!1),[u,d]=g.useState(!1),h=e==="desktop",p=g.useCallback(()=>{const m=n.current;if(!m)return;const k=m.scrollWidth>m.clientWidth+2;d(k),a(m.scrollLeft>2),c(m.scrollLeft<m.scrollWidth-m.clientWidth-2)},[]);g.useEffect(()=>{p();const m=n.current;if(!m)return;const k=new ResizeObserver(p);return k.observe(m),Array.from(m.children).forEach(w=>k.observe(w)),window.addEventListener("resize",p),()=>{k.disconnect(),window.removeEventListener("resize",p)}},[p,t]);const f=(m,k)=>{k.stopPropagation(),k.preventDefault();const w=n.current;if(!w)return;const S=w.clientWidth*.75;w.scrollTo({left:w.scrollLeft+(m==="left"?-S:S),behavior:"smooth"})},y=h&&u,b=h?"":"snap-x snap-mandatory";return l.jsxs("div",{style:{position:"relative",width:"100%",maxWidth:"100%",overflow:"hidden"},children:[y&&i&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{position:"absolute",top:0,bottom:0,left:0,width:40,zIndex:5,pointerEvents:"none",background:"linear-gradient(to right, rgba(0,0,0,0.15), transparent)",borderRadius:"8px 0 0 8px"}}),l.jsx("button",{type:"button",onPointerDown:m=>m.stopPropagation(),onClick:m=>f("left",m),"aria-label":"Scroll left",style:Xi("left"),children:l.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"M15 18l-6-6 6-6"})})})]}),l.jsx("div",{ref:n,className:`${b} ${r}`,style:{...s,display:"flex",overflowX:"auto",width:"100%",maxWidth:"100%",WebkitOverflowScrolling:"touch",...h?{scrollbarWidth:"thin",scrollbarColor:"rgba(255,255,255,0.4) rgba(255,255,255,0.1)"}:{scrollbarWidth:"none",msOverflowStyle:"none",touchAction:"pan-x",overscrollBehavior:"contain"}},onScroll:p,children:t}),y&&o&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{position:"absolute",top:0,bottom:0,right:0,width:40,zIndex:5,pointerEvents:"none",background:"linear-gradient(to left, rgba(0,0,0,0.15), transparent)",borderRadius:"0 8px 8px 0"}}),l.jsx("button",{type:"button",onPointerDown:m=>m.stopPropagation(),onClick:m=>f("right",m),"aria-label":"Scroll right",style:Xi("right"),children:l.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"M9 18l6-6-6-6"})})})]})]})};function Xi(t){return{position:"absolute",top:"50%",transform:"translateY(-50%)",[t]:-4,zIndex:10,width:40,height:40,borderRadius:"50%",background:"rgba(255, 140, 0, 0.95)",color:"white",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",border:"2px solid rgba(255, 255, 255, 0.6)",boxShadow:"0 4px 20px rgba(255, 140, 0, 0.5), 0 2px 8px rgba(0, 0, 0, 0.3)",padding:0,WebkitAppearance:"none",appearance:"none"}}const Od=({tier:t,isSelected:e,viewportSize:r,packageTitle:s,packageId:n,onSelect:i,onAddToCart:a})=>{const o=tn[t.tierName],c=t.savingsAmount&&t.savingsAmount>0,u=r==="desktop"?"240px":r==="tablet"?"190px":"160px",d=t.brands[0],h=d?`${Cr.storageBase}/brand_images/${d.fullName.replace(/\s+/g,"")}.jpg`:"",[p,f]=g.useState(0),y=b=>{b.stopPropagation();const m=t.bundleDiscountPercentage||0,k=1-m/100,w=t.products.map(S=>({id:S.sku,name:S.name,brand:S.brand,price:m>0?Math.round(S.displayPrice*k*100)/100:S.displayPrice,image_url:S.productImageUrl,brandImageUrl:S.brandImageUrl,sku:S.sku,partNumber:S.partNumber||void 0,partslotDescription:S.partslotName,quantity:1,_bundleMeta:{is_bundle_item:!0,bundle_discount_percentage:m,service_package_name:s,service_package_id:n,quality_tier:t.tierName}}));a==null||a(w)};return l.jsxs("div",{onClick:i,className:"flex-shrink-0 cursor-pointer transition-all duration-200 snap-start",style:{width:u,minWidth:"140px",borderRadius:"16px",background:t.isRecommended?"linear-gradient(145deg, rgba(0,82,204,0.04) 0%, rgba(56,189,248,0.04) 100%)":e?"rgba(248,250,252,1)":"#FFFFFF",border:t.isRecommended?`2.5px solid ${G.primary}`:e?`2px solid ${G.primary}60`:"1.5px solid #E2E8F0",boxShadow:t.isRecommended?"0 4px 16px rgba(0,82,204,0.15)":e?"0 2px 12px rgba(0,0,0,0.06)":"0 1px 4px rgba(0,0,0,0.04)",position:"relative",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.isRecommended&&l.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,zIndex:2,background:G.primary,color:"white",fontSize:"10px",fontWeight:700,letterSpacing:"0.06em",textAlign:"center",padding:"5px 0"},children:"★ CARFIX VALUE"}),l.jsx("div",{style:{height:"130px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",padding:"8px 12px",overflow:"hidden",paddingTop:t.isRecommended?"32px":"8px"},children:d&&p<2?l.jsx("img",{src:p===0?d.imageUrl:h,alt:d.fullName,style:{width:"100%",height:"100%",objectFit:"contain"},onError:()=>{f(p===0&&h?1:2)}}):l.jsx("span",{style:{fontSize:"18px",fontWeight:800,color:"#334155",textAlign:"center",lineHeight:1.2},children:(d==null?void 0:d.fullName)||t.dominantBrand})}),l.jsxs("div",{style:{padding:"6px 12px 0",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"6px"},children:[l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[l.jsx("span",{style:{fontSize:"14px",lineHeight:1},children:o==null?void 0:o.emoji}),l.jsx("span",{style:{fontSize:"13px",fontWeight:700,color:(o==null?void 0:o.textColor)||G.foreground},children:t.displayName})]}),d&&p<2&&l.jsx("div",{style:{background:"#F8FAFC",borderRadius:"6px",padding:"3px 6px",border:"1px solid #E2E8F0",display:"flex",alignItems:"center",height:"28px"},children:l.jsx("img",{src:p===0?d.imageUrl:h,alt:d.fullName,style:{height:"28px",width:"auto",objectFit:"contain",maxWidth:"60px"},onError:b=>{b.target.style.display="none"}})})]}),l.jsxs("p",{style:{fontSize:"13px",fontWeight:700,color:G.foreground,textAlign:"left",margin:"3px 0 0",padding:"0 12px"},children:[t.productCount," ",t.productCount===1?"part":"parts"]}),l.jsx("div",{style:{padding:"4px 12px 0",textAlign:"center"},children:c?l.jsxs(l.Fragment,{children:[l.jsx("p",{style:{fontSize:"12px",textDecoration:"line-through",color:"#94A3B8",margin:"0 0 1px"},children:lt(t.originalTotalPrice)}),l.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"center",gap:"5px",flexWrap:"wrap"},children:[l.jsx("span",{style:{fontSize:r==="mobile"?"22px":"26px",fontWeight:800,color:G.foreground,letterSpacing:"-0.03em",lineHeight:1},children:lt(t.totalPrice)}),l.jsxs("span",{style:{fontSize:"10px",fontWeight:700,color:"white",background:G.success,padding:"2px 6px",borderRadius:"6px",whiteSpace:"nowrap",lineHeight:1.4},children:["SAVE ",t.bundleDiscountPercentage,"%"]})]}),l.jsx("p",{style:{fontSize:"9px",color:G.mutedForeground,margin:"2px 0 0"},children:"inc GST"})]}):l.jsxs(l.Fragment,{children:[l.jsx("p",{style:{fontSize:r==="mobile"?"22px":"26px",fontWeight:800,color:t.isRecommended?G.primary:G.foreground,letterSpacing:"-0.03em",lineHeight:1,margin:0},children:lt(t.totalPrice)}),l.jsx("p",{style:{fontSize:"9px",color:G.mutedForeground,margin:"2px 0 0"},children:"inc GST"})]})}),l.jsxs("div",{style:{padding:"8px 12px 12px",display:"flex",gap:"6px",marginTop:"auto"},children:[l.jsx("button",{onClick:y,style:{flex:1,padding:"9px 0",borderRadius:"10px",fontSize:"13px",fontWeight:700,cursor:"pointer",border:t.isRecommended?"none":"1.5px solid #E2E8F0",background:t.isRecommended?"linear-gradient(135deg, #22C55E 0%, #16A34A 100%)":"#FFFFFF",color:t.isRecommended?"white":G.foreground,boxShadow:t.isRecommended?"0 4px 12px rgba(34,197,94,0.3)":"none",transition:"all 0.15s ease"},children:"Add"}),l.jsx("button",{onClick:b=>b.stopPropagation(),style:{width:"38px",minWidth:"38px",padding:"9px 0",borderRadius:"10px",fontSize:"16px",cursor:"pointer",border:"1.5px solid #E2E8F0",background:"#FFFFFF",transition:"all 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",color:"#EF4444"},children:"♡"})]})]})},Pd=({tier:t})=>l.jsx("div",{className:"px-4 pb-4",style:{borderTop:`1px solid ${G.border}`},children:l.jsxs("div",{className:"pt-3",children:[l.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:G.mutedForeground},children:[t.displayName," Tier Products"]}),l.jsx("div",{className:"space-y-2",children:t.products.map(e=>l.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:G.background,border:`1px solid ${G.border}`},children:[l.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg overflow-hidden flex items-center justify-center",style:{width:"48px",height:"48px",minWidth:"48px"},children:e.productImageUrl?l.jsx("img",{src:e.productImageUrl,alt:e.name,className:"object-contain",style:{width:"100%",height:"100%",padding:"4px"}}):l.jsx("svg",{className:"w-5 h-5 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-xs font-medium truncate",style:{color:G.foreground},children:e.name}),l.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[l.jsx("span",{className:"text-[10px]",style:{color:G.mutedForeground},children:e.brand}),e.isRotor&&l.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 font-medium",children:"Pair"})]})]}),l.jsxs("div",{className:"text-right flex-shrink-0",children:[l.jsx("p",{className:"text-sm font-bold",style:{color:G.primary},children:lt(e.displayPrice)}),e.isRotor&&l.jsxs("p",{className:"text-[9px]",style:{color:G.mutedForeground},children:["$",e.price.toFixed(2)," ea"]})]})]},e.sku))})]})}),oo=["SHOE","DRUM"],lo=["PAD","ROTOR"];function co(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 uo(t,e){const r=e==="disc"?oo:lo;return t.filter(s=>{const n=s.partslotName.toUpperCase();return!r.some(i=>n.includes(i))})}function ho(t){return t.reduce((e,r)=>e+r.displayPrice,0)}function fo(t){const e=t.flatMap(n=>n.products),r=e.some(n=>{const i=n.partslotName.toUpperCase();return n.displayPrice>0&&lo.some(a=>i.includes(a))}),s=e.some(n=>{const i=n.partslotName.toUpperCase();return n.displayPrice>0&&oo.some(a=>i.includes(a))});return{hasDisc:r,hasDrum:s}}const Id=({pkg:t,viewportSize:e,onAddToCart:r})=>{var x,A;const[s,n]=g.useState(!1),[i,a]=g.useState(null),[o,c]=g.useState("disc"),u=co(t),d=(t.preparedTiers||[]).filter(T=>!T.isHidden),{hasDisc:h,hasDrum:p}=u?fo(d):{hasDisc:!1,hasDrum:!1},f=u&&h&&!p?"disc":u&&p&&!h?"drum":o;let y=d;u&&(y=d.map(T=>{const R=uo(T.products,f);return{...T,products:R,totalPrice:ho(R),productCount:R.length}}));const b=((x=y.find(T=>T.isRecommended))==null?void 0:x.tierName)||((A=y[0])==null?void 0:A.tierName)||"",m=i||b,k=y.find(T=>T.tierName===m),S=ro(t.title).split(".")[0]+".";return l.jsxs("div",{className:"transition-all duration-300",style:{borderRadius:"20px",background:"linear-gradient(145deg, rgba(255,255,255,0.97) 0%, rgba(248,250,252,0.95) 100%)",boxShadow:"0 8px 32px rgba(0,0,0,0.08), 0 2px 8px rgba(0,0,0,0.04)",border:"1px solid rgba(226,232,240,0.8)"},children:[l.jsx("div",{className:"px-4 py-3.5 overflow-hidden",style:{background:`linear-gradient(135deg, ${G.primary} 0%, #0066DD 100%)`,borderRadius:"20px 20px 0 0"},children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-10 h-10 rounded-2xl bg-white/15 flex items-center justify-center flex-shrink-0 backdrop-blur-sm",children:l.jsx("svg",{className:"h-5 w-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("h3",{className:"text-white font-bold text-[15px] leading-tight truncate",children:t.title}),t.estimated_time&&l.jsxs("span",{className:"text-white/60 text-[11px] flex items-center gap-1 mt-0.5",children:[l.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),t.estimated_time]})]})]})}),l.jsxs("div",{className:"px-4 py-2.5",children:[l.jsx("p",{className:"text-[12px] leading-relaxed",style:{color:G.mutedForeground},children:S}),u&&h&&p&&l.jsx("div",{className:"mt-2",children:l.jsxs("div",{className:"flex rounded-xl overflow-hidden",style:{border:`1px solid ${G.border}`},children:[l.jsx("button",{onClick:()=>c("disc"),className:"flex-1 py-1.5 px-3 text-[11px] font-semibold transition-all",style:{background:f==="disc"?G.primary:"transparent",color:f==="disc"?"#FFFFFF":G.mutedForeground},children:"Disc Brakes"}),l.jsx("button",{onClick:()=>c("drum"),className:"flex-1 py-1.5 px-3 text-[11px] font-semibold transition-all",style:{background:f==="drum"?G.primary:"transparent",color:f==="drum"?"#FFFFFF":G.mutedForeground},children:"Drum Brakes"})]})})]}),y.length>0&&l.jsx("div",{className:"pb-3",children:l.jsx(ao,{viewportSize:e,className:"gap-4 px-4 pb-2",children:y.map(T=>l.jsx(Od,{tier:T,isSelected:T.tierName===m,viewportSize:e,packageTitle:t.title,packageId:t.id,onSelect:()=>a(T.tierName),onAddToCart:r},T.tierName))})}),l.jsxs("div",{onClick:()=>n(!s),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer transition-colors",style:{borderTop:`1px solid ${G.border}`},children:[l.jsx("span",{style:{fontSize:"11px",color:G.mutedForeground},children:s?"Hide details":"Show details"}),l.jsx("svg",{className:`transition-transform duration-200 ${s?"rotate-180":""}`,style:{width:"14px",height:"14px",color:G.mutedForeground},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),s&&k&&l.jsx(Pd,{tier:k})]})},po=({product:t,isSpotlighted:e=!1,onProductClick:r,onAddToCart:s})=>{const[n,i]=g.useState(0),a=t.brand?`${Cr.storageBase}/brand_images/${t.brand.replace(/\s+/g,"")}.jpg`:void 0,o=n===0?t.image_url:n===1?t.brandImageUrl||a:void 0,c=()=>{n===0&&(t.brandImageUrl||a)?i(1):i(2)},u=t.webDescription||t.name;return l.jsxs("div",{onClick:()=>r==null?void 0:r(t),className:"flex-shrink-0 cursor-pointer transition-all duration-200",style:{borderRadius:"14px",background:"#0F172A",border:e?`2px solid ${G.primary}`:"1px solid #1E293B",boxShadow:e?"0 4px 16px rgba(0,82,204,0.25)":"0 2px 8px rgba(0,0,0,0.2)",position:"relative",display:"flex",flexDirection:"column",overflow:"hidden"},children:[e&&l.jsx("div",{style:{position:"absolute",top:"6px",right:"6px",zIndex:2,background:G.primary,color:"white",fontSize:"9px",fontWeight:700,padding:"3px 8px",borderRadius:"10px",letterSpacing:"0.03em"},children:"⭐ Bob's Pick"}),l.jsx("div",{style:{height:"100px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",borderRadius:"13px 13px 0 0"},children:o&&n<2?l.jsx("img",{src:o,alt:t.name,loading:"lazy",style:{width:"100%",height:"100%",objectFit:"contain"},onError:c}):l.jsx("span",{style:{fontSize:"22px",fontWeight:800,color:"#94A3B8",textAlign:"center",letterSpacing:"0.02em"},children:t.brand||"No Image"})}),l.jsx("div",{style:{padding:"8px 10px 0"},children:l.jsx("p",{style:{fontSize:"12px",fontWeight:600,color:"#E2E8F0",lineHeight:1.3,overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",margin:0},children:u})}),l.jsxs("div",{style:{padding:"4px 10px 0",display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},children:[t.brand&&l.jsx("span",{style:{fontSize:"10px",fontWeight:600,color:"#94A3B8",background:"rgba(255,255,255,0.08)",padding:"1px 6px",borderRadius:"6px",border:"1px solid #334155"},children:t.brand}),t.perCarQty&&t.perCarQty>1&&l.jsxs("span",{style:{fontSize:"10px",fontWeight:600,color:G.accent,background:`${G.accent}18`,padding:"1px 6px",borderRadius:"6px"},children:["Qty: ",t.perCarQty]})]}),(t.viscosity||t.volume)&&l.jsx("p",{style:{fontSize:"10px",color:"#64748B",margin:"2px 0 0",padding:"0 10px"},children:[t.viscosity,t.volume].filter(Boolean).join(" / ")}),l.jsxs("div",{style:{padding:"6px 10px 0",textAlign:"left"},children:[l.jsx("p",{style:{fontSize:"28px",fontWeight:800,color:"#FFFFFF",letterSpacing:"-0.02em",lineHeight:1,margin:0},children:t.price>0?lt(t.price):"POA"}),l.jsx("p",{style:{fontSize:"10px",color:"#64748B",margin:"2px 0 0"},children:"inc GST"})]}),l.jsxs("div",{style:{padding:"8px 10px 10px",display:"flex",gap:"6px",marginTop:"auto"},children:[l.jsx("button",{onClick:d=>{d.stopPropagation(),s==null||s(t)},style:{flex:1,padding:"8px 0",borderRadius:"10px",fontSize:"12px",fontWeight:700,cursor:"pointer",border:"none",background:"linear-gradient(135deg, #22C55E 0%, #16A34A 100%)",color:"white",boxShadow:"0 4px 12px rgba(34,197,94,0.3)",transition:"all 0.15s ease"},children:"Add"}),l.jsx("button",{onClick:d=>d.stopPropagation(),style:{width:"36px",minWidth:"36px",padding:"8px 0",borderRadius:"10px",fontSize:"15px",cursor:"pointer",border:"1px solid #334155",background:"rgba(255,255,255,0.05)",transition:"all 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",color:"#EF4444"},children:"♡"})]}),t.partslotDescription&&l.jsx("div",{style:{borderTop:"1px solid #1E293B",padding:"4px 10px 6px"},children:l.jsx("span",{style:{fontSize:"9px",color:"#475569"},children:t.partslotDescription})})]})},Nd=(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},Fd=({name:t,products:e,viewportSize:r,isHighlighted:s,highlightedProduct:n,onProductClick:i,onAddToCart:a})=>l.jsxs("section",{className:"transition-all duration-300",style:{background:"transparent",borderRadius:"24px"},children:[l.jsxs("div",{"data-testid":"partslot-header","data-partslot-name":t,className:"px-3 py-2.5 flex items-center justify-between",style:{background:s?"rgba(0, 102, 204, 0.95)":"rgba(0, 51, 102, 0.9)",borderRadius:"16px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",marginBottom:"8px"},children:[l.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l.jsx("div",{className:"w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0",style:{background:s?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 1) 100%)":"rgba(255,255,255,0.2)"},children:l.jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),l.jsx("span",{className:"text-xs font-bold truncate uppercase tracking-wide",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)"},children:t})]}),l.jsx("span",{className:"text-[10px] font-bold px-2.5 py-1 rounded-full flex-shrink-0",style:{background:"rgba(255, 149, 0, 0.9)",color:"white",boxShadow:"0 2px 8px rgba(255, 149, 0, 0.4)"},children:e.length})]}),l.jsx(ao,{viewportSize:r,className:"gap-3 pb-2",children:e.map((o,c)=>{const u=!!(n&&Nd(o,n));return l.jsx("div",{"data-testid":"partslot-product",className:"snap-start flex-shrink-0",style:{width:r==="desktop"?"250px":r==="tablet"?"45%":"65%",minWidth:r==="desktop"?"250px":void 0},children:l.jsx(po,{product:o,isSpotlighted:u,onProductClick:i,onAddToCart:a})},`${o.id}-${c}`)})})]}),wn=(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))},dn=({products:t,servicePackages:e,highlightedPartType:r,highlightedProduct:s,scrollToCategory:n,onScrollToCategoryComplete:i,onProductClick:a,isResearching:o,visible:c=!0,onAddToCart:u,vehicleMakeModel:d,pendingVariants:h,pendingVariantMake:p,pendingVariantModel:f,onVariantSelect:y})=>{const b=d||"Bob's Shelf",m=ln(),k=g.useRef(null),w=g.useRef({}),[S,x]=g.useState(0),A=g.useMemo(()=>{const B={};return t.forEach(N=>{const H=N.partslotDescription||"Other Parts";B[H]||(B[H]=[]),B[H].push(N)}),Object.keys(B).sort((N,H)=>N.localeCompare(H)).map(N=>({name:N,products:B[N]}))},[t]);g.useEffect(()=>{if(!r)return;const B=setTimeout(()=>{for(const[N,H]of Object.entries(w.current))if(H&&wn(N,r)){H.scrollIntoView({behavior:"smooth",block:"start"});break}},300);return()=>clearTimeout(B)},[r]),g.useEffect(()=>{if(!n)return;const B=setTimeout(()=>{for(const[N,H]of Object.entries(w.current))if(H&&wn(N,n)){H.scrollIntoView({behavior:"smooth",block:"start"});break}i==null||i()},300);return()=>clearTimeout(B)},[n]);const T=B=>{const N=B.currentTarget,H=N.scrollHeight-N.clientHeight;H>0&&x(Math.max(0,Math.min(1,N.scrollTop/H)))},R=((h==null?void 0:h.length)??0)>0,E=t.length>0||e.length>0||R,O=o&&!E,j=E&&!O,C=c||E,L=m==="mobile"?92:m==="tablet"?65:70,P=m==="desktop"?"900px":m==="tablet"?"500px":"100%",F=m==="mobile"?"calc(8px + env(safe-area-inset-top, 4px))":"6px";return l.jsxs(l.Fragment,{children:[E&&c&&l.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${S*65+18}%)`,...jd,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),l.jsxs("div",{ref:k,onScroll:T,className:`absolute overflow-y-auto flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${C?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${L}%`,maxWidth:P,right:"0",left:"auto",top:F,bottom:m==="mobile"?"calc(100px + env(safe-area-inset-bottom, 0px))":"52px",paddingTop:"4px",paddingRight:"8px",paddingLeft:"8px",paddingBottom:"8px",zIndex:55,pointerEvents:"auto",touchAction:"auto",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"},children:[l.jsx(Td,{vehicleDisplayName:b,itemCount:t.length+e.length,isUpdating:!!(o&&E)}),O&&l.jsx(Rd,{}),R&&h&&y&&l.jsx(Ad,{variants:h,make:p,model:f,onSelect:y}),!O&&!E&&l.jsx(Cd,{productCount:t.length,packageCount:e.length}),j&&e.length>0&&l.jsx("div",{className:"space-y-6",children:e.map(B=>l.jsx("div",{ref:N=>{w.current[B.title]=N},children:l.jsx(Id,{pkg:B,viewportSize:m,onAddToCart:u})},B.id))}),j&&A.map(({name:B,products:N})=>l.jsx("div",{ref:H=>{w.current[B]=H},children:l.jsx(Fd,{name:B,products:N,viewportSize:m,isHighlighted:!!(r&&wn(B,r)),highlightedProduct:s,onProductClick:a,onAddToCart:u})},B)),l.jsx("div",{className:"h-4"})]})]})},ai=({onTranscript:t,onSpeechEnd:e,language:r="en-NZ",mode:s="toggle"}={})=>{const[n,i]=g.useState(!1),[a,o]=g.useState(""),[c,u]=g.useState(""),[d,h]=g.useState(null),[p,f]=g.useState(!1),y=g.useRef(null),b=g.useRef(""),m=g.useRef(t),k=g.useRef(e),w=g.useRef(null),S=15e3;g.useEffect(()=>{m.current=t,k.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)"),f(!1);return}const R=window.SpeechRecognition||window.webkitSpeechRecognition;if(R){f(!0);const E=new R;E.continuous=s==="ptt",E.interimResults=!0,E.lang=r,E.maxAlternatives=1,E.onstart=()=>{i(!0),h(null)},E.onresult=O=>{let j="",C="";for(let L=O.resultIndex;L<O.results.length;L++){const P=O.results[L][0].transcript;O.results[L].isFinal?C+=P:j+=P}C&&(b.current=C,o(C),m.current&&m.current(C)),u(j)},E.onerror=O=>{switch(i(!1),O.error){case"no-speech":h("No speech detected. Please try again.");break;case"audio-capture":h("No microphone found. Please check your device.");break;case"not-allowed":h("Microphone permission denied. Please allow access.");break;default:h("Speech recognition error. Please try again.")}},E.onend=()=>{w.current&&(clearTimeout(w.current),w.current=null),i(!1),u(""),b.current&&k.current&&k.current(b.current),b.current=""},y.current=E}return()=>{y.current&&y.current.stop()}},[r,s]);const x=()=>{if(y.current&&!n){o(""),u(""),h(null),w.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(R){console.warn("[SpeechRecognition] start() failed (already running):",R),w.current&&(clearTimeout(w.current),w.current=null)}}},A=()=>{w.current&&(clearTimeout(w.current),w.current=null),y.current&&n&&y.current.stop()};return{isListening:n,transcript:a,interimTranscript:c,error:d,isSupported:p,startListening:x,stopListening:A,toggleListening:()=>{n?A():x()}}},go=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:o,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onAddToCart:p,onProductClick:f,onQuickReply:y,onInterrupt:b,counterHeightPercent:m=22})=>{var Ee;const[k,w]=g.useState(!1),S=g.useRef(null),x=g.useRef(!1),{bottomOffset:A,zIndexBase:T}=ni(),{isListening:R,interimTranscript:E,error:O,isSupported:j,startListening:C,stopListening:L}=ai({onTranscript:te=>r(te),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{E&&r(E)},[E,r]);const P=h?"speaking":s?"processing":R?"listening":"idle",F=g.useCallback(te=>{if(te.preventDefault(),P==="speaking"){b==null||b();return}s||x.current||(x.current=!0,navigator.vibrate&&navigator.vibrate(30),C())},[P,s,C,b]),B=g.useCallback(()=>{x.current&&(x.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),L(),setTimeout(()=>{n()},150))},[L,n]),N=[...t].reverse().find(te=>te.role==="assistant"),H=((Ee=N==null?void 0:N.suggestedProducts)==null?void 0:Ee.length)||0,Z=N!=null&&N.content?N.content.length>50?N.content.slice(0,50)+"...":N.content:"Ask Bob about car parts...",W=H>0?` (${H} products)`:"",z={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"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)"}},re={idle:z.idle,listening:z.active,processing:z.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)"}}[P],se={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return l.jsxs("div",{ref:S,style:{position:"fixed",bottom:A,left:0,right:0,...io,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:k?"55vh":"90px",zIndex:T+80,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[l.jsx("button",{onClick:()=>w(!k),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:T+90,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":k?"Collapse chat":"Expand chat",children:k?l.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):l.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!k&&l.jsx("div",{onClick:()=>w(!0),style:{padding:"8px 12px 2px 12px",cursor:"pointer"},children:l.jsxs("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Z,W&&l.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:W})]})}),k&&l.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map((te,ge)=>{var je;return l.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:te.role==="user"?"flex-end":"flex-start"},children:l.jsxs("div",{style:{maxWidth:(je=te.suggestedProducts)!=null&&je.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:te.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:[te.content,te.role==="assistant"&&te.suggestedProducts&&te.suggestedProducts.length>0&&l.jsx(ii,{products:te.suggestedProducts,title:te.suggestionsTitle,onAddToCart:p,onProductClick:f}),te.role==="assistant"&&te.quickReplies&&te.quickReplies.length>0&&l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:te.quickReplies.map((U,$e)=>l.jsx("button",{onClick:Ve=>{Ve.stopPropagation(),b==null||b(),y==null||y(U.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:U.label},$e))})]})},ge)}),l.jsx("div",{ref:c})]}),j&&l.jsxs("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px",position:"relative"},children:[P==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),P!=="listening"&&se[P]&&l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:se[P].border,transform:"translate(-50%, -50%)",animation:se[P].animation,pointerEvents:"none"}}),l.jsx("button",{onTouchStart:F,onTouchEnd:B,onTouchCancel:B,onMouseDown:F,onMouseUp:B,onMouseLeave:B,onClick:R?B:void 0,disabled:P==="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:P==="processing"?"not-allowed":"pointer",opacity:P==="processing"?.6:1,transform:P==="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:re.backdropFilter,WebkitBackdropFilter:re.WebkitBackdropFilter,"--bob-ptt-bg":re.background,"--bob-ptt-shadow":re.boxShadow,"--bob-ptt-border":re.border,"--bob-ptt-radius":"32px"},title:"Hold to talk",children:l.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...un.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:P==="listening"?"LISTENING":P==="processing"?"THINKING":P==="speaking"?"TAP TO STOP":"TALK"})})]}),l.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[O&&l.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:O}),l.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[d&&l.jsx("button",{onClick:d,style:{flexShrink:0,height:"40px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"12px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?l.jsxs("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):l.jsx("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),l.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[l.jsx("input",{type:"text",value:e,onChange:te=>r(te.target.value),onKeyPress:i,onFocus:a,onBlur:o,placeholder:"Message Bob...",disabled:P!=="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:P!=="idle"?0:1,transition:"opacity 0.15s ease"}}),P!=="idle"&&l.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[P==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),P==="processing"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),P==="speaking"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map((te,ge)=>l.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${te}s infinite`}},ge))}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&l.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]})]})]})]})},bo=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:p,chatEndRef:f,isMuted:y,onToggleMute:b,isSpeaking:m,products:k,servicePackages:w,highlightedPartType:S,highlightedProduct:x,scrollToCategory:A,onScrollToCategoryComplete:T,onProductClick:R,onPackageSelect:E,isResearching:O,onAddToCart:j,onQuickReply:C,onInterrupt:L,vehicle:P,onChangeVehicle:F,pendingVariants:B,pendingVariantMake:N,pendingVariantModel:H,onVariantSelect:Z,bobOffset:W=0,bobScale:z=100,embedded:fe=!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 re=ln(),[se,Ee]=g.useState("center"),[te,ge]=g.useState("hidden"),je=k.length>0||w.length>0,U=((B==null?void 0:B.length)??0)>0,$e=je||U,_e=(()=>{switch(re){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*z/100;g.useEffect(()=>{if(O&&te!=="loading"&&te!=="visible")ge("loading"),se==="center"&&Ee("partial-left");else if($e&&te!=="visible")if(se==="center"){Ee("partial-left"),ge("transitioning");const ct=setTimeout(()=>{ge("visible")},400);return()=>clearTimeout(ct)}else ge("visible");else!$e&&!O&&te!=="hidden"&&(ge("hidden"),Ee("center"))},[$e,O,te,se]);const De=te!=="hidden";return l.jsxs("div",{className:fe?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:fe?"100%":"100dvh",touchAction:"manipulation"},children:[r&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)",transform:"scale(1.02)"}}),l.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))"}})]}),l.jsx(cn,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:_e,position:se,verticalOffset:W}),l.jsx(dn,{products:k,servicePackages:w,highlightedPartType:S,highlightedProduct:x,scrollToCategory:A,onScrollToCategoryComplete:T,onProductClick:R,onPackageSelect:E,isResearching:O,visible:De,counterHeightPercent:n,hasVehicle:!!P,onAddToCart:j,pendingVariants:B,pendingVariantMake:N,pendingVariantModel:H,onVariantSelect:Z}),l.jsx(go,{messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:p,chatEndRef:f,isMuted:y,onToggleMute:b,isSpeaking:m,onAddToCart:j,onProductClick:R,onQuickReply:C,onInterrupt:L,counterHeightPercent:n})]})};function Bd(t){const[e,r]=g.useState(null);return g.useEffect(()=>{const s=t.current;if(!s||(r(s.getBoundingClientRect().height),typeof ResizeObserver>"u"))return;const n=new ResizeObserver(i=>{var a,o;for(const c of i){const u=((o=(a=c.borderBoxSize)==null?void 0:a[0])==null?void 0:o.blockSize)??c.contentRect.height;u>0&&r(u)}});return n.observe(s),()=>n.disconnect()},[t]),e}const mo=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:o,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onQuickReply:p,onInterrupt:f,counterHeightPercent:y=22})=>{const[b,m]=g.useState(!1),k=g.useRef(null),w=g.useRef(!1),{bottomOffset:S,zIndexBase:x}=ni(),{isListening:A,interimTranscript:T,error:R,isSupported:E,startListening:O,stopListening:j}=ai({onTranscript:z=>r(z),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{T&&r(T)},[T,r]);const C=h?"speaking":s?"processing":A?"listening":"idle",L=g.useCallback(z=>{if(z.preventDefault(),C==="speaking"){f==null||f();return}s||w.current||(w.current=!0,navigator.vibrate&&navigator.vibrate(30),O())},[C,s,O,f]),P=g.useCallback(()=>{w.current&&(w.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),j(),setTimeout(()=>{n()},150))},[j,n]),F=[...t].reverse().find(z=>z.role==="assistant"),B=F!=null&&F.content?F.content.length>50?F.content.slice(0,50)+"...":F.content:"Ask Bob about car parts...",N={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:N.idle,listening:N.active,processing:N.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)"}}[C],W={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return l.jsxs("div",{ref:k,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",willChange:"transform, height",...io,background:"rgba(15, 23, 42, 0.92)",borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"height 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:b?"55%":"110px",overflow:"visible",zIndex:x+30,paddingBottom:"calc(8px + env(safe-area-inset-bottom, 0px))",pointerEvents:"none"},children:[l.jsx("button",{onClick:()=>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:x+40,cursor:"pointer",minHeight:"32px",minWidth:"32px",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto"},"aria-label":b?"Collapse chat":"Expand chat",children:b?l.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 9l-7 7-7-7"})}):l.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M5 15l7-7 7 7"})})}),!b&&l.jsx("div",{onClick:()=>m(!0),style:{padding:"6px 12px 4px 12px",height:"26px",overflow:"hidden",cursor:"pointer",pointerEvents:"auto"},children:l.jsx("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:B})}),b&&l.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px",pointerEvents:"auto"},className:"glass-scroll",children:[[...t].reverse().map((z,fe)=>l.jsx("div",{style:{display:"flex",justifyContent:z.role==="user"?"flex-end":"flex-start"},children:l.jsxs("div",{style:{maxWidth:"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:z.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:[z.content,z.role==="assistant"&&z.quickReplies&&z.quickReplies.length>0&&l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:z.quickReplies.map((re,se)=>l.jsx("button",{onClick:Ee=>{Ee.stopPropagation(),f==null||f(),p==null||p(re.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:re.label},se))})]})},fe)),l.jsx("div",{ref:c})]}),l.jsxs("div",{style:{padding:b?"8px 12px 4px 12px":"4px 12px 4px 12px",borderTop:b?"1px solid rgba(255, 255, 255, 0.15)":"none",pointerEvents:"auto"},children:[R&&l.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:R}),l.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&b&&l.jsx("button",{onClick:d,style:{flexShrink:0,height:"36px",width:"36px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"10px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#22c55e":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?l.jsxs("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):l.jsx("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),l.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[l.jsx("input",{type:"text",value:e,onChange:z=>r(z.target.value),onKeyPress:i,onFocus:a,onBlur:o,placeholder:"Message Bob...",disabled:C!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:C!=="idle"?0:1,transition:"opacity 0.15s ease"}}),C!=="idle"&&l.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[C==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),C==="processing"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),C==="speaking"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map((z,fe)=>l.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${z}s infinite`}},fe))}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&l.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]}),E&&l.jsxs("div",{style:{position:"relative",marginLeft:"4px"},children:[C==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),C!=="listening"&&W[C]&&l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:W[C].border,transform:"translate(-50%, -50%)",animation:W[C].animation,pointerEvents:"none"}}),l.jsxs("button",{onTouchStart:L,onTouchEnd:P,onTouchCancel:P,onMouseDown:L,onMouseUp:P,onMouseLeave:P,disabled:C==="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:C==="processing"?"not-allowed":"pointer",opacity:C==="processing"?.6:1,transform:C==="listening"?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.3s ease",zIndex:x+45,backdropFilter:Z.backdropFilter,WebkitBackdropFilter:Z.WebkitBackdropFilter,"--bob-ptt-bg":Z.background,"--bob-ptt-shadow":Z.boxShadow,"--bob-ptt-border":Z.border,"--bob-ptt-radius":"50%"},title:"Hold to talk",children:[l.jsx("svg",{style:{height:"28px",width:"28px",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2))"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})}),C==="listening"&&l.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",width:"12px",height:"12px",borderRadius:"50%",backgroundColor:"#fef3c7",animation:"ptt-dot 0.6s ease-in-out infinite alternate"}})]})]})]})]})]})},Ld=({product:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{const n=t.productUrl||t.product_url,i=t.partNumber||t.part_number,a=!!n||!!s;return l.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-white/95 backdrop-blur-md overflow-hidden",children:[l.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-gray-200 bg-white/80 backdrop-blur-sm",children:l.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-blue-600 font-medium text-sm hover:text-blue-700 active:scale-95 transition-all",children:[l.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back to Products"]})}),l.jsxs("div",{className:"flex-1 overflow-y-auto",children:[l.jsx("div",{className:"aspect-square bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center",children:t.image_url?l.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):l.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[l.jsx("svg",{className:"h-16 w-16 mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),l.jsx("span",{className:"text-sm font-medium uppercase tracking-wide",children:"No Image Available"})]})}),l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("div",{children:[l.jsx("h1",{className:"text-xl font-bold text-gray-900 mb-1",children:t.name}),t.brand&&l.jsx("p",{className:"text-sm text-gray-600 font-medium",children:t.brand})]}),l.jsxs("div",{className:"bg-blue-50 rounded-xl p-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-1",children:"Price"}),l.jsx("p",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"Price on Request"}),t.price>0&&l.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Inc. GST"})]}),l.jsxs("div",{className:"space-y-3",children:[t.partslotDescription&&l.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"Category"}),l.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.partslotDescription})]}),t.sku&&l.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"SKU"}),l.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.sku})]}),i&&l.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"Part Number"}),l.jsx("span",{className:"text-sm font-medium text-gray-900",children:i})]})]}),a&&l.jsx("a",{href:n||"#",onClick:o=>{s&&(o.preventDefault(),s(t))},target:n&&!s?"_blank":void 0,rel:n&&!s?"noopener noreferrer":void 0,className:"block text-center text-blue-600 text-sm font-medium hover:underline py-2",children:"View Full Details on CARFIX →"})]})]}),l.jsx("div",{className:"p-4 border-t border-gray-200 bg-white/95 backdrop-blur-sm",children:l.jsx("button",{onClick:()=>r==null?void 0:r(t),className:"w-full bg-blue-600 text-white text-base font-semibold py-3 rounded-xl hover:bg-blue-700 active:bg-blue-800 transition-colors shadow-lg",children:"Add to Cart"})})]})},yo=({package:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{var S;const[n,i]=g.useState(!1),a=g.useMemo(()=>co(t),[t.id,t.title]),{hasDisc:o,hasDrum:c}=g.useMemo(()=>{if(!a||!t.preparedTiers)return{hasDisc:!1,hasDrum:!1};const x=t.preparedTiers.filter(A=>!A.isHidden);return fo(x)},[a,t.preparedTiers]),[u,d]=g.useState("disc"),h=g.useMemo(()=>!a||o&&!c?"disc":c&&!o?"drum":u,[a,o,c,u]),p=a&&o&&c,f=g.useMemo(()=>{if(!t.preparedTiers||t.preparedTiers.length===0)return[];const x=t.preparedTiers.filter(A=>!A.isHidden);return a?x.map(A=>{const T=uo(A.products,h);return{...A,products:T,totalPrice:ho(T),productCount:T.length}}):x},[t.preparedTiers,a,h]),y=f.length>0,b=x=>{const A=x.bundleDiscountPercentage||0,T=1-A/100,R=x.products.map(E=>({...E,displayPrice:A>0?Math.round(E.displayPrice*T*100)/100:E.displayPrice,_bundleMeta:{is_bundle_item:!0,bundle_discount_percentage:A,service_package_name:t.title,service_package_id:t.id,quality_tier:x.tierName}}));r==null||r(R)},m=x=>x===2?"grid-cols-2":x===3?"grid-cols-3":"grid-cols-2",k=ro(t.title),w=((S=f[0])==null?void 0:S.productCount)||0;return l.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-[#FAFAFA] overflow-hidden",children:[l.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#E2E8F0] bg-white shadow-sm",children:l.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-[#0052CC] font-medium text-sm hover:text-[#0047B3] active:scale-95 transition-all",children:[l.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]})}),l.jsxs("div",{className:"flex-1 overflow-y-auto",children:[l.jsxs("div",{className:"px-4 pt-4 pb-4",style:{background:"linear-gradient(135deg, rgba(0,82,204,0.05) 0%, rgba(56,189,248,0.05) 100%)"},children:[l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 bg-white shadow-md",children:t.icon_url?l.jsx("img",{src:t.icon_url,alt:"",className:"w-8 h-8 object-contain"}):l.jsx("svg",{className:"w-7 h-7 text-[#0052CC]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("h1",{className:"text-xl font-bold text-[#0F172A]",children:t.title}),l.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#64748B]",children:[t.estimated_time&&l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),t.estimated_time]}),t.difficulty_level&&l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085"})}),t.difficulty_level]})]})]})]}),l.jsx("p",{className:"text-sm text-[#64748B] mt-3 leading-relaxed",children:k}),p&&l.jsxs("div",{className:"mt-3",children:[l.jsx("p",{className:"text-[11px] text-[#94A3B8] mb-1.5",children:"Select your vehicle's rear brake type"}),l.jsxs("div",{className:"flex rounded-xl overflow-hidden border border-[#E2E8F0] bg-white",children:[l.jsx("button",{onClick:()=>d("disc"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:u==="disc"?G.primary:"transparent",color:u==="disc"?"#FFFFFF":"#64748B"},children:"Disc Brakes (Pads + Rotors)"}),l.jsx("button",{onClick:()=>d("drum"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:u==="drum"?G.primary:"transparent",color:u==="drum"?"#FFFFFF":"#64748B"},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),l.jsxs("div",{className:"px-4 py-3 flex items-center justify-center gap-2 border-b border-[#E2E8F0] bg-white",children:[l.jsx("span",{className:"font-semibold text-[#0F172A] text-sm",children:"Choose Your Value Level"}),l.jsx("span",{className:"text-[#64748B] text-xs cursor-help",title:"Select the quality tier that suits your needs",children:"ⓘ"})]}),l.jsx("div",{className:"p-4",children:y?l.jsx("div",{className:`grid ${m(f.length)} gap-3`,children:f.map(x=>{const A=tn[x.tierName];return l.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:x.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[x.isRecommended&&l.jsx("div",{className:"absolute top-0 left-0 right-0 px-2 py-1 text-[9px] font-bold text-white text-center",style:{background:G.primary},children:"★ CARFIX VALUE"}),l.jsxs("div",{className:`p-3 flex-1 flex flex-col ${x.isRecommended?"pt-7":""}`,children:[l.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[l.jsx("span",{className:"text-lg",children:A==null?void 0:A.emoji}),l.jsxs("div",{children:[l.jsx("span",{className:"font-bold text-sm block",style:{color:(A==null?void 0:A.textColor)||G.foreground},children:x.displayName}),l.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:x.description||(A==null?void 0:A.description)})]})]}),l.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:x.brands.slice(0,3).map(T=>l.jsx("div",{className:"h-10 px-2 bg-white rounded-xl flex items-center justify-center shadow-md border border-[#F1F5F9]",children:l.jsx("img",{src:T.imageUrl,alt:T.fullName,className:"h-6 w-auto object-contain",onError:R=>{const E=R.target,O=`${Cr.storageBase}/brand_images/${T.fullName.replace(/\s+/g,"")}.jpg`;if(E.src!==O)E.src=O;else{const j=E.parentElement;j&&(j.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${T.name}</span>`)}}})},T.name))}),l.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[x.productCount," part",x.productCount!==1?"s":""," included"]}),l.jsx("div",{className:"mt-auto",children:x.savingsAmount&&x.savingsAmount>0?l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-xs line-through text-[#94A3B8]",children:lt(x.originalTotalPrice)}),l.jsx("p",{className:"text-xl font-bold",style:{color:"#22C55E"},children:lt(x.totalPrice)}),l.jsxs("p",{className:"text-[10px] font-semibold text-[#22C55E] bg-[#22C55E]/10 inline-block px-1.5 py-0.5 rounded-full mt-0.5",children:["SAVE ",lt(x.savingsAmount)," — ",x.bundleDiscountPercentage,"% Bundle Deal"]})]}):l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-xl font-bold",style:{color:x.isRecommended?"#0052CC":"#0F172A"},children:lt(x.totalPrice)}),l.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]})}),l.jsx("button",{onClick:()=>b(x),className:`mt-3 w-full px-3 py-2.5 rounded-xl text-xs font-semibold transition-all hover:scale-[1.02] active:scale-95 flex items-center justify-center ${x.isRecommended?"bg-[#22C55E] text-white shadow-md hover:bg-[#16A34A]":"bg-slate-100 text-[#22C55E] border border-slate-200 hover:bg-slate-200"}`,children:"Add to Cart"})]})]},x.tierName)})}):l.jsxs("div",{className:"rounded-2xl p-6 bg-white border border-[#E2E8F0] shadow-md text-center",children:[l.jsx("svg",{className:"w-12 h-12 mx-auto text-[#94A3B8] mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),l.jsx("p",{className:"text-sm font-medium text-[#64748B]",children:"Package details not available for this vehicle"}),l.jsx("p",{className:"text-xs text-[#94A3B8] mt-1",children:"Please try refreshing or contact support"})]})}),y&&l.jsxs("div",{className:"px-4 pb-4",children:[l.jsxs("button",{onClick:()=>i(!n),className:"w-full flex items-center justify-between p-3 rounded-xl bg-white border border-[#E2E8F0] hover:bg-slate-50 transition-all shadow-sm",children:[l.jsxs("span",{className:"text-sm font-medium text-[#0F172A]",children:[n?"▼":"▶"," View Product Details"]}),l.jsxs("span",{className:"text-xs text-[#64748B]",children:[w," product",w!==1?"s":""]})]}),n&&l.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:f.map(x=>{if(x.products.length===0)return null;const A=tn[x.tierName];return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2 pb-1 border-b border-[#E2E8F0]",children:[l.jsx("span",{className:"text-lg",children:A==null?void 0:A.emoji}),l.jsx("span",{className:"font-semibold text-sm",style:{color:A==null?void 0:A.textColor},children:x.displayName}),l.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",x.products.length," parts)"]})]}),l.jsx("div",{className:"space-y-2",children:x.products.map((T,R)=>{var j;const E=(j=t.carfixValueProducts)==null?void 0:j.includes(T.sku),O=T.unitPrice??T.price;return l.jsxs("div",{className:"flex items-center gap-3 p-2.5 rounded-xl transition-all hover:bg-slate-50 cursor-pointer border border-[#E2E8F0]",onClick:()=>s==null?void 0:s(T.sku),children:[l.jsx("div",{className:"flex-shrink-0 rounded-lg bg-white overflow-hidden border border-[#E2E8F0]",style:{width:"56px",height:"56px",minWidth:"56px",maxWidth:"56px"},children:l.jsx("img",{src:T.productImageUrl||Cr.productImage(T.sku),alt:T.name,className:"object-contain",style:{width:"100%",height:"100%",maxWidth:"56px",maxHeight:"56px",padding:"6px"},onError:C=>{C.target.src="/placeholder.svg"}})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[l.jsx("span",{className:"text-xs font-semibold text-[#0F172A]",children:T.brandFullName||T.brand}),E&&l.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"rgba(0, 82, 204, 0.1)",color:"#0052CC"},children:"CFX VALUE"}),T.isMultiQty&&T.perCarQty>1&&l.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",T.perCarQty]}),T.isRotor&&l.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#EFF6FF",color:"#1D4ED8"},children:"Pair"})]}),l.jsx("p",{className:"text-xs text-[#64748B] line-clamp-1",children:T.name})]}),l.jsxs("div",{className:"text-right flex-shrink-0",children:[l.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:lt(T.displayPrice)}),T.isMultiQty&&T.perCarQty>1&&l.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[T.perCarQty,"× ",lt(O)," each"]}),T.isRotor&&!T.isMultiQty&&l.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[lt(O)," each"]})]})]},`${T.sku}-${R}`)})})]},x.tierName)})})]}),t.bundle_discount_percentage&&t.bundle_discount_percentage>0&&l.jsx("div",{className:"px-4 pb-4",children:l.jsx("div",{className:"rounded-xl p-3 text-center",style:{background:"rgba(34,197,94,0.1)",border:"1px solid rgba(34,197,94,0.2)"},children:l.jsxs("span",{className:"text-sm font-semibold text-[#22C55E]",children:["Bundle saves you ",t.bundle_discount_percentage,"%"]})})})]})]})},vo=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:p,chatEndRef:f,isMuted:y,onToggleMute:b,isSpeaking:m,products:k,servicePackages:w,highlightedPartType:S,highlightedProduct:x,scrollToCategory:A,onScrollToCategoryComplete:T,onProductClick:R,onPackageSelect:E,isResearching:O,onAddToCart:j,onNavigateToProductPage:C,onQuickReply:L,onInterrupt:P,vehicle:F,onChangeVehicle:B,pendingVariants:N,pendingVariantMake:H,pendingVariantModel:Z,onVariantSelect:W,bobOffset:z=0,bobScale:fe=100})=>{const re=g.useRef(null),se=Bd(re),[Ee,te]=g.useState("center"),[ge,je]=g.useState("hidden"),[U,$e]=g.useState("products"),[Ve,tt]=g.useState(null),[_e,De]=g.useState(null),ct=k.length>0||w.length>0,rt=((N==null?void 0:N.length)??0)>0,Be=ct||rt,st=(U==="productDetail"?70:Ee==="center"&&!Be?140:98)*fe/100;g.useEffect(()=>{if(O&&ge!=="loading"&&ge!=="visible")je("loading"),Ee==="center"&&te("partial-left");else if(Be&&ge!=="visible")if(Ee==="center"){te("partial-left"),je("transitioning");const me=setTimeout(()=>{je("visible")},400);return()=>clearTimeout(me)}else je("visible");else!Be&&!O&&ge!=="hidden"&&(je("hidden"),te("center"))},[Be,O,ge,Ee]);const qe=me=>{if(C){C(me),R==null||R(me);return}tt(me),$e("productDetail"),R==null||R(me)},V=()=>{tt(null),De(null),$e("products")},ie=me=>{console.log("[ContainedMobileBobLayout] Package selected:",me.title),De(me),$e("packageDetail"),E==null||E(me)},ke=ge!=="hidden"&&U==="products",Q=ge!=="hidden";return l.jsxs("div",{ref:re,className:"absolute inset-0",style:{height:se?`${se}px`:"100%",overflow:"clip",isolation:"isolate",willChange:"height",WebkitUserSelect:"none",userSelect:"none",WebkitTouchCallout:"none"},onContextMenu:me=>me.preventDefault(),children:[r&&l.jsx("div",{className:"absolute inset-0 z-0 transition-all duration-500 ease-out",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:Q?"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)":"none",transform:Q?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}}),l.jsx(cn,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:st,position:Ee,verticalOffset:z}),l.jsx(dn,{products:k,servicePackages:w,highlightedPartType:S,highlightedProduct:x,scrollToCategory:A,onScrollToCategoryComplete:T,onProductClick:qe,onPackageSelect:ie,isResearching:O,visible:ke,counterHeightPercent:n,hasVehicle:!!F,onAddToCart:j,vehicleMakeModel:F?`${F.make||""} ${F.model||""}`.trim():void 0,pendingVariants:N,pendingVariantMake:H,pendingVariantModel:Z,onVariantSelect:W}),U==="productDetail"&&Ve&&l.jsx(Ld,{product:Ve,onBack:V,onAddToCart:j,onNavigateToProductPage:C}),U==="packageDetail"&&_e&&l.jsx(yo,{package:_e,onBack:V,onAddToCart:me=>{me.forEach(ye=>{var Qe;j==null||j({id:ye.sku||((Qe=ye.partslotId)==null?void 0:Qe.toString())||"unknown",name:ye.name||ye.partslotName||"Unknown Part",brand:ye.brand,price:ye.displayPrice,sku:ye.sku,partNumber:ye.partNumber,image_url:ye.productImageUrl,partslotDescription:ye.partslotName})})},onNavigateToProductPage:me=>{const ye=k.find(Qe=>Qe.sku===me);ye&&C&&C(ye)}}),U==="products"&&l.jsx(mo,{messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:p,chatEndRef:f,isMuted:y,onToggleMute:b,isSpeaking:m,onQuickReply:L,onInterrupt:P,counterHeightPercent:n})]})},oi=({variant:t="inline",initialState:e="idle",showChat:r=!0,className:s="",backdropUrl:n,counterOverlayUrl:i,counterHeightPercent:a,defaultBobImage:o,verticalOffset:c=0,scale:u=100,sessionToken:d,embedded:h=!1,initialVehicle:p})=>{var st,qe;const{callbacks:f}=Jt(),[y,b]=g.useState(!1),{animationState:m,setAnimationState:k,getCurrentImage:w,getCurrentOffset:S,getCurrentScale:x,availableStates:A}=Qa({isSpeaking:y}),{activeBackdrop:T}=Ya(),[R,E]=g.useState([]),[O,j]=g.useState([]),[C,L]=g.useState(null),[P,F]=g.useState(null),[B,N]=g.useState(!1),[H,Z]=g.useState(null),W=g.useRef(new Map);g.useEffect(()=>{const V=new Map;for(const[ie,ke]of W.current)ke==="package"&&V.set(ie,"package");R.forEach(ie=>{const ke=ie.partslotDescription||"Other Parts";V.set(ke,"partslot")}),W.current=V},[R]),g.useEffect(()=>{if(O.length>0){const V=new Map(W.current);O.forEach(ie=>{ie.title&&V.set(ie.title,"package")}),W.current=V}},[O]);const[z,fe]=g.useState([]),[re,se]=g.useState(""),[Ee,te]=g.useState(""),ge=g.useRef(null),je=g.useRef(null);g.useEffect(()=>{ge.current=V=>{if(N(!1),!V||V.length===0){console.log("[Bob] Clearing products (empty array received)"),E([]);return}const ie=V[0];console.log("[Bob] First part raw keys:",Object.keys(ie));const ke=V.map((Q,me)=>{const ye=Q.Brand||Q.brand||"";return{id:Q.SKU||Q.sku||`part-${me}`,name:Q["Part Product Type"]||Q.partslot_description||Q.name||"Unknown Part",brand:ye,price:Q["Metro Retail Price"]||Q.price||0,sku:Q.SKU||Q.sku,partNumber:Q["Part Number"]||Q.part_number||null,partslotDescription:Q["Part Product Type"]||Q.partslot_description||Q.partslotDescription||Q.part_type||Q.category||"General Parts",image_url:Q.image_url||(Q.SKU||Q.sku?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${Q.SKU||Q.sku}.jpg`:void 0),webDescription:Q["Web Part Description"]||Q.web_description||null,brandDescription:Q["Brand Description"]||Q.brand_description||null,perCarQty:Q["Per Car Qty"]||Q.per_car_qty||1,volume:Q.volume||null,viscosity:Q.viscosity||null,brandImageUrl:ye?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${ye.replace(/\s+/g,"")}.jpg`:void 0}});E(Q=>{var Dt;const me=new Set(Q.map(Ie=>Ie.sku).filter(Boolean)),ye=new Set(Q.map(Ie=>Ie.partslotDescription||"Other Parts")),Qe=new Set,Ue=ke.filter(Ie=>!Ie.sku||Qe.has(Ie.sku)||me.has(Ie.sku)?!1:(Qe.add(Ie.sku),!0));if(console.log("[Bob] Products mapped:",ke.length,"-> new unique:",Ue.length,"-> existing:",Q.length),Ue.length>0&&Q.length>0){const Ie=(Dt=Ue.find(Is=>!ye.has(Is.partslotDescription||"Other Parts")))==null?void 0:Dt.partslotDescription;Ie&&setTimeout(()=>Z(Ie),100)}return[...Q,...Ue]})},je.current=V=>{if(!V||V.length===0){console.log("[Bob] Clearing service packages (empty array received)"),j([]);return}console.log("[Bob] Service packages received via stable ref:",V.length),j(V)}},[]);const U=Ga({setAnimationState:k,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{k(A.find(V=>V.includes("idle"))||"idle")},onResearchStart:()=>{},onPartsResearchStart:()=>{N(!0)},onVariantSelectionRequired:(V,ie,ke)=>{N(!1),fe(V),se(ie),te(ke)},onHighlightPart:V=>{L(V),setTimeout(()=>L(null),8e3)},onHighlightProduct:V=>{F(V),setTimeout(()=>F(null),8e3)},onAutoFetchComplete:()=>{N(!1)},shelfCategoriesRef:W,initialVehicle:p});g.useEffect(()=>{U.identifiedVehicle&&(fe([]),se(""),te(""))},[(st=U.identifiedVehicle)==null?void 0:st.vehicle_id,(qe=U.identifiedVehicle)==null?void 0:qe.id]);const $e=V=>{U.sendDirectMessage(`Option ${V.optionNumber}`)};g.useEffect(()=>{b(U.isSpeaking)},[U.isSpeaking]);const Ve=g.useRef(!1);g.useEffect(()=>{var ie,ke;if(Ve.current||!((ie=U.identifiedVehicle)!=null&&ie.vehicle_id)&&!((ke=U.identifiedVehicle)!=null&&ke.id)||R.length>0||O.length>0)return;const V=setTimeout(()=>{R.length===0&&O.length===0&&(Ve.current=!0,console.log("[Bob] Session restore: vehicle present but shelf empty — re-fetching parts"),U.refetchPartsForVehicle())},1500);return()=>clearTimeout(V)},[U.identifiedVehicle]),g.useEffect(()=>{const V=f.onPartsFound,ie=f.onServicePackagesFound;return f.onPartsFound=ke=>{var Q;(Q=ge.current)==null||Q.call(ge,ke),V==null||V(ke)},f.onServicePackagesFound=ke=>{var Q;(Q=je.current)==null||Q.call(je,ke),ie==null||ie(ke)},()=>{f.onPartsFound=V,f.onServicePackagesFound=ie}},[f]);const tt=n||(T==null?void 0:T.image_url),_e=i||(T==null?void 0:T.counter_overlay_url)||void 0,De=a||(T==null?void 0:T.counter_height_percent)||12,ct=w()||o||"",rt=S(),Be=x(),gt=g.useCallback(V=>{var Q,me,ye,Qe;const ie=Array.isArray(V)?V:[V],ke=((me=(Q=U.identifiedVehicle)==null?void 0:Q.vehicle_id)==null?void 0:me.toString())||((Qe=(ye=U.identifiedVehicle)==null?void 0:ye.id)==null?void 0:Qe.toString());ie.forEach(Ue=>{var Ie;const Dt={product_id:Ue.id||Ue.sku||"",product_name:Ue.name,quantity:Ue.quantity||1,unit_price:Ue.price,sku:Ue.sku,brand:Ue.brand,image_url:Ue.image_url,vehicle_id:ke,...Ue._bundleMeta||{}};(Ie=f.onAddToCart)==null||Ie.call(f,Dt)})},[U.identifiedVehicle,f]);if(t==="mobile"||t==="fullscreen")return l.jsx(bo,{currentImage:ct,animationState:m,backdropUrl:tt,counterOverlayUrl:_e,counterHeightPercent:De,bobOffset:rt,bobScale:Be,embedded:h,messages:U.messages,input:U.input,setInput:U.setInput,isLoading:U.isLoading,onSend:U.handleSend,onKeyPress:U.handleKeyPress,onInputFocus:U.handleInputFocus,onInputBlur:U.handleInputBlur,chatEndRef:U.chatEndRef,isMuted:U.isMuted,onToggleMute:U.toggleMute,isSpeaking:U.isSpeaking,products:R,servicePackages:O,highlightedPartType:C,highlightedProduct:P,scrollToCategory:H,onScrollToCategoryComplete:()=>Z(null),onAddToCart:gt,onNavigateToProductPage:V=>{var ie;return(ie=f.onNavigateToProductPage)==null?void 0:ie.call(f,V)},onQuickReply:V=>{var ie;return(ie=f.onNavigateToProductPage)==null?void 0:ie.call(f,{url:V})},onPackageSelect:V=>console.log("[BobWidget] Package selected:",V),isResearching:B,vehicle:U.identifiedVehicle,pendingVariants:z,pendingVariantMake:re,pendingVariantModel:Ee,onVariantSelect:$e,onInterrupt:U.stopAllAudio});if(t==="inline"&&r)return l.jsx("div",{className:`relative w-full h-full ${s}`,children:l.jsx(vo,{currentImage:ct,animationState:m,backdropUrl:tt,counterOverlayUrl:_e,counterHeightPercent:De,bobOffset:rt,bobScale:Be,messages:U.messages,input:U.input,setInput:U.setInput,isLoading:U.isLoading,onSend:U.handleSend,onKeyPress:U.handleKeyPress,onInputFocus:U.handleInputFocus,onInputBlur:U.handleInputBlur,chatEndRef:U.chatEndRef,isMuted:U.isMuted,onToggleMute:U.toggleMute,isSpeaking:U.isSpeaking,products:R,servicePackages:O,highlightedPartType:C,highlightedProduct:P,scrollToCategory:H,onScrollToCategoryComplete:()=>Z(null),onAddToCart:gt,onNavigateToProductPage:V=>{var ie;return(ie=f.onNavigateToProductPage)==null?void 0:ie.call(f,V)},onQuickReply:V=>{var ie;return(ie=f.onNavigateToProductPage)==null?void 0:ie.call(f,{url:V})},onPackageSelect:V=>console.log("[BobWidget] Package selected:",V),isResearching:B,vehicle:U.identifiedVehicle,pendingVariants:z,pendingVariantMake:re,pendingVariantModel:Ee,onVariantSelect:$e,onInterrupt:U.stopAllAudio})});const ur={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return l.jsxs("div",{className:`${ur[t]||""} ${s}`,children:[ct&&l.jsx(Xa,{currentImage:ct,animationState:m,backdropUrl:tt,counterOverlayUrl:_e,counterHeightPercent:De,verticalOffset:rt,scale:Be}),r&&l.jsx(so,{messages:U.messages,input:U.input,setInput:U.setInput,isLoading:U.isLoading,onSend:U.handleSend,onKeyPress:U.handleKeyPress,onInputFocus:U.handleInputFocus,onInputBlur:U.handleInputBlur,chatEndRef:U.chatEndRef,isMuted:U.isMuted,onToggleMute:U.toggleMute,isSpeaking:U.isSpeaking})]})},wo=(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(o=>o.stop()),r("granted")}).catch(()=>r("denied"))),i.addEventListener("change",()=>{r(i.state)}))}).catch(()=>{n()}):n();function n(){var i;if(!s.current){if(!((i=navigator.mediaDevices)!=null&&i.getUserMedia)){r("unsupported");return}s.current=!0,navigator.mediaDevices.getUserMedia({audio:!0}).then(a=>{a.getTracks().forEach(o=>o.stop()),r("granted")}).catch(()=>r("denied"))}}},[t]),{micPermission:e}},$d=({bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,variant:n="mobile",initialState:i,showChat:a,className:o,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:p,scale:f,ga4Config:y,analyticsEnabled:b=!0,bottomOffset:m=0,zIndexBase:k=50,embedded:w=!1})=>{const{micPermission:S}=wo(!0),x=g.useRef(null);return g.useEffect(()=>Ha(x.current),[]),g.useEffect(()=>{console.log("[BobWidget] Initialized",{version:Vt,variant:n,bottomOffset:m,zIndexBase:k,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:b,micPermission:S})},[n,m,k,t.supabaseUrl,e.baseUrl,b,S]),l.jsx("div",{ref:x,className:"bob-widget-root",style:{width:"100%",height:"100%"},children:l.jsx(si,{bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,ga4Config:y,analyticsEnabled:b,bottomOffset:m,zIndexBase:k,children:l.jsx(oi,{variant:n,initialState:i,showChat:a,className:o,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:p,scale:f,embedded:w})})})};function Dd(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function Ud(){const t=[];if(typeof window>"u")return t;const e=document.querySelector(".bob-widget-root");if(!e)return t.push("bob-widget-root not found in DOM"),t;const r=window.getComputedStyle(e),s=e.parentElement;return s&&window.getComputedStyle(s).overflow==="hidden"&&t.push("Parent has overflow:hidden - may clip Bob"),r.transform!=="none"&&r.transform!=="matrix(1, 0, 0, 1, 0, 0)"&&t.push(`Unexpected transform on root: ${r.transform}`),r.isolation!=="isolate"&&t.push("Isolation not properly set"),t}const xo=({partnerConfig:t,sessionToken:e})=>{const[r,s]=g.useState(null),[n,i]=g.useState([]),[a,o]=g.useState(!1);if(g.useEffect(()=>{const u=()=>{var p;const d=window.innerWidth,h=window.innerHeight;s({viewport:{width:d,height:h,deviceType:Dd(d)},origin:window.location.origin,originAllowed:((p=t==null?void 0:t.allowed_origins)==null?void 0:p.some(f=>f===window.location.origin||f.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),i(Ud())};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[t]),!r)return null;const c=({ok:u,label:d})=>l.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,background:u?"rgba(34, 197, 94, 0.2)":"rgba(239, 68, 68, 0.2)",color:u?"#22c55e":"#ef4444"},children:[u?"✓":"✗"," ",d]});return l.jsxs("div",{style:{position:"fixed",top:"8px",right:"8px",zIndex:99999,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace',fontSize:"11px",lineHeight:1.4},children:[l.jsx("button",{onClick:()=>o(!a),style:{position:"absolute",top:0,right:0,width:"24px",height:"24px",background:"rgba(0, 0, 0, 0.8)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:a?"🔍":"✕"}),!a&&l.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"8px",padding:"12px",color:"#fff",maxWidth:"320px",backdropFilter:"blur(8px)"},children:[l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"12px",paddingBottom:"8px",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[l.jsx("span",{style:{fontSize:"14px"},children:"🔧"}),l.jsxs("span",{style:{fontWeight:600},children:["Bob Debug v",Vt]})]}),l.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginBottom:"12px"},children:[l.jsx(c,{ok:!!t,label:`Partner: ${(t==null?void 0:t.partner_code)||"none"}`}),l.jsx(c,{ok:!!e,label:e?"Session":"No Session"}),l.jsx(c,{ok:r.originAllowed,label:"Origin"})]}),l.jsxs("div",{style:{display:"grid",gap:"6px"},children:[l.jsx(Lr,{label:"Viewport",value:`${r.viewport.width}×${r.viewport.height} (${r.viewport.deviceType})`}),l.jsx(Lr,{label:"Origin",value:r.origin}),l.jsx(Lr,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),l.jsx(Lr,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),l.jsx(Lr,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),l.jsx(Lr,{label:"Overlay",value:`${(((t==null?void 0:t.backdrop_overlay_opacity)??.15)*100).toFixed(0)}%`})]}),(t==null?void 0:t.feature_flags)&&l.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[l.jsx("div",{style:{color:"rgba(255,255,255,0.5)",marginBottom:"4px"},children:"Features:"}),l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Object.entries(t.feature_flags).map(([u,d])=>l.jsx(c,{ok:!!d,label:u.replace(/([A-Z])/g," $1").trim()},u))})]}),n.length>0&&l.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[l.jsx("div",{style:{color:"#ef4444",marginBottom:"4px"},children:"⚠️ CSS Conflicts:"}),n.map((u,d)=>l.jsxs("div",{style:{color:"#fca5a5",fontSize:"10px"},children:["• ",u]},d))]}),l.jsx("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.4)",fontSize:"10px"},children:r.timestamp})]})]})},Lr=({label:t,value:e})=>l.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px"},children:[l.jsxs("span",{style:{color:"rgba(255,255,255,0.5)"},children:[t,":"]}),l.jsx("span",{style:{color:"#fff",textAlign:"right",wordBreak:"break-all"},children:e})]}),Zi="https://gjoguxzstsihhxvdgpto.supabase.co",ea="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function Md(t,e){return t.some(r=>{if(r.includes("*")){const s=r.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}return r===e})}function _o(t){const[e,r]=g.useState(null),[s,n]=g.useState(!0),[i,a]=g.useState(null),[o,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 p=Fn(Zi,ea);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:f,error:y}=await p.from("bob_partners").select("*").eq("partner_code",t).eq("is_active",!0).maybeSingle();if(y)throw new Error(`Failed to load partner config: ${y.message}`);if(!f)throw new Error(`Partner "${t}" not found or inactive`);const b=f,m=typeof window<"u"?window.location.origin:"",k=Md(b.allowed_origins||[],m);!k&&m&&(console.warn(`[BobWidget] Origin "${m}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",b.allowed_origins));const w=Fn(b.bob_supabase_url||Zi,b.bob_supabase_key||ea,{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:k}),r(b),c(k),d(w)}catch(p){const f=p instanceof Error?p:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",f),a(f)}finally{n(!1)}},[t]);return g.useEffect(()=>{h()},[h]),{config:e,isLoading:s,error:i,isOriginAllowed:o,supabaseClient:u,reload:h}}function ko(t,e,r){return t!=null&&t.feature_flags?t.feature_flags[e]??r:r}const Wd=()=>l.jsxs("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #0a1628 0%, #0f2137 100%)"},children:[l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[l.jsx("div",{style:{width:"48px",height:"48px",border:"4px solid rgba(0, 102, 204, 0.3)",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"}}),l.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"14px"},children:"Loading Bob..."})]}),l.jsx("style",{children:`
|
|
77
78
|
@keyframes spin {
|
|
78
79
|
to { transform: rotate(360deg); }
|
|
79
80
|
}
|
|
80
|
-
`})]}),
|
|
81
|
+
`})]}),qd=({error:t,partner:e})=>l.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #1a0a0a 0%, #2a1515 100%)",padding:"24px"},children:l.jsxs("div",{style:{maxWidth:"400px",textAlign:"center",color:"white"},children:[l.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"⚠️"}),l.jsx("h3",{style:{fontSize:"20px",fontWeight:600,marginBottom:"8px"},children:"Bob Widget Error"}),l.jsx("p",{style:{fontSize:"14px",color:"rgba(255,255,255,0.7)",marginBottom:"16px"},children:t.message}),l.jsxs("code",{style:{display:"block",fontSize:"12px",background:"rgba(255,0,0,0.1)",padding:"12px",borderRadius:"8px",color:"#ff6b6b"},children:["Partner: ",e,l.jsx("br",{}),"Origin: ",typeof window<"u"?window.location.origin:"unknown"]})]})}),zd=g.forwardRef(({partner:t,sessionToken:e,bottomOffset:r,zIndexBase:s,backdropBlurIntensity:n,backdropOverlayOpacity:i,onAddToCart:a,onNavigate:o,onCheckout:c,onError:u,debug:d=!1,className:h="",initialVehicle:p},f)=>{const y=g.useRef(null),b=g.useRef(null);g.useImperativeHandle(f,()=>({stopSpeech:()=>{var O;return(O=y.current)==null?void 0:O.call(y)},interrupt:()=>{var O;return(O=y.current)==null?void 0:O.call(y)}}));const{config:m,isLoading:k,error:w,supabaseClient:S}=_o(t);g.useEffect(()=>{console.log("[BobStandalone] Initialized",{version:Vt,partner:t,sessionToken:e?"present":"none",debug:d})},[t,e,d]),g.useEffect(()=>{if(!(k||!m||!S))return Ha(b.current)},[k,m==null?void 0:m.id,S]);const x=g.useMemo(()=>({onAddToCart:a?O=>a(O):void 0,onCheckoutRequested:c,onError:u,onNavigateToProductPage:o?O=>{const j=O;j!=null&&j.url?o(j.url):j!=null&&j.sku&&o(`/product/${j.sku}`)}:void 0,onStopSpeechReady:O=>{y.current=O}}),[a,o,c,u]),A=g.useMemo(()=>({}),[]);if(k)return l.jsx(Wd,{});if(w||!m||!S){const O=w||new Error("Failed to initialize Bob");return u==null||u(O),l.jsx(qd,{error:O,partner:t})}const T=r??m.default_bottom_offset,R=s??m.default_z_index_base,E=d||ko(m,"showDebugOverlay",!1);return l.jsx("div",{ref:b,className:`bob-widget-root ${h}`,style:{width:"100%",height:"100%","--bob-blur-intensity":`${n??m.backdrop_blur_intensity}px`,"--bob-overlay-opacity":i??m.backdrop_overlay_opacity,"--bob-z-base":R},children:l.jsxs(si,{bobConfig:{supabaseUrl:m.bob_supabase_url,supabaseKey:m.bob_supabase_key},hostApiConfig:{baseUrl:m.api_base_url,apiKey:"",partnerCode:m.partner_code},hostContext:A,callbacks:x,bottomOffset:T,zIndexBase:R,children:[l.jsx(oi,{variant:"inline",sessionToken:e,initialVehicle:p}),E&&l.jsx(xo,{partnerConfig:m,sessionToken:e})]})})}),Hd=({children:t,isSpeaking:e=!1,hasProducts:r=!1,onVisibilityChange:s,onPositionChange:n,currentPosition:i="center"})=>{const[a,o]=g.useState(!1),[c,u]=g.useState(0),d=g.useRef(null),h=g.useRef(0),p=g.useRef(0),f=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(x=>{h.current=x.touches[0].clientX,p.current=x.touches[0].clientY,f.current=!1,o(!0)},[]),m=g.useCallback(x=>{if(!a)return;const A=x.touches[0].clientX,T=x.touches[0].clientY,R=A-h.current,E=T-p.current;!f.current&&Math.abs(R)>10&&(f.current=Math.abs(R)>Math.abs(E)),f.current&&(x.preventDefault(),u(R))},[a]),k=g.useCallback(()=>{var E;if(!a)return;o(!1);const x=((E=d.current)==null?void 0:E.offsetWidth)||300,A=Math.abs(c)/x,T=c<0,R=c>0;T?i==="center"&&A>y?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&A>y&&(n==null||n("hidden"),s==null||s(!1)):R&&(i==="hidden"&&A>y?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&A>y&&!r&&(n==null||n("center"),s==null||s(!0))),u(0)},[a,c,i,r,n,s]),w=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 l.jsxs(l.Fragment,{children:[l.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:k,children:[t,i==="center"&&!a&&l.jsx("div",{className:"absolute left-2 top-1/2 -translate-y-1/2 pointer-events-none",style:{animation:"swipeHint 3s ease-in-out 2s 1",opacity:0},children:l.jsx("svg",{className:"w-6 h-6 text-white/50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})})]}),i==="hidden"&&l.jsx("button",{onClick:w,className:"fixed left-0 top-1/2 -translate-y-1/2 z-50 flex items-center justify-center",style:{writingMode:"vertical-rl",textOrientation:"mixed",background:"linear-gradient(180deg, #0066CC 0%, #004999 100%)",padding:"16px 8px",borderTopRightRadius:"12px",borderBottomRightRadius:"12px",boxShadow:"4px 0 12px rgba(0, 102, 204, 0.3)",animation:"slideInFromLeft 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",border:"none",cursor:"pointer"},children:l.jsx("span",{className:"text-white font-bold text-lg tracking-wider",children:"BOB"})}),l.jsx("style",{children:`
|
|
81
82
|
@keyframes slideInFromLeft {
|
|
82
83
|
from {
|
|
83
84
|
transform: translateX(-100%) translateY(-50%);
|
|
@@ -99,4 +100,4 @@ ${k}`}class Fe extends Error{constructor({message:e,code:r,cause:s,name:n}){var
|
|
|
99
100
|
transform: translateX(-10px) translateY(-50%);
|
|
100
101
|
}
|
|
101
102
|
}
|
|
102
|
-
`})]})},qt={primary:"216 100% 40%",secondary:"199 95% 74%",success:"33 100% 50%",background:"223 46% 13%",backgroundMode:"dark",sparkDealColor:"33 100% 50%",primaryHex:"#0066CC",secondaryHex:"#7DD3FC",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500"};function ns(t){const e=t.match(/(\d+\.?\d*)\s+(\d+\.?\d*)%?\s+(\d+\.?\d*)%?/);if(!e)return"#000000";const r=parseFloat(e[1]),s=parseFloat(e[2])/100,n=parseFloat(e[3])/100,i=(1-Math.abs(2*n-1))*s,a=i*(1-Math.abs(r/60%2-1)),o=n-i/2;let c=0,u=0,d=0;r<60?(c=i,u=a):r<120?(c=a,u=i):r<180?(u=i,d=a):r<240?(u=a,d=i):r<300?(c=a,d=i):(c=i,d=a);const h=g=>Math.round((g+o)*255).toString(16).padStart(2,"0");return`#${h(c)}${h(u)}${h(d)}`}function yo(){const t=Sr();return Os({queryKey:["bob-theme-settings"],queryFn:async()=>{var d,h,g,f,y,m,_,k,x,j,w;if(!t)return console.log("[useThemeSettings] No supabase client, using defaults"),qt;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),qt;if(!e||e.length===0)return qt;const s=new Map(e.map(A=>[A.setting_key,A])),n=((d=s.get("matrix_primary"))==null?void 0:d.color_value)||qt.primary,i=((h=s.get("matrix_secondary"))==null?void 0:h.color_value)||qt.secondary,a=((g=s.get("matrix_success"))==null?void 0:g.color_value)||qt.success,o=((f=s.get("matrix_background"))==null?void 0:f.color_value)||qt.background,c=((y=s.get("matrix_spark_deal_color"))==null?void 0:y.color_value)||qt.sparkDealColor,u=((m=s.get("matrix_background_mode"))==null?void 0:m.color_value)||"dark";return{primary:n,secondary:i,success:a,background:o,backgroundMode:u,sparkDealColor:c,primaryHex:((_=s.get("matrix_primary"))==null?void 0:_.hex_preview)||ns(n),secondaryHex:((k=s.get("matrix_secondary"))==null?void 0:k.hex_preview)||ns(i),successHex:((x=s.get("matrix_success"))==null?void 0:x.hex_preview)||ns(a),backgroundHex:((j=s.get("matrix_background"))==null?void 0:j.hex_preview)||ns(o),sparkDealHex:((w=s.get("matrix_spark_deal_color"))==null?void 0:w.hex_preview)||ns(c)}},staleTime:60*1e3,gcTime:5*60*1e3})}const bn={enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500,bobCommentary:!1};function Id(){const t=Sr();return Os({queryKey:["spark-deals-settings"],queryFn:async()=>{if(!t)return bn;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),bn;if(!e||e.length===0)return bn;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 vo(t=!0){const e=Sr();return Os({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 Bd(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 wo=({deals:t,currentDealIndex:e,onDealChange:r,onDealClick:s,scrollSpeed:n,theme:i})=>{const[a,o]=p.useState(!1),[c,u]=p.useState(100),d=t[e],h=i.sparkDealHex||"#FF9500",g=i.backgroundMode!=="light";p.useEffect(()=>{if(!d)return;o(!0),u(100);const m=setTimeout(()=>{u(0)},50),_=setTimeout(()=>{u(-100)},n-500),k=setTimeout(()=>{const x=(e+1)%t.length;r(x),o(!1)},n);return()=>{clearTimeout(m),clearTimeout(_),clearTimeout(k)}},[e,d,n,t.length,r]);const f=p.useCallback(()=>{d&&s(d)},[d,s]);if(!d)return null;const y=d.original_price?Math.round((1-d.price/d.original_price)*100):null;return l.jsxs("div",{className:"absolute bottom-20 left-0 right-0 z-20 overflow-hidden pointer-events-none",style:{height:"72px"},children:[l.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-auto",style:{transform:`translateX(${c}%)`,transition:"transform 0.5s ease-out"},children:l.jsxs("button",{onClick:f,className:"group flex items-center gap-4 px-6 py-3 rounded-xl shadow-2xl transition-all hover:scale-105 active:scale-95",style:{background:g?"linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(17, 24, 39, 0.9) 100%)":"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.98) 100%)",border:`2px solid ${h}`,boxShadow:`0 8px 32px -4px ${h}40, 0 4px 16px -2px rgba(0,0,0,0.2)`},children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0",style:{background:`${h}20`},children:l.jsx("svg",{className:"w-5 h-5",fill:h,viewBox:"0 0 24 24",children:l.jsx("path",{d:"M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z"})})}),l.jsxs("div",{className:"flex flex-col items-start min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xs font-bold uppercase tracking-wider",style:{color:h},children:"⚡ Spark Deal"}),y&&y>0&&l.jsxs("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:{background:h,color:g?"#000":"#fff"},children:[y,"% OFF"]})]}),l.jsxs("p",{className:"text-sm font-semibold truncate max-w-[200px]",style:{color:g?"#fff":"#111827"},children:[d.brand," ",d.product_name]})]}),l.jsxs("div",{className:"flex flex-col items-end shrink-0",children:[d.original_price&&d.original_price>d.price&&l.jsxs("span",{className:"text-xs line-through",style:{color:g?"#9ca3af":"#6b7280"},children:["$",d.original_price.toFixed(2)]}),l.jsxs("span",{className:"text-xl font-bold",style:{color:h},children:["$",d.price.toFixed(2)]})]}),l.jsx("svg",{className:"w-5 h-5 opacity-60 group-hover:opacity-100 group-hover:translate-x-1 transition-all",fill:"none",stroke:h,strokeWidth:2,viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.25 4.5l7.5 7.5-7.5 7.5"})})]})}),t.length>1&&l.jsx("div",{className:"absolute bottom-1 left-0 right-0 flex justify-center gap-1.5",children:t.map((m,_)=>l.jsx("div",{className:"w-1.5 h-1.5 rounded-full transition-all",style:{background:_===e?h:`${h}40`,transform:_===e?"scale(1.3)":"scale(1)"}},_))})]})},Yi=["*",":","=",">","<","+","-","|","•","○","●","◆","◇","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","#","@","$","%","&","~","^","/","\\","[","]","{","}"],Xi=["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"],Fd=({phase:t,message:e,onComplete:r,onSparkDealClick:s,subliminalBrands:n=[]})=>{const i=p.useRef(null),a=p.useRef(),o=p.useRef([]),c=p.useRef(0),[u,d]=p.useState(0),[h,g]=p.useState(!1),[f,y]=p.useState(0),{data:m}=yo(),{data:_}=Id(),{data:k}=vo(t!=="hidden"&&(_==null?void 0:_.enabled)),x=m||{primaryHex:"#0066CC",secondaryHex:"#004999",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500",backgroundMode:"dark"},j=_||{enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500},w=k&&j.inRain?[...Bd(k),...n]:n,A=.08,T=p.useCallback(()=>w.length>0&&Math.random()<A?{char:w[Math.floor(Math.random()*w.length)],isSubliminal:!0}:Math.random()<.15?{char:Xi[Math.floor(Math.random()*Xi.length)],isSubliminal:!1}:{char:Yi[Math.floor(Math.random()*Yi.length)],isSubliminal:!1},[w]),R=p.useCallback((C,D)=>C.isSubliminal?x.sparkDealHex:t==="success"?x.successHex:Math.sin(D*2+C.x*.01)*.5+.5>.5?x.primaryHex:x.secondaryHex,[t,x]),E=p.useCallback((C,D)=>{const N=[],F=Math.floor(C/25);for(let H=0;H<F;H++){const{char:U,isSubliminal:ie}=T();N.push({x:H*25+12,y:Math.random()*D,speed:1.5+Math.random()*3.5,char:U,isSubliminal:ie,opacity:.2+Math.random()*.6,size:ie?13:9+Math.random()*3,glowIntensity:ie?.6:0,changeCounter:Math.floor(Math.random()*30)})}o.current=N},[T]);p.useEffect(()=>{if(t==="hidden"){a.current&&cancelAnimationFrame(a.current);return}const C=i.current;if(!C)return;const D=C.getContext("2d");if(!D)return;const N=()=>{C.width=C.offsetWidth*window.devicePixelRatio,C.height=C.offsetHeight*window.devicePixelRatio,D.scale(window.devicePixelRatio,window.devicePixelRatio),E(C.offsetWidth,C.offsetHeight)};N(),c.current=Date.now();const F=()=>{const H=C.offsetWidth,U=C.offsetHeight,Y=(Date.now()-c.current)/1e3;if(D.clearRect(0,0,H,U),o.current.forEach(M=>{const G=R(M,Y);if(D.font=`bold ${M.size}px monospace`,D.fillStyle=G,D.globalAlpha=M.opacity,M.isSubliminal&&M.glowIntensity>0?(D.shadowColor=x.sparkDealHex,D.shadowBlur=8*M.glowIntensity):D.shadowBlur=0,D.fillText(M.char,M.x,M.y),M.y+=M.speed,M.changeCounter++,M.changeCounter>20+Math.random()*40){const{char:pe,isSubliminal:se}=T();M.char=pe,M.isSubliminal=se,M.size=se?13:9+Math.random()*3,M.glowIntensity=se?.6:0,M.changeCounter=0}if(M.y>U+20){const{char:pe,isSubliminal:se}=T();M.y=-20,M.char=pe,M.isSubliminal=se,M.speed=1.5+Math.random()*3.5,M.opacity=.2+Math.random()*.6,M.size=se?13:9+Math.random()*3,M.glowIntensity=se?.6:0,M.changeCounter=0}}),D.globalAlpha=1,D.shadowBlur=0,t==="success"){const M=Math.max(0,1-Y*2);M>0&&(D.fillStyle=`rgba(255, 149, 0, ${M*.3})`,D.fillRect(0,0,H,U)),Y>.5&&r&&r()}a.current=requestAnimationFrame(F)};return F(),window.addEventListener("resize",N),()=>{a.current&&cancelAnimationFrame(a.current),window.removeEventListener("resize",N)}},[t,x,T,R,E,r]),p.useEffect(()=>{if(t==="hidden"||!k||k.length===0||!j.bannerEnabled){g(!1);return}if(f>=j.maxPerSession)return;const C=setTimeout(()=>{g(!0)},j.delayMs);return()=>clearTimeout(C)},[t,k,j,f]);const O=p.useCallback(C=>{d(C),y(D=>D+1)},[]),S=p.useCallback(C=>{console.log("[MatrixLoader] Spark deal clicked:",C.product_name),s==null||s(C)},[s]);return t==="hidden"?null:l.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center overflow-hidden pointer-events-none",style:{background:"transparent"},children:[l.jsx("canvas",{ref:i,className:"absolute inset-0 w-full h-full",style:{opacity:.85}}),h&&k&&k.length>0&&l.jsx(wo,{deals:k.slice(0,j.maxPerSession),currentDealIndex:u,onDealChange:O,onDealClick:S,scrollSpeed:j.scrollSpeed,theme:x})]})},Ld=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,products:i,servicePackages:a,highlightedPartType:o,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,vehicle:g,onChangeVehicle:f,bobOffset:y=0,bobScale:m=100,bobHasArrived:_=!0,externalBobPosition:k,onBobPositionChange:x,pendingVariants:j,pendingVariantMake:w,pendingVariantModel:A,onVariantSelect:T})=>{const R=nn(),E=ri(),[O,S]=p.useState("center"),[C,D]=p.useState("hidden"),N=k??O,F=p.useCallback(ne=>{S(ne),x==null||x(ne)},[x]),H=i.length>0||a.length>0,U=((j==null?void 0:j.length)??0)>0,ie=H||U,G=(()=>{switch(R){case"desktop":return 80*E.uiScale;case"tablet":return 90*E.uiScale;case"mobile":return 140;default:return 140}})()*m/100;p.useEffect(()=>{if(h&&C!=="loading"&&C!=="visible"){if(U){N==="center"&&F("partial-left");return}D("loading"),N==="center"&&F("partial-left")}else if(ie&&C!=="visible")if(N==="center"){F("partial-left"),D("transitioning");const ne=setTimeout(()=>{D("visible")},400);return()=>clearTimeout(ne)}else D("visible");else!ie&&!h&&C!=="hidden"&&(U||(D("hidden"),F("center")))},[ie,U,h,C,N,F]);const pe=C!=="hidden"||U,se=pe&&ie;return l.jsxs("div",{className:"absolute inset-0 overflow-hidden",style:{width:"100%",height:"100%",touchAction:"manipulation",isolation:"isolate",WebkitUserSelect:"none",userSelect:"none",WebkitTouchCallout:"none"},children:[r&&l.jsxs(l.Fragment,{children:[l.jsx("img",{src:r,alt:"Shop backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-center transition-all duration-500",style:{pointerEvents:"none",filter:se?"blur(var(--bob-blur-intensity, 0px))":"none",transform:se?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1}),l.jsx("div",{className:"absolute inset-0 z-[1] transition-opacity duration-500 pointer-events-none",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))",opacity:se?1:0}})]}),l.jsx(an,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:G,position:N,verticalOffset:y,hasArrived:_}),l.jsx(on,{products:i,servicePackages:a,highlightedPartType:o,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,visible:pe,counterHeightPercent:n,hasVehicle:!!g,pendingVariants:j,pendingVariantMake:w,pendingVariantModel:A,onVariantSelect:T})]})},$d=6e4,Dd=({states:t,setAnimationState:e,manualMode:r})=>{const[s,n]=p.useState("page_load"),[i,a]=p.useState(!1),o=p.useRef(null),c=p.useCallback(S=>{const C=t.find(D=>D.chat_trigger===S&&D.is_active);return console.log(`[StateTransitions] Looking for trigger: "${S}" -> found:`,(C==null?void 0:C.state_key)||"none"),C},[t]),u=p.useCallback(()=>t.find(S=>S.chat_trigger==="processing_input"||S.state_key==="research"||S.state_key==="researching"||S.title.toLowerCase().includes("research")||S.title.toLowerCase().includes("thinking")),[t]),d=p.useCallback(()=>t.find(S=>S.chat_trigger==="streaming_response"||S.state_key==="talk"||S.state_key==="talking"||S.title.toLowerCase().includes("talk")),[t]),h=p.useCallback(()=>t.find(S=>S.chat_trigger==="awaiting_input"||S.state_key==="talk_pause"||S.state_key==="listening"||S.title.toLowerCase().includes("listen")||S.title.toLowerCase().includes("pause")),[t]),g=p.useCallback(()=>{const S=t.find(C=>C.chat_trigger==="response_complete"||C.state_key==="complete"||C.title.toLowerCase().includes("complete"));return S||t.find(C=>C.state_key==="idle"||C.title.toLowerCase().includes("idle"))},[t]),f=p.useCallback(()=>t.find(S=>S.chat_trigger==="idle"||S.state_key==="idle"||S.title.toLowerCase().includes("idle")),[t]),y=p.useCallback(S=>{const C=t.find(D=>D.state_key===S);return{speed:(C==null?void 0:C.animation_speed)||400,pauseDuration:(C==null?void 0:C.pause_duration)||0,loopCount:(C==null?void 0:C.loop_count)||0}},[t]),m=p.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),_=p.useCallback(()=>{m(),!r&&(o.current=setTimeout(()=>{const S=f();S&&(n("idle"),e(S.state_key))},$d))},[r,f,e,m]),k=p.useCallback(S=>{if(r)return;const C=c(S);C&&e(C.state_key)},[r,c,e]),x=p.useCallback(()=>{if(r)return;const S=h();S&&(n("awaiting_input"),e(S.state_key),_())},[r,h,e,_]),j=p.useCallback(()=>{i||r||(a(!0),n("page_load"),k("page_load"),setTimeout(()=>{x()},3e3))},[i,r,k,x]),w=p.useCallback(()=>{if(r)return;m(),n("processing_input");const S=u();console.log("[StateTransitions] User input - switching to RESEARCH:",S==null?void 0:S.state_key),S?e(S.state_key):k("processing_input")},[r,m,u,e,k]),A=p.useCallback(()=>{if(r)return;m(),n("streaming_response");const S=d();console.log("[StateTransitions] Speech started - switching to TALK:",S==null?void 0:S.state_key),S&&e(S.state_key)},[r,m,d,e]),T=p.useCallback(()=>{if(r)return;const S=g();console.log("[StateTransitions] Speech ended - switching to COMPLETE:",S==null?void 0:S.state_key),S&&e(S.state_key),setTimeout(()=>{r||x()},2e3)},[r,g,e,x]),R=p.useCallback(()=>{m(),n("streaming_response"),console.log("[StateTransitions] Stream started (API response)")},[m]),E=p.useCallback(()=>{n("response_complete"),console.log("[StateTransitions] Stream complete (API finished)");const S=g();S&&e(S.state_key),setTimeout(()=>{x()},2e3)},[g,e,x]),O=p.useCallback(()=>{if(r)return;n("showing_product"),console.log("[StateTransitions] Showing products");const S=t.find(C=>C.chat_trigger==="showing_product"||C.state_key==="showing_product");S&&e(S.state_key),setTimeout(()=>{x()},3e3)},[r,t,e,x]);return p.useEffect(()=>()=>m(),[m]),{chatStage:s,initialize:j,onUserInput:w,onSpeechStart:A,onSpeechEnd:T,onStreamStart:R,onStreamComplete:E,onShowingProduct:O,getStateSettings:y}},Ud=()=>{const t=Sr();return{checkHealth:async()=>{if(!t)return{healthy:!1,reason:"No Supabase client available - ensure BobProvider is configured",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};try{const{data:r,error:s}=await t.from("bob_looks").select("id, name, is_active").eq("is_active",!0).limit(1);if(s)return{healthy:!1,reason:`Database error fetching looks: ${s.message}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const n=r==null?void 0:r[0];if(!n)return{healthy:!1,reason:"No active look configured in bob_looks table",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const{data:i,error:a}=await t.from("animation_states").select("state_key").eq("is_active",!0).eq("look_id",n.id);if(a)return{healthy:!1,reason:`Database error fetching states: ${a.message}`,activeLookId:n.id,activeLookName:n.name,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const o=(i==null?void 0:i.map(y=>y.state_key))||[],u=["idle","talking","listening"].filter(y=>{const m=[y,y.replace("ing",""),y+"ing"];return!o.some(_=>m.includes(_))}),{data:d,error:h}=await t.from("bob_animations").select("id").eq("is_active",!0).eq("look_id",n.id),g=h?0:(d==null?void 0:d.length)||0,f=o.length>=4&&g>0&&u.length===0;return{healthy:f,reason:f?void 0:`Missing critical states: ${u.join(", ")}`,activeLookId:n.id,activeLookName:n.name,stateCount:o.length,states:o,missingCritical:u,frameCount:g}}catch(r){return{healthy:!1,reason:`Unexpected error: ${r instanceof Error?r.message:"Unknown"}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0}}}}};console.log(`[BobWidget] Package loaded - v${Ft}`);exports.BADGE_CONFIG=Ja;exports.BOB_VERSION=Ft;exports.Bob=ni;exports.BobCharacter=Ga;exports.BobDebugOverlay=go;exports.BobProvider=Zn;exports.BobStandalone=Pd;exports.BobSuggestions=ti;exports.BobWidget=jd;exports.CARFIX_COLORS=K;exports.ChatInterface=Za;exports.ContainedChatDrawer=uo;exports.ContainedMobileBobLayout=fo;exports.IMAGE_URLS=ks;exports.MatrixProductLoader=Fd;exports.MobileBobCharacter=an;exports.MobileBobLayout=co;exports.MobileBobLayoutCore=Ld;exports.MobileChatDrawer=lo;exports.MobileProductColumn=on;exports.ProductBadge=ls;exports.ProductTile=to;exports.QUALITY_TIER_CONFIG=Xs;exports.ServicePackageDetailView=ho;exports.SparkDealBanner=wo;exports.SwipeableBob=Nd;exports.TYPOGRAPHY=vt;exports.formatNZD=st;exports.getBobVersion=_o;exports.getDisplayPrice=Ya;exports.getFeatureFlag=bo;exports.isRotorProduct=Qa;exports.useBobAnalytics=$a;exports.useBobAnalyticsConfig=id;exports.useBobAnimation=Ka;exports.useBobAnimationData=za;exports.useBobBackdrop=Va;exports.useBobCallbacks=nd;exports.useBobChat=Ha;exports.useBobContext=$t;exports.useBobHealthCheck=Ud;exports.useBobLayoutConfig=ei;exports.useBobStateTransitions=Dd;exports.useBobSupabase=td;exports.useBobSupabaseSafe=Sr;exports.useHostApiConfig=sd;exports.useHostContext=rd;exports.useMicPermission=po;exports.usePartnerConfig=mo;exports.useReturningUser=qa;exports.useSparkDeals=vo;exports.useSpeechRecognition=si;exports.useSpeechSynthesis=Wa;exports.useThemeSettings=yo;
|
|
103
|
+
`})]})},Xt={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 os(t){const e=t.match(/(\d+\.?\d*)\s+(\d+\.?\d*)%?\s+(\d+\.?\d*)%?/);if(!e)return"#000000";const r=parseFloat(e[1]),s=parseFloat(e[2])/100,n=parseFloat(e[3])/100,i=(1-Math.abs(2*n-1))*s,a=i*(1-Math.abs(r/60%2-1)),o=n-i/2;let c=0,u=0,d=0;r<60?(c=i,u=a):r<120?(c=a,u=i):r<180?(u=i,d=a):r<240?(u=a,d=i):r<300?(c=a,d=i):(c=i,d=a);const h=p=>Math.round((p+o)*255).toString(16).padStart(2,"0");return`#${h(c)}${h(u)}${h(d)}`}function So(){const t=Ar();return Ps({queryKey:["bob-theme-settings"],queryFn:async()=>{var d,h,p,f,y,b,m,k,w,S,x;if(!t)return console.log("[useThemeSettings] No supabase client, using defaults"),Xt;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),Xt;if(!e||e.length===0)return Xt;const s=new Map(e.map(A=>[A.setting_key,A])),n=((d=s.get("matrix_primary"))==null?void 0:d.color_value)||Xt.primary,i=((h=s.get("matrix_secondary"))==null?void 0:h.color_value)||Xt.secondary,a=((p=s.get("matrix_success"))==null?void 0:p.color_value)||Xt.success,o=((f=s.get("matrix_background"))==null?void 0:f.color_value)||Xt.background,c=((y=s.get("matrix_spark_deal_color"))==null?void 0:y.color_value)||Xt.sparkDealColor,u=((b=s.get("matrix_background_mode"))==null?void 0:b.color_value)||"dark";return{primary:n,secondary:i,success:a,background:o,backgroundMode:u,sparkDealColor:c,primaryHex:((m=s.get("matrix_primary"))==null?void 0:m.hex_preview)||os(n),secondaryHex:((k=s.get("matrix_secondary"))==null?void 0:k.hex_preview)||os(i),successHex:((w=s.get("matrix_success"))==null?void 0:w.hex_preview)||os(a),backgroundHex:((S=s.get("matrix_background"))==null?void 0:S.hex_preview)||os(o),sparkDealHex:((x=s.get("matrix_spark_deal_color"))==null?void 0:x.hex_preview)||os(c)}},staleTime:60*1e3,gcTime:5*60*1e3})}const xn={enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500,bobCommentary:!1};function Kd(){const t=Ar();return Ps({queryKey:["spark-deals-settings"],queryFn:async()=>{if(!t)return xn;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),xn;if(!e||e.length===0)return xn;const s=new Map(e.map(n=>[n.setting_key,n.setting_value]));return{enabled:s.get("spark_deals_enabled")==="true",inRain:s.get("spark_deals_in_rain")==="true",rainFrequency:parseFloat(s.get("spark_deals_rain_frequency")||"0.15"),primingEnabled:s.get("spark_deals_priming_enabled")==="true",bannerEnabled:s.get("spark_deals_banner_enabled")==="true",delayMs:parseInt(s.get("spark_deals_delay_ms")||"2000",10),scrollSpeed:parseInt(s.get("spark_deals_scroll_speed")||"5000",10),maxPerSession:parseInt(s.get("spark_deals_max_per_session")||"3",10),minResearchTime:parseInt(s.get("spark_deals_min_research_time")||"1500",10),bobCommentary:s.get("spark_deals_bob_commentary")==="true"}},staleTime:60*1e3,gcTime:5*60*1e3})}function Eo(t=!0){const e=Ar();return Ps({queryKey:["spark-deals"],queryFn:async()=>{if(!e)return console.log("[useSparkDeals] No supabase client"),[];try{return console.error("[useSparkDeals] Missing VITE_SUPABASE_URL"),[]}catch(r){return console.error("[useSparkDeals] Error:",r),[]}},enabled:t,staleTime:5*60*1e3,gcTime:10*60*1e3})}function Vd(t){const e=[];return t.forEach(r=>{e.push(`$${r.price.toFixed(0)}`),r.brand&&e.push(r.brand.toUpperCase());const s=r.product_name.split(" ")[0];s&&s.length>2&&e.push(s.toUpperCase())}),e}const jo=({deals:t,currentDealIndex:e,onDealChange:r,onDealClick:s,scrollSpeed:n,theme:i})=>{const[a,o]=g.useState(!1),[c,u]=g.useState(100),d=t[e],h=i.sparkDealHex||"#FF9500",p=i.backgroundMode!=="light";g.useEffect(()=>{if(!d)return;o(!0),u(100);const b=setTimeout(()=>{u(0)},50),m=setTimeout(()=>{u(-100)},n-500),k=setTimeout(()=>{const w=(e+1)%t.length;r(w),o(!1)},n);return()=>{clearTimeout(b),clearTimeout(m),clearTimeout(k)}},[e,d,n,t.length,r]);const f=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 l.jsxs("div",{className:"absolute bottom-20 left-0 right-0 z-20 overflow-hidden pointer-events-none",style:{height:"72px"},children:[l.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-auto",style:{transform:`translateX(${c}%)`,transition:"transform 0.5s ease-out"},children:l.jsxs("button",{onClick:f,className:"group flex items-center gap-4 px-6 py-3 rounded-xl shadow-2xl transition-all hover:scale-105 active:scale-95",style:{background:p?"linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(17, 24, 39, 0.9) 100%)":"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.98) 100%)",border:`2px solid ${h}`,boxShadow:`0 8px 32px -4px ${h}40, 0 4px 16px -2px rgba(0,0,0,0.2)`},children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0",style:{background:`${h}20`},children:l.jsx("svg",{className:"w-5 h-5",fill:h,viewBox:"0 0 24 24",children:l.jsx("path",{d:"M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z"})})}),l.jsxs("div",{className:"flex flex-col items-start min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xs font-bold uppercase tracking-wider",style:{color:h},children:"⚡ Spark Deal"}),y&&y>0&&l.jsxs("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:{background:h,color:p?"#000":"#fff"},children:[y,"% OFF"]})]}),l.jsxs("p",{className:"text-sm font-semibold truncate max-w-[200px]",style:{color:p?"#fff":"#111827"},children:[d.brand," ",d.product_name]})]}),l.jsxs("div",{className:"flex flex-col items-end shrink-0",children:[d.original_price&&d.original_price>d.price&&l.jsxs("span",{className:"text-xs line-through",style:{color:p?"#9ca3af":"#6b7280"},children:["$",d.original_price.toFixed(2)]}),l.jsxs("span",{className:"text-xl font-bold",style:{color:h},children:["$",d.price.toFixed(2)]})]}),l.jsx("svg",{className:"w-5 h-5 opacity-60 group-hover:opacity-100 group-hover:translate-x-1 transition-all",fill:"none",stroke:h,strokeWidth:2,viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.25 4.5l7.5 7.5-7.5 7.5"})})]})}),t.length>1&&l.jsx("div",{className:"absolute bottom-1 left-0 right-0 flex justify-center gap-1.5",children:t.map((b,m)=>l.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))})]})},ta=["*",":","=",">","<","+","-","|","•","○","●","◆","◇","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","#","@","$","%","&","~","^","/","\\","[","]","{","}"],ra=["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"],Gd=({phase:t,message:e,onComplete:r,onSparkDealClick:s,subliminalBrands:n=[]})=>{const i=g.useRef(null),a=g.useRef(),o=g.useRef([]),c=g.useRef(0),[u,d]=g.useState(0),[h,p]=g.useState(!1),[f,y]=g.useState(0),{data:b}=So(),{data:m}=Kd(),{data:k}=Eo(t!=="hidden"&&(m==null?void 0:m.enabled)),w=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},x=k&&S.inRain?[...Vd(k),...n]:n,A=.08,T=g.useCallback(()=>x.length>0&&Math.random()<A?{char:x[Math.floor(Math.random()*x.length)],isSubliminal:!0}:Math.random()<.15?{char:ra[Math.floor(Math.random()*ra.length)],isSubliminal:!1}:{char:ta[Math.floor(Math.random()*ta.length)],isSubliminal:!1},[x]),R=g.useCallback((C,L)=>C.isSubliminal?w.sparkDealHex:t==="success"?w.successHex:Math.sin(L*2+C.x*.01)*.5+.5>.5?w.primaryHex:w.secondaryHex,[t,w]),E=g.useCallback((C,L)=>{const P=[],F=Math.floor(C/25);for(let B=0;B<F;B++){const{char:N,isSubliminal:H}=T();P.push({x:B*25+12,y:Math.random()*L,speed:1.5+Math.random()*3.5,char:N,isSubliminal:H,opacity:.2+Math.random()*.6,size:H?13:9+Math.random()*3,glowIntensity:H?.6:0,changeCounter:Math.floor(Math.random()*30)})}o.current=P},[T]);g.useEffect(()=>{if(t==="hidden"){a.current&&cancelAnimationFrame(a.current);return}const C=i.current;if(!C)return;const L=C.getContext("2d");if(!L)return;const P=()=>{C.width=C.offsetWidth*window.devicePixelRatio,C.height=C.offsetHeight*window.devicePixelRatio,L.scale(window.devicePixelRatio,window.devicePixelRatio),E(C.offsetWidth,C.offsetHeight)};P(),c.current=Date.now();const F=()=>{const B=C.offsetWidth,N=C.offsetHeight,Z=(Date.now()-c.current)/1e3;if(L.clearRect(0,0,B,N),o.current.forEach(W=>{const z=R(W,Z);if(L.font=`bold ${W.size}px monospace`,L.fillStyle=z,L.globalAlpha=W.opacity,W.isSubliminal&&W.glowIntensity>0?(L.shadowColor=w.sparkDealHex,L.shadowBlur=8*W.glowIntensity):L.shadowBlur=0,L.fillText(W.char,W.x,W.y),W.y+=W.speed,W.changeCounter++,W.changeCounter>20+Math.random()*40){const{char:fe,isSubliminal:re}=T();W.char=fe,W.isSubliminal=re,W.size=re?13:9+Math.random()*3,W.glowIntensity=re?.6:0,W.changeCounter=0}if(W.y>N+20){const{char:fe,isSubliminal:re}=T();W.y=-20,W.char=fe,W.isSubliminal=re,W.speed=1.5+Math.random()*3.5,W.opacity=.2+Math.random()*.6,W.size=re?13:9+Math.random()*3,W.glowIntensity=re?.6:0,W.changeCounter=0}}),L.globalAlpha=1,L.shadowBlur=0,t==="success"){const W=Math.max(0,1-Z*2);W>0&&(L.fillStyle=`rgba(255, 149, 0, ${W*.3})`,L.fillRect(0,0,B,N)),Z>.5&&r&&r()}a.current=requestAnimationFrame(F)};return F(),window.addEventListener("resize",P),()=>{a.current&&cancelAnimationFrame(a.current),window.removeEventListener("resize",P)}},[t,w,T,R,E,r]),g.useEffect(()=>{if(t==="hidden"||!k||k.length===0||!S.bannerEnabled){p(!1);return}if(f>=S.maxPerSession)return;const C=setTimeout(()=>{p(!0)},S.delayMs);return()=>clearTimeout(C)},[t,k,S,f]);const O=g.useCallback(C=>{d(C),y(L=>L+1)},[]),j=g.useCallback(C=>{console.log("[MatrixLoader] Spark deal clicked:",C.product_name),s==null||s(C)},[s]);return t==="hidden"?null:l.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center overflow-hidden pointer-events-none",style:{background:"transparent"},children:[l.jsx("canvas",{ref:i,className:"absolute inset-0 w-full h-full",style:{opacity:.85}}),h&&k&&k.length>0&&l.jsx(jo,{deals:k.slice(0,S.maxPerSession),currentDealIndex:u,onDealChange:O,onDealClick:j,scrollSpeed:S.scrollSpeed,theme:w})]})},Jd=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,products:i,servicePackages:a,highlightedPartType:o,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,vehicle:p,onChangeVehicle:f,bobOffset:y=0,bobScale:b=100,bobHasArrived:m=!0,externalBobPosition:k,onBobPositionChange:w,pendingVariants:S,pendingVariantMake:x,pendingVariantModel:A,onVariantSelect:T})=>{const R=ln(),E=no(),[O,j]=g.useState("center"),[C,L]=g.useState("hidden"),P=k??O,F=g.useCallback(se=>{j(se),w==null||w(se)},[w]),B=i.length>0||a.length>0,N=((S==null?void 0:S.length)??0)>0,H=B||N,z=(()=>{switch(R){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&&C!=="loading"&&C!=="visible"){if(N){P==="center"&&F("partial-left");return}L("loading"),P==="center"&&F("partial-left")}else if(H&&C!=="visible")if(P==="center"){F("partial-left"),L("transitioning");const se=setTimeout(()=>{L("visible")},400);return()=>clearTimeout(se)}else L("visible");else!H&&!h&&C!=="hidden"&&(N||(L("hidden"),F("center")))},[H,N,h,C,P,F]);const fe=C!=="hidden"||N,re=fe&&H;return l.jsxs("div",{className:"absolute inset-0 overflow-clip",style:{width:"100%",height:"100%",touchAction:"auto",isolation:"isolate",WebkitUserSelect:"none",userSelect:"none",WebkitTouchCallout:"none"},children:[r&&l.jsxs(l.Fragment,{children:[l.jsx("img",{src:r,alt:"Shop backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-center transition-all duration-500",style:{pointerEvents:"none",filter:re?"blur(var(--bob-blur-intensity, 0px))":"none",transform:re?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1}),l.jsx("div",{className:"absolute inset-0 z-[1] transition-opacity duration-500 pointer-events-none",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))",opacity:re?1:0}})]}),l.jsx(cn,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:z,position:P,verticalOffset:y,hasArrived:m}),l.jsx(dn,{products:i,servicePackages:a,highlightedPartType:o,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,visible:fe,counterHeightPercent:n,hasVehicle:!!p,pendingVariants:S,pendingVariantMake:x,pendingVariantModel:A,onVariantSelect:T})]})},Qd=6e4,Yd=({states:t,setAnimationState:e,manualMode:r})=>{const[s,n]=g.useState("page_load"),[i,a]=g.useState(!1),o=g.useRef(null),c=g.useCallback(j=>{const C=t.find(L=>L.chat_trigger===j&&L.is_active);return console.log(`[StateTransitions] Looking for trigger: "${j}" -> found:`,(C==null?void 0:C.state_key)||"none"),C},[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]),p=g.useCallback(()=>{const j=t.find(C=>C.chat_trigger==="response_complete"||C.state_key==="complete"||C.title.toLowerCase().includes("complete"));return j||t.find(C=>C.state_key==="idle"||C.title.toLowerCase().includes("idle"))},[t]),f=g.useCallback(()=>t.find(j=>j.chat_trigger==="idle"||j.state_key==="idle"||j.title.toLowerCase().includes("idle")),[t]),y=g.useCallback(j=>{const C=t.find(L=>L.state_key===j);return{speed:(C==null?void 0:C.animation_speed)||400,pauseDuration:(C==null?void 0:C.pause_duration)||0,loopCount:(C==null?void 0:C.loop_count)||0}},[t]),b=g.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),m=g.useCallback(()=>{b(),!r&&(o.current=setTimeout(()=>{const j=f();j&&(n("idle"),e(j.state_key))},Qd))},[r,f,e,b]),k=g.useCallback(j=>{if(r)return;const C=c(j);C&&e(C.state_key)},[r,c,e]),w=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"),k("page_load"),setTimeout(()=>{w()},3e3))},[i,r,k,w]),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):k("processing_input")},[r,b,u,e,k]),A=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]),T=g.useCallback(()=>{if(r)return;const j=p();console.log("[StateTransitions] Speech ended - switching to COMPLETE:",j==null?void 0:j.state_key),j&&e(j.state_key),setTimeout(()=>{r||w()},2e3)},[r,p,e,w]),R=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=p();j&&e(j.state_key),setTimeout(()=>{w()},2e3)},[p,e,w]),O=g.useCallback(()=>{if(r)return;n("showing_product"),console.log("[StateTransitions] Showing products");const j=t.find(C=>C.chat_trigger==="showing_product"||C.state_key==="showing_product");j&&e(j.state_key),setTimeout(()=>{w()},3e3)},[r,t,e,w]);return g.useEffect(()=>()=>b(),[b]),{chatStage:s,initialize:S,onUserInput:x,onSpeechStart:A,onSpeechEnd:T,onStreamStart:R,onStreamComplete:E,onShowingProduct:O,getStateSettings:y}},Xd=()=>{const t=Ar();return{checkHealth:async()=>{if(!t)return{healthy:!1,reason:"No Supabase client available - ensure BobProvider is configured",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};try{const{data:r,error:s}=await t.from("bob_looks").select("id, name, is_active").eq("is_active",!0).limit(1);if(s)return{healthy:!1,reason:`Database error fetching looks: ${s.message}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const n=r==null?void 0:r[0];if(!n)return{healthy:!1,reason:"No active look configured in bob_looks table",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const{data:i,error:a}=await t.from("animation_states").select("state_key").eq("is_active",!0).eq("look_id",n.id);if(a)return{healthy:!1,reason:`Database error fetching states: ${a.message}`,activeLookId:n.id,activeLookName:n.name,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const o=(i==null?void 0:i.map(y=>y.state_key))||[],u=["idle","talking","listening"].filter(y=>{const b=[y,y.replace("ing",""),y+"ing"];return!o.some(m=>b.includes(m))}),{data:d,error:h}=await t.from("bob_animations").select("id").eq("is_active",!0).eq("look_id",n.id),p=h?0:(d==null?void 0:d.length)||0,f=o.length>=4&&p>0&&u.length===0;return{healthy:f,reason:f?void 0:`Missing critical states: ${u.join(", ")}`,activeLookId:n.id,activeLookName:n.name,stateCount:o.length,states:o,missingCritical:u,frameCount:p}}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${Vt}`);exports.BADGE_CONFIG=Za;exports.BOB_VERSION=Vt;exports.Bob=oi;exports.BobCharacter=Xa;exports.BobDebugOverlay=xo;exports.BobProvider=si;exports.BobStandalone=zd;exports.BobSuggestions=ii;exports.BobWidget=$d;exports.CARFIX_COLORS=G;exports.ChatInterface=so;exports.ContainedChatDrawer=mo;exports.ContainedMobileBobLayout=vo;exports.IMAGE_URLS=Cr;exports.MatrixProductLoader=Gd;exports.MobileBobCharacter=cn;exports.MobileBobLayout=bo;exports.MobileBobLayoutCore=Jd;exports.MobileChatDrawer=go;exports.MobileProductColumn=dn;exports.ProductBadge=ds;exports.ProductTile=po;exports.QUALITY_TIER_CONFIG=tn;exports.ServicePackageDetailView=yo;exports.SparkDealBanner=jo;exports.SwipeableBob=Hd;exports.TYPOGRAPHY=Tt;exports.formatNZD=lt;exports.getBobVersion=Ao;exports.getDisplayPrice=to;exports.getFeatureFlag=ko;exports.isRotorProduct=eo;exports.useBobAnalytics=Wa;exports.useBobAnalyticsConfig=fd;exports.useBobAnimation=Qa;exports.useBobAnimationData=Ja;exports.useBobBackdrop=Ya;exports.useBobCallbacks=hd;exports.useBobChat=Ga;exports.useBobContext=Jt;exports.useBobHealthCheck=Xd;exports.useBobLayoutConfig=ni;exports.useBobStateTransitions=Yd;exports.useBobSupabase=cd;exports.useBobSupabaseSafe=Ar;exports.useHostApiConfig=dd;exports.useHostContext=ud;exports.useMicPermission=wo;exports.usePartnerConfig=_o;exports.useReturningUser=Va;exports.useSparkDeals=Eo;exports.useSpeechRecognition=ai;exports.useSpeechSynthesis=Ka;exports.useThemeSettings=So;
|