@1interface/chat-core 0.2.4 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{nanoid as e,formatProdErrorMessage as t,createSelector as n,createAction as r,createAsyncThunk as a,createSlice as s,prepareAutoBatched as o,isAnyOf as i,isFulfilled as c,isRejectedWithValue as u,combineReducers as d,isPlainObject as l,SHOULD_AUTOBATCH as p,isAllOf as f,isRejected as h,isPending as g,isAction as m,createNextState as y,isAsyncThunkAction as v,configureStore as _}from"@reduxjs/toolkit";import{useStore as b,useSelector as S,useDispatch as w,batch as T,shallowEqual as E}from"react-redux";import{useCallback as I,useDebugValue as A,useMemo as R,useState as k,useEffect as O,useRef as C,useLayoutEffect as N,createContext as P,useContext as x}from"react";import{getCustomHeaders as q,isDevMode as M,logger as D,showErrorToast as Q,getTokenRefreshHandler as F,clearSession as U,setSession as L,readAccessToken as j,API_ENDPOINTS as $,TIMING as z,sessionExpired as K,indicatorReducer as H,sessionReducer as G,sessionListenerMiddleware as B,setAccessTokenReader as V,setTokenExpiresAtReader as W,getPaymentId as J,isTokenAboutToExpire as X,readTokenExpiresAt as Z,generateUniqueId as Y,getApiUrl as ee,AUTH_PATHS as te,extractTokens as ne,createTokenRefresher as re,formatTimeRemaining as ae,getTimeUntilExpiry as se,isTokenExpired as oe,INDICATOR_TIMER_ACTIONS as ie,setLastResponseTime as ce,handleSharedEvent as ue,clearLastResponseTime as de,readDeviceToken as le,showSuccessToast as pe,eventEmitter as fe,STORAGE_KEYS as he,useStorage as ge,useBranding as me,hasWidgets as ye,getTimeUntilRefresh as ve,FEATURE_FLAGS as _e,getBaseUrl as be}from"@1interface/shared-core";import{fetchEventSource as Se}from"@microsoft/fetch-event-source";var we=Symbol.for("immer-nothing"),Te=Symbol.for("immer-draftable"),Ee=Symbol.for("immer-state"),Ie="production"!==process.env.NODE_ENV?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function Ae(e,...t){if("production"!==process.env.NODE_ENV){const n=Ie[e],r=We(n)?n.apply(null,t):n;throw new Error(`[Immer] ${r}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Re=Object,ke=Re.getPrototypeOf,Oe="constructor",Ce="prototype",Ne="configurable",Pe="enumerable",xe="writable",qe="value",Me=e=>!!e&&!!e[Ee];function De(e){return!!e&&(Ue(e)||He(e)||!!e[Te]||!!e[Oe]?.[Te]||Ge(e)||Be(e))}var Qe=Re[Ce][Oe].toString(),Fe=new WeakMap;function Ue(e){if(!e||!Ve(e))return!1;const t=ke(e);if(null===t||t===Re[Ce])return!0;const n=Re.hasOwnProperty.call(t,Oe)&&t[Oe];if(n===Object)return!0;if(!We(n))return!1;let r=Fe.get(n);return void 0===r&&(r=Function.toString.call(n),Fe.set(n,r)),r===Qe}function Le(e,t,n=!0){0===je(e)?(n?Reflect.ownKeys(e):Re.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function je(e){const t=e[Ee];return t?t.type_:He(e)?1:Ge(e)?2:Be(e)?3:0}var $e=(e,t,n=je(e))=>2===n?e.has(t):Re[Ce].hasOwnProperty.call(e,t),ze=(e,t,n=je(e))=>2===n?e.get(t):e[t],Ke=(e,t,n,r=je(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n},He=Array.isArray,Ge=e=>e instanceof Map,Be=e=>e instanceof Set,Ve=e=>"object"==typeof e,We=e=>"function"==typeof e,Je=e=>"boolean"==typeof e,Xe=e=>e.copy_||e.base_,Ze=e=>e.modified_?e.copy_:e.base_;function Ye(e,t){if(Ge(e))return new Map(e);if(Be(e))return new Set(e);if(He(e))return Array[Ce].slice.call(e);const n=Ue(e);if(!0===t||"class_only"===t&&!n){const t=Re.getOwnPropertyDescriptors(e);delete t[Ee];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const a=n[r],s=t[a];!1===s[xe]&&(s[xe]=!0,s[Ne]=!0),(s.get||s.set)&&(t[a]={[Ne]:!0,[xe]:!0,[Pe]:s[Pe],[qe]:e[a]})}return Re.create(ke(e),t)}{const t=ke(e);if(null!==t&&n)return{...e};const r=Re.create(t);return Re.assign(r,e)}}function et(e,t=!1){return nt(e)||Me(e)||!De(e)||(je(e)>1&&Re.defineProperties(e,{set:tt,add:tt,clear:tt,delete:tt}),Re.freeze(e),t&&Le(e,(e,t)=>{et(t,!0)},!1)),e}var tt={[qe]:function(){Ae(2)}};function nt(e){return null===e||!Ve(e)||Re.isFrozen(e)}var rt="MapSet",at="Patches",st="ArrayMethods",ot={};function it(e){const t=ot[e];return t||Ae(0,e),t}var ct,ut=e=>!!ot[e],dt=()=>ct;function lt(e,t){t&&(e.patchPlugin_=it(at),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function pt(e){ft(e),e.drafts_.forEach(gt),e.drafts_=null}function ft(e){e===ct&&(ct=e.parent_)}var ht=e=>ct={drafts_:[],parent_:ct,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:ut(rt)?it(rt):void 0,arrayMethodsPlugin_:ut(st)?it(st):void 0};function gt(e){const t=e[Ee];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function mt(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[Ee].modified_&&(pt(t),Ae(4)),De(e)&&(e=yt(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[Ee].base_,e,t)}else e=yt(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&et(t,n)}(t,e,!0),pt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==we?e:void 0}function yt(e,t){if(nt(t))return t;const n=t[Ee];if(!n)return Tt(t,e.handledSet_,e);if(!_t(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:t}=n;if(t)for(;t.length>0;)t.pop()(e);wt(n,e)}return n.copy_}function vt(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var _t=(e,t)=>e.scope_===t,bt=[];function St(e,t,n,r){const a=Xe(e),s=e.type_;if(void 0!==r&&ze(a,r,s)===t)return void Ke(a,r,n,s);if(!e.draftLocations_){const t=e.draftLocations_=new Map;Le(a,(e,n)=>{if(Me(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const o=e.draftLocations_.get(t)??bt;for(const e of o)Ke(a,e,n,s)}function wt(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||1===e.type_&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){const{patchPlugin_:n}=t;if(n){const r=n.getPath(e);r&&n.generatePatches_(e,r,t)}vt(e)}}function Tt(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Me(e)||t.has(e)||!De(e)||nt(e)||(t.add(e),Le(e,(r,a)=>{if(Me(a)){const t=a[Ee];if(_t(t,n)){const n=Ze(t);Ke(e,r,n,e.type_),vt(t)}}else De(a)&&Tt(a,t,n)})),e}var Et={get(e,t){if(t===Ee)return e;let n=e.scope_.arrayMethodsPlugin_;const r=1===e.type_&&"string"==typeof t;if(r&&n?.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);const a=Xe(e);if(!$e(a,t,e.type_))return function(e,t,n){const r=Rt(t,n);return r?qe in r?r[qe]:r.get?.call(e.draft_):void 0}(e,a,t);const s=a[t];if(e.finalized_||!De(s))return s;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return s;if(s===At(e.base_,t)){Ot(e);const n=1===e.type_?+t:t,r=Ct(0,s,e,n);return e.copy_[n]=r}return s},has:(e,t)=>t in Xe(e),ownKeys:e=>Reflect.ownKeys(Xe(e)),set(e,t,n){const r=Rt(Xe(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=At(Xe(e),t),o=r?.[Ee];if(o&&o.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((a=n)===(s=r)?0!==a||1/a==1/s:a!=a&&s!=s)&&(void 0!==n||$e(e.base_,t,e.type_)))return!0;Ot(e),kt(e)}var a,s;return e.copy_[t]===n&&(void 0!==n||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:r}=e;if(Me(n)){const a=n[Ee];_t(a,r)&&a.callbacks_.push(function(){Ot(e);const r=Ze(a);St(e,n,r,t)})}else De(n)&&e.callbacks_.push(function(){const a=Xe(e);3===e.type_?a.has(n)&&Tt(n,r.handledSet_,r):ze(a,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&Tt(ze(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(Ot(e),void 0!==At(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),kt(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Xe(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[xe]:!0,[Ne]:1!==e.type_||"length"!==t,[Pe]:r[Pe],[qe]:n[t]}:r},defineProperty(){Ae(11)},getPrototypeOf:e=>ke(e.base_),setPrototypeOf(){Ae(12)}},It={};for(let e in Et){let t=Et[e];It[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function At(e,t){const n=e[Ee];return(n?Xe(n):e)[t]}function Rt(e,t){if(!(t in e))return;let n=ke(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=ke(n)}}function kt(e){e.modified_||(e.modified_=!0,e.parent_&&kt(e.parent_))}function Ot(e){e.copy_||(e.assigned_=new Map,e.copy_=Ye(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function Ct(e,t,n,r){const[a,s]=Ge(t)?it(rt).proxyMap_(t,n):Be(t)?it(rt).proxySet_(t,n):function(e,t){const n=He(e),r={type_:n?1:0,scope_:t?t.scope_:dt(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,s=Et;n&&(a=[r],s=It);const{revoke:o,proxy:i}=Proxy.revocable(a,s);return r.draft_=i,r.revoke_=o,[i,r]}(t,n);return(n?.scope_??dt()).drafts_.push(a),s.callbacks_=n?.callbacks_??[],s.key_=r,n&&void 0!==r?function(e,t,n){e.callbacks_.push(function(r){const a=t;if(!a||!_t(a,r))return;r.mapSetPlugin_?.fixSetContents(a);const s=Ze(a);St(e,a.draft_??a,s,n),wt(a,r)})}(n,s,r):s.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(s);const{patchPlugin_:t}=e;s.modified_&&t&&t.generatePatches_(s,[],e)}),a}function Nt(e){return Me(e)||Ae(10,e),Pt(e)}function Pt(e){if(!De(e)||nt(e))return e;const t=e[Ee];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Ye(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=Ye(e,!0);return Le(n,(e,t)=>{Ke(n,e,Pt(t))},r),t&&(t.finalized_=!1),n}It.deleteProperty=function(e,t){return"production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&Ae(13),It.set.call(this,e,t,void 0)},It.set=function(e,t,n){return"production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&Ae(14),Et.set.call(this,e[0],t,n,e[0])};var xt=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(We(e)&&!We(t)){const n=t;t=e;const r=this;return function(e=n,...a){return r.produce(e,e=>t.call(this,e,...a))}}let r;if(We(t)||Ae(6),void 0===n||We(n)||Ae(7),De(e)){const a=ht(this),s=Ct(0,e,void 0);let o=!0;try{r=t(s),o=!1}finally{o?pt(a):ft(a)}return lt(a,n),mt(r,a)}if(!e||!Ve(e)){if(r=t(e),void 0===r&&(r=e),r===we&&(r=void 0),this.autoFreeze_&&et(r,!0),n){const t=[],a=[];it(at).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:a}),n(t,a)}return r}Ae(1,e)},this.produceWithPatches=(e,t)=>{if(We(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},Je(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),Je(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),Je(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){De(e)||Ae(8),Me(e)&&(e=Nt(e));const t=ht(this),n=Ct(0,e,void 0);return n[Ee].isManual_=!0,ft(t),n}finishDraft(e,t){const n=e&&e[Ee];n&&n.isManual_||Ae(9);const{scope_:r}=n;return lt(r,t),mt(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}n>-1&&(t=t.slice(n+1));const r=it(at).applyPatches_;return Me(e)?r(e,t):this.produce(e,e=>r(e,t))}},qt=xt.produceWithPatches.bind(xt),Mt=xt.applyPatches.bind(xt),Dt=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}},Qt=(e,t,n)=>{if(1===t.length&&t[0]===n){let t=!1;try{const n={};e(n)===n&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},Ft=(e,t,n)=>{const{memoize:r,memoizeOptions:a}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,i=r(()=>({}),...a);if(i.apply(null,s)!==i.apply(null,o)){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:n,firstInputs:s,secondInputs:o,stack:e})}},Ut={inputStabilityCheck:"once",identityFunctionCheck:"once"},Lt=e=>Array.isArray(e)?e:[e];function jt(e,t){const n=[],{length:r}=e;for(let a=0;a<r;a++)n.push(e[a].apply(null,t));return n}var $t="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function zt(){return{s:0,v:void 0,o:null,p:null}}function Kt(e,t={}){let n={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:r}=t;let a,s=0;function o(){let t=n;const{length:o}=arguments;for(let e=0,n=o;e<n;e++){const n=arguments[e];if("function"==typeof n||"object"==typeof n&&null!==n){let e=t.o;null===e&&(t.o=e=new WeakMap);const r=e.get(n);void 0===r?(t=zt(),e.set(n,t)):t=r}else{let e=t.p;null===e&&(t.p=e=new Map);const r=e.get(n);void 0===r?(t=zt(),e.set(n,t)):t=r}}const i=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),s++,r){const e=a?.deref?.()??a;null!=e&&r(e,c)&&(c=e,0!==s&&s--),a="object"==typeof c&&null!==c||"function"==typeof c?new $t(c):c}return i.s=1,i.v=c,c}return o.clearCache=()=>{n={s:0,v:void 0,o:null,p:null},o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function Ht(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t,r=0,a=0,s={},o=e.pop();"object"==typeof o&&(s=o,o=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);const i={...n,...s},{memoize:c,memoizeOptions:u=[],argsMemoize:d=Kt,argsMemoizeOptions:l=[],devModeChecks:p={}}=i,f=Lt(u),h=Lt(l),g=function(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const n=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${n}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}(e),m=c(function(){return r++,o.apply(null,arguments)},...f);let y=!0;const v=d(function(){a++;const e=jt(g,arguments);if(t=m.apply(null,e),"production"!==process.env.NODE_ENV){const{identityFunctionCheck:n,inputStabilityCheck:r}=((e,t)=>{const{identityFunctionCheck:n,inputStabilityCheck:r}={...Ut,...t};return{identityFunctionCheck:{shouldRun:"always"===n||"once"===n&&e,run:Qt},inputStabilityCheck:{shouldRun:"always"===r||"once"===r&&e,run:Ft}}})(y,p);if(n.shouldRun&&n.run(o,e,t),r.shouldRun){const t=jt(g,arguments);r.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:f},arguments)}y&&(y=!1)}return t},...h);return Object.assign(v,{resultFunc:o,memoizedResultFunc:m,dependencies:g,dependencyRecomputations:()=>a,resetDependencyRecomputations:()=>{a=0},lastResult:()=>t,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(r,{withTypes:()=>r}),r}var Gt=Ht(Kt),Bt=Object.assign((e,t=Gt)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const n=Object.keys(e);return t(n.map(t=>e[t]),(...e)=>e.reduce((e,t,r)=>(e[n[r]]=t,e),{}))},{withTypes:()=>Bt}),Vt=(e=>(e.uninitialized="uninitialized",e.pending="pending",e.fulfilled="fulfilled",e.rejected="rejected",e))(Vt||{}),Wt="uninitialized",Jt="pending",Xt="fulfilled",Zt="rejected";function Yt(e){return{status:e,isUninitialized:e===Wt,isLoading:e===Jt,isSuccess:e===Xt,isError:e===Zt}}var en=l;function tn(e,t){if(e===t||!(en(e)&&en(t)||Array.isArray(e)&&Array.isArray(t)))return t;const n=Object.keys(t),r=Object.keys(e);let a=n.length===r.length;const s=Array.isArray(t)?[]:{};for(const r of n)s[r]=tn(e[r],t[r]),a&&(a=e[r]===s[r]);return a?e:s}function nn(e,t,n){return e.reduce((e,r,a)=>(t(r,a)&&e.push(n(r,a)),e),[]).flat()}function rn(e){return null!=e}function an(e){return[...e?.values()??[]].filter(rn)}function sn(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var on=()=>new Map,cn=e=>{const t=new AbortController;return setTimeout(()=>{const e="signal timed out",n="TimeoutError";t.abort("undefined"!=typeof DOMException?new DOMException(e,n):Object.assign(new Error(e),{name:n}))},e),t.signal},un=(...e)=>{for(const t of e)if(t.aborted)return AbortSignal.abort(t.reason);const t=new AbortController;for(const n of e)n.addEventListener("abort",()=>t.abort(n.reason),{signal:t.signal,once:!0});return t.signal},dn=(...e)=>fetch(...e),ln=e=>e.status>=200&&e.status<=299,pn=e=>/ion\/(vnd\.api\+)?json/.test(e.get("content-type")||"");function fn(e){if(!l(e))return e;const t={...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];return t}var hn=class{constructor(e,t=void 0){this.value=e,this.meta=t}},gn="__rtkq/",mn="online",yn="offline",vn="focus",_n="focused",bn="visibilitychange",Sn=r(`${gn}${_n}`),wn=r(`${gn}un${_n}`),Tn=r(`${gn}${mn}`),En=r(`${gn}${yn}`),In=!1,An="query",Rn="mutation",kn="infinitequery";function On(e){return e.type===An}function Cn(e){return e.type===kn}function Nn(e){return On(e)||Cn(e)}function Pn(e,t,n,r,a,s){const o="function"==typeof e?e(t,n,r,a):e;return o?nn(o,rn,e=>s(xn(e))):[]}function xn(e){return"string"==typeof e?{type:e}:e}var qn=(e,t)=>e.endpointDefinitions[t],Mn=Symbol("forceQueryFn"),Dn=e=>"function"==typeof e[Mn],Qn=class extends Dt{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}},Fn=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function Un(e,t,n,r){const a=await e["~standard"].validate(t);if(a.issues)throw new Qn(a.issues,t,n,r);return a.value}function Ln(e){return e}var jn=(e={})=>({...e,[p]:!0});function $n(e,{pages:t,pageParams:n},r){const a=t.length-1;return e.getNextPageParam(t[a],t,n[a],n,r)}function zn(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function Kn(e,t,n,r){return Pn(n[e.meta.arg.endpointName][t],c(e)?e.payload:void 0,u(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,r)}function Hn(e){return Me(e)?Nt(e):e}function Gn(e,t,n){const r=e[t];r&&n(r)}function Bn(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function Vn(e,t,n){const r=e[Bn(t)];r&&n(r)}var Wn={},Jn=Symbol.for("RTKQ/skipToken"),Xn={status:Wt},Zn=y(Xn,()=>{}),Yn=y(Xn,()=>{}),er=WeakMap?new WeakMap:void 0,tr=({endpointName:e,queryArgs:t})=>{let n="";const r=er?.get(t);if("string"==typeof r)n=r;else{const e=JSON.stringify(t,(e,t)=>(t="bigint"==typeof t?{$bigint:t.toString()}:t,t=l(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t));l(t)&&er?.set(t,e),n=e}return`${e}(${n})`};function nr(...n){return function(r){const a=Kt(e=>r.extractRehydrationInfo?.(e,{reducerPath:r.reducerPath??"api"})),s={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...r,extractRehydrationInfo:a,serializeQueryArgs(e){let t=tr;if("serializeQueryArgs"in e.endpointDefinition){const n=e.endpointDefinition.serializeQueryArgs;t=e=>{const t=n(e);return"string"==typeof t?t:tr({...e,queryArgs:t})}}else r.serializeQueryArgs&&(t=r.serializeQueryArgs);return t(e)},tagTypes:[...r.tagTypes||[]]},o={endpointDefinitions:{},batch(e){e()},apiUid:e(),extractRehydrationInfo:a,hasRehydrationInfo:Kt(e=>null!=a(e))},i={injectEndpoints:function(e){const n=e.endpoints({query:e=>({...e,type:An}),mutation:e=>({...e,type:Rn}),infiniteQuery:e=>({...e,type:kn})});for(const[r,a]of Object.entries(n))if(!0!==e.overrideExisting&&r in o.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error("production"===process.env.NODE_ENV?t(39):`called \`injectEndpoints\` to override already-existing endpointName ${r} without specifying \`overrideExisting: true\``);"undefined"!=typeof process&&"development"===process.env.NODE_ENV&&console.error(`called \`injectEndpoints\` to override already-existing endpointName ${r} without specifying \`overrideExisting: true\``)}else{if("undefined"!=typeof process&&"development"===process.env.NODE_ENV&&Cn(a)){const{infiniteQueryOptions:e}=a,{maxPages:n,getPreviousPageParam:s}=e;if("number"==typeof n){if(n<1)throw new Error("production"===process.env.NODE_ENV?t(40):`maxPages for endpoint '${r}' must be a number greater than 0`);if("function"!=typeof s)throw new Error("production"===process.env.NODE_ENV?t(41):`getPreviousPageParam for endpoint '${r}' must be a function if maxPages is used`)}}o.endpointDefinitions[r]=a;for(const e of c)e.injectEndpoint(r,a)}return i},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)s.tagTypes.includes(t)||s.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(qn(o,e)):Object.assign(qn(o,e)||{},n);return i}},c=n.map(e=>e.init(i,s,o));return i.injectEndpoints({endpoints:r.endpoints})}}function rr(e,...t){return Object.assign(e,...t)}var ar=({api:e,queryThunk:t,context:n,internalState:r,selectors:{selectQueryEntry:a,selectConfig:s},getRunningQueryThunk:o})=>{const{removeQueryResult:c,unsubscribeQueryResult:u,cacheEntriesUpserted:d}=e.internalActions,l=i(u.match,t.fulfilled,t.rejected,d.match);function p(e){const t=r.currentSubscriptions.get(e);return!!t&&t.size>0}const f={};function h(e){for(const t of e.values())t?.abort?.()}function g(e,t,n){const r=t.getState();for(const s of e){const e=a(r,s);e?.endpointName&&m(s,e.endpointName,t,n)}}function m(e,t,r,s){const i=qn(n,t),u=i?.keepUnusedDataFor??s.keepUnusedDataFor;if(u===1/0)return;const d=Math.max(0,Math.min(u,2147482.647));if(!p(e)){const t=f[e];t&&clearTimeout(t),f[e]=setTimeout(()=>{if(!p(e)){const t=a(r.getState(),e);if(t?.endpointName){const e=r.dispatch(o(t.endpointName,t.originalArgs));e?.abort()}r.dispatch(c({queryCacheKey:e}))}delete f[e]},1e3*d)}}return(t,a)=>{const o=a.getState(),i=s(o);if(l(t)){let e;if(d.match(t))e=t.payload.map(e=>e.queryDescription.queryCacheKey);else{const{queryCacheKey:n}=u.match(t)?t.payload:t.meta.arg;e=[n]}g(e,a,i)}if(e.util.resetApiState.match(t)){for(const[e,t]of Object.entries(f))t&&clearTimeout(t),delete f[e];h(r.runningQueries),h(r.runningMutations)}if(n.hasRehydrationInfo(t)){const{queries:e}=n.extractRehydrationInfo(t);g(Object.keys(e),a,i)}}},sr=new Error("Promise never resolved before cacheEntryRemoved."),or=({api:e,reducerPath:t,context:n,queryThunk:r,mutationThunk:a,selectors:{selectQueryEntry:s}})=>{const o=v(r),i=v(a),u=c(r,a),d={},{removeQueryResult:l,removeMutationResult:p,cacheEntriesUpserted:f}=e.internalActions;function h(e,t,n){const r=d[e];r?.valueResolved&&(r.valueResolved({data:t,meta:n}),delete r.valueResolved)}function g(e){const t=d[e];t&&(delete d[e],t.cacheEntryRemoved())}function m(e){const{arg:t,requestId:n}=e.meta,{endpointName:r,originalArgs:a}=t;return[r,a,n]}function y(t,r,a,s,o){const i=qn(n,t),c=i?.onCacheEntryAdded;if(!c)return;const u={},l=new Promise(e=>{u.cacheEntryRemoved=e}),p=Promise.race([new Promise(e=>{u.valueResolved=e}),l.then(()=>{throw sr})]);p.catch(()=>{}),d[a]=u;const f=e.endpoints[t].select(Nn(i)?r:a),h=s.dispatch((e,t,n)=>n),g={...s,getCacheEntry:()=>f(s.getState()),requestId:o,extra:h,updateCachedData:Nn(i)?n=>s.dispatch(e.util.updateQueryData(t,r,n)):void 0,cacheDataLoaded:p,cacheEntryRemoved:l},m=c(r,g);Promise.resolve(m).catch(e=>{if(e!==sr)throw e})}return(n,c,v)=>{const _=function(e){return o(e)?e.meta.arg.queryCacheKey:i(e)?e.meta.arg.fixedCacheKey??e.meta.requestId:l.match(e)?e.payload.queryCacheKey:p.match(e)?Bn(e.payload):""}(n);function b(e,t,n,r){const a=s(v,t),o=s(c.getState(),t);!a&&o&&y(e,r,t,c,n)}if(r.pending.match(n)){const[e,t,r]=m(n);b(e,_,r,t)}else if(f.match(n))for(const{queryDescription:e,value:t}of n.payload){const{endpointName:r,originalArgs:a,queryCacheKey:s}=e;b(r,s,n.meta.requestId,a),h(s,t,{})}else if(a.pending.match(n)){if(c.getState()[t].mutations[_]){const[e,t,r]=m(n);y(e,t,_,c,r)}}else if(u(n))h(_,n.payload,n.meta.baseQueryMeta);else if(l.match(n)||p.match(n))g(_);else if(e.util.resetApiState.match(n))for(const e of Object.keys(d))g(e)}},ir=({api:e,context:{apiUid:t},reducerPath:n})=>(r,a)=>{e.util.resetApiState.match(r)&&a.dispatch(e.internalActions.middlewareRegistered(t)),"undefined"!=typeof process&&"development"===process.env.NODE_ENV&&e.internalActions.middlewareRegistered.match(r)&&r.payload===t&&"conflict"===a.getState()[n]?.config?.middlewareRegistered&&console.warn(`There is a mismatch between slice and middleware for the reducerPath "${n}".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${"api"===n?"\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!":""}`)},cr=({reducerPath:e,context:t,context:{endpointDefinitions:n},mutationThunk:r,queryThunk:a,api:s,assertTagType:o,refetchQuery:d,internalState:l})=>{const{removeQueryResult:p}=s.internalActions,f=i(c(r),u(r)),g=i(c(a,r),h(a,r));let m=[],y=0;function v(n,r){const a=r.getState(),o=a[e];if(m.push(...n),"delayed"===o.config.invalidationBehavior&&y>0)return;const i=m;if(m=[],0===i.length)return;const c=s.util.selectInvalidatedBy(a,i);t.batch(()=>{const e=Array.from(c.values());for(const{queryCacheKey:t}of e){const e=o.queries[t],n=sn(l.currentSubscriptions,t,on);e&&(0===n.size?r.dispatch(p({queryCacheKey:t})):e.status!==Wt&&r.dispatch(d(e)))}})}return(e,t)=>{(a.pending.match(e)||r.pending.match(e))&&y++,g(e)&&(y=Math.max(0,y-1)),f(e)?v(Kn(e,"invalidatesTags",n,o),t):g(e)?v([],t):s.util.invalidateTags.match(e)&&v(Pn(e.payload,void 0,void 0,void 0,void 0,o),t)}},ur=({reducerPath:e,queryThunk:t,api:n,refetchQuery:r,internalState:a})=>{const{currentPolls:s,currentSubscriptions:o}=a,i=new Set;let c=null;function u(e,t){i.add(e),c||(c=setTimeout(()=>{for(const e of i)l({queryCacheKey:e},t);i.clear(),c=null},0))}function d({queryCacheKey:t},n){const a=n.getState()[e],i=a.queries[t],c=o.get(t);if(!i||i.status===Wt)return;const{lowestPollingInterval:u,skipPollingIfUnfocused:l}=f(c);if(!Number.isFinite(u))return;const p=s.get(t);p?.timeout&&(clearTimeout(p.timeout),p.timeout=void 0);const h=Date.now()+u;s.set(t,{nextPollTimestamp:h,pollingInterval:u,timeout:setTimeout(()=>{!a.config.focused&&l||n.dispatch(r(i)),d({queryCacheKey:t},n)},u)})}function l({queryCacheKey:t},n){const r=n.getState()[e].queries[t],a=o.get(t);if(!r||r.status===Wt)return;const{lowestPollingInterval:i}=f(a);if("test"===process.env.NODE_ENV){const e=s.pollUpdateCounters??={};e[t]??=0,e[t]++}if(!Number.isFinite(i))return void p(t);const c=s.get(t),u=Date.now()+i;(!c||u<c.nextPollTimestamp)&&d({queryCacheKey:t},n)}function p(e){const t=s.get(e);t?.timeout&&clearTimeout(t.timeout),s.delete(e)}function f(e=new Map){let t=!1,n=Number.POSITIVE_INFINITY;for(const r of e.values())r.pollingInterval&&(n=Math.min(r.pollingInterval,n),t=r.skipPollingIfUnfocused||t);return{lowestPollingInterval:n,skipPollingIfUnfocused:t}}return(e,r)=>{(n.internalActions.updateSubscriptionOptions.match(e)||n.internalActions.unsubscribeQueryResult.match(e))&&u(e.payload.queryCacheKey,r),(t.pending.match(e)||t.rejected.match(e)&&e.meta.condition)&&u(e.meta.arg.queryCacheKey,r),(t.fulfilled.match(e)||t.rejected.match(e)&&!e.meta.condition)&&d(e.meta.arg,r),n.util.resetApiState.match(e)&&(function(){for(const e of s.keys())p(e)}(),c&&(clearTimeout(c),c=null),i.clear())}},dr=({api:e,context:t,queryThunk:n,mutationThunk:r})=>{const a=g(n,r),s=h(n,r),o=c(n,r),i={};return(n,r)=>{if(a(n)){const{requestId:a,arg:{endpointName:s,originalArgs:o}}=n.meta,c=qn(t,s),u=c?.onQueryStarted;if(u){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),i[a]=t;const d=e.endpoints[s].select(Nn(c)?o:a),l=r.dispatch((e,t,n)=>n),p={...r,getCacheEntry:()=>d(r.getState()),requestId:a,extra:l,updateCachedData:Nn(c)?t=>r.dispatch(e.util.updateQueryData(s,o,t)):void 0,queryFulfilled:n};u(o,p)}}else if(o(n)){const{requestId:e,baseQueryMeta:t}=n.meta;i[e]?.resolve({data:n.payload,meta:t}),delete i[e]}else if(s(n)){const{requestId:e,rejectedWithValue:t,baseQueryMeta:r}=n.meta;i[e]?.reject({error:n.payload??n.error,isUnhandledError:!t,meta:r}),delete i[e]}}};var lr=Symbol(),pr=({createSelector:l=n}={})=>({name:lr,init(n,{baseQuery:v,tagTypes:_,reducerPath:b,serializeQueryArgs:S,keepUnusedDataFor:w,refetchOnMountOrArgChange:T,refetchOnFocus:E,refetchOnReconnect:I,invalidationBehavior:A,onSchemaFailure:R,catchSchemaFailure:k,skipSchemaValidation:O},C){!function(){"production"!==process.env.NODE_ENV&&Ie.push('Sets cannot have "replace" patches.',function(e){return"Unsupported patch operation: "+e},function(e){return"Cannot apply patch, path doesn't resolve: "+e},"Patching reserved attributes like __proto__, prototype and constructor is not allowed");const e="replace",t="add",n="remove";function r(e){if(!De(e))return e;if(He(e))return e.map(r);if(Ge(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(Be(e))return new Set(Array.from(e).map(r));const t=Object.create(ke(e));for(const n in e)t[n]=r(e[n]);return $e(e,Te)&&(t[Te]=e[Te]),t}function a(e){return Me(e)?r(e):e}var s;ot[s=at]||(ot[s]={applyPatches_:function(a,s){return s.forEach(s=>{const{path:o,op:i}=s;let c=a;for(let e=0;e<o.length-1;e++){const t=je(c);let n=o[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==Oe||Ae(19),We(c)&&n===Ce&&Ae(19),c=ze(c,n),Ve(c)||Ae(18,o.join("/"))}const u=je(c),d=r(s.value),l=o[o.length-1];switch(i){case e:switch(u){case 2:return c.set(l,d);case 3:Ae(16);default:return c[l]=d}case t:switch(u){case 1:return"-"===l?c.push(d):c.splice(l,0,d);case 2:return c.set(l,d);case 3:return c.add(d);default:return c[l]=d}case n:switch(u){case 1:return c.splice(l,1);case 2:return c.delete(l);case 3:return c.delete(s.value);default:return delete c[l]}default:Ae(17,i)}}),a},generatePatches_:function(r,s,o){if(r.scope_.processedForPatches_.has(r))return;r.scope_.processedForPatches_.add(r);const{patches_:i,inversePatches_:c}=o;switch(r.type_){case 0:case 2:return function(r,s,o,i){const{base_:c,copy_:u,type_:d}=r;Le(r.assigned_,(r,l)=>{const p=ze(c,r,d),f=ze(u,r,d),h=l?$e(c,r)?e:t:n;if(p===f&&h===e)return;const g=s.concat(r);o.push(h===n?{op:h,path:g}:{op:h,path:g,value:a(f)}),i.push(h===t?{op:n,path:g}:h===n?{op:t,path:g,value:a(p)}:{op:e,path:g,value:a(p)})})}(r,s,i,c);case 1:return function(r,s,o,i){let{base_:c,assigned_:u}=r,d=r.copy_;d.length<c.length&&([c,d]=[d,c],[o,i]=[i,o]);const l=!0===r.allIndicesReassigned_;for(let t=0;t<c.length;t++){const n=d[t],r=c[t];if((l||u?.get(t.toString()))&&n!==r){const c=n?.[Ee];if(c&&c.modified_)continue;const u=s.concat([t]);o.push({op:e,path:u,value:a(n)}),i.push({op:e,path:u,value:a(r)})}}for(let e=c.length;e<d.length;e++){const n=s.concat([e]);o.push({op:t,path:n,value:a(d[e])})}for(let e=d.length-1;c.length<=e;--e){const t=s.concat([e]);i.push({op:n,path:t})}}(r,s,i,c);case 3:return function(e,r,a,s){let{base_:o,copy_:i}=e,c=0;o.forEach(e=>{if(!i.has(e)){const o=r.concat([c]);a.push({op:n,path:o,value:e}),s.unshift({op:t,path:o,value:e})}c++}),c=0,i.forEach(e=>{if(!o.has(e)){const o=r.concat([c]);a.push({op:t,path:o,value:e}),s.unshift({op:n,path:o,value:e})}c++})}(r,s,i,c)}},generateReplacementPatches_:function(t,n,r){const{patches_:a,inversePatches_:s}=r;a.push({op:e,path:[],value:n===we?void 0:n}),s.push({op:e,path:[],value:t})},getPath:function e(t,n=[]){if(void 0!==t.key_){const e=t.parent_.copy_??t.parent_.base_,a=(r=ze(e,t.key_),Ve(r)?r?.[Ee]:null),s=ze(e,t.key_);if(void 0===s)return null;if(s!==t.draft_&&s!==t.base_&&s!==t.copy_)return null;if(null!=a&&a.base_!==t.base_)return null;const o=3===t.parent_.type_;let i;if(i=o?Array.from(t.parent_.drafts_.keys()).indexOf(t.key_):t.key_,!(o&&e.size>i||$e(e,i)))return null;n.push(i)}var r;if(t.parent_)return e(t.parent_,n);n.reverse();try{!function(e,t){let n=e;for(let e=0;e<t.length-1;e++)if(n=ze(n,t[e]),!Ve(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}(t.copy_,n)}catch(e){return null}return n}})}();const N=e=>("undefined"!=typeof process&&"development"===process.env.NODE_ENV&&(_.includes(e.type)||console.error(`Tag type '${e.type}' was used, but not specified in \`tagTypes\`!`)),e);Object.assign(n,{reducerPath:b,endpoints:{},internalActions:{onOnline:Tn,onOffline:En,onFocus:Sn,onFocusLost:wn},util:{}});const P=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>Zn,a=e=>Yn;return{buildQuerySelector:function(e,t){return u(e,t,s)},buildInfiniteQuerySelector:function(e,t){const{infiniteQueryOptions:n}=t;return u(e,t,function(e){const t={...e,...Yt(e.status)},{isLoading:r,isError:a,direction:s}=t,o="forward"===s,i="backward"===s;return{...t,hasNextPage:(c=n,u=t.data,l=t.originalArgs,!!u&&null!=$n(c,u,l)),hasPreviousPage:d(n,t.data,t.originalArgs),isFetchingNextPage:r&&o,isFetchingPreviousPage:r&&i,isFetchNextPageError:a&&o,isFetchPreviousPageError:a&&i};var c,u,l})},buildMutationSelector:function(){return e=>{let t;return t="object"==typeof e?Bn(e)??Jn:e,n(t===Jn?a:e=>o(e)?.mutations?.[t]??Yn,s)}},selectInvalidatedBy:function(e,n){const r=e[t],a=new Set,s=nn(n,rn,xn);for(const e of s){const t=r.provided.tags[e.type];if(!t)continue;let n=(void 0!==e.id?t[e.id]:Object.values(t).flat())??[];for(const e of n)a.add(e)}return Array.from(a.values()).flatMap(e=>{const t=r.queries[e];return t?{queryCacheKey:e,endpointName:t.endpointName,originalArgs:t.originalArgs}:[]})},selectCachedArgsForQuery:function(e,t){return nn(Object.values(i(e)),e=>e?.endpointName===t&&e.status!==Wt,e=>e.originalArgs)},selectApiState:o,selectQueries:i,selectMutations:function(e){return o(e)?.mutations},selectQueryEntry:c,selectConfig:function(e){return o(e)?.config}};function s(e){return{...e,...Yt(e.status)}}function o(e){const n=e[t];if("production"!==process.env.NODE_ENV&&!n){if(o.triggered)return n;o.triggered=!0,console.error(`Error: No data found at \`state.${t}\`. Did you forget to add the reducer to the store?`)}return n}function i(e){return o(e)?.queries}function c(e,t){return i(e)?.[t]}function u(t,a,s){return o=>{if(o===Jn)return n(r,s);const i=e({queryArgs:o,endpointDefinition:a,endpointName:t});return n(e=>c(e,i)??Zn,s)}}function d(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=zn(e,t,n)}}({serializeQueryArgs:S,reducerPath:b,createSelector:l}),{selectInvalidatedBy:x,selectCachedArgsForQuery:q,buildQuerySelector:M,buildInfiniteQuerySelector:D,buildMutationSelector:Q}=P;rr(n.util,{selectInvalidatedBy:x,selectCachedArgsForQuery:q});const{queryThunk:F,infiniteQueryThunk:U,mutationThunk:L,patchQueryData:j,updateQueryData:$,upsertQueryData:z,prefetch:K,buildMatchThunkActions:H}=function({reducerPath:e,baseQuery:t,context:{endpointDefinitions:n},serializeQueryArgs:r,api:s,assertTagType:o,selectors:i,onSchemaFailure:u,catchSchemaFailure:d,skipSchemaValidation:l}){function p(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}function m(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}const y=(e,t)=>e.query&&e[t]?e[t]:Ln,v=async(e,{signal:r,abort:a,rejectWithValue:s,fulfillWithValue:o,dispatch:c,getState:f,extra:h})=>{const g=n[e.endpointName],{metaSchema:v,skipSchemaValidation:b=l}=g,S=e.type===An;try{let w=Ln;const T={signal:r,abort:a,dispatch:c,getState:f,extra:h,endpoint:e.endpointName,type:e.type,forced:S?_(e,f()):void 0,queryCacheKey:S?e.queryCacheKey:void 0},E=S?e[Mn]:void 0;let I;const A=async(t,n,r,a)=>{if(null==n&&t.pages.length)return Promise.resolve({data:t});const s={queryArg:e.originalArgs,pageParam:n},o=await R(s),i=a?p:m;return{data:{pages:i(t.pages,o.data,r),pageParams:i(t.pageParams,n,r)},meta:o.meta}};async function R(n){let r;const{extraOptions:a,argSchema:s,rawResponseSchema:o,responseSchema:i}=g;if(s&&!Fn(b,"arg")&&(n=await Un(s,n,"argSchema",{})),E?r=E():g.query?(w=y(g,"transformResponse"),r=await t(g.query(n),T,a)):r=await g.queryFn(n,T,a,e=>t(e,T,a)),"undefined"!=typeof process&&"development"===process.env.NODE_ENV){const t=g.query?"`baseQuery`":"`queryFn`";let n;if(r){if("object"!=typeof r)n=`${t} did not return an object.`;else if(r.error&&r.data)n=`${t} returned an object containing both \`error\` and \`result\`.`;else if(void 0===r.error&&void 0===r.data)n=`${t} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;else for(const e of Object.keys(r))if("error"!==e&&"data"!==e&&"meta"!==e){n=`The object returned by ${t} has the unknown property ${e}.`;break}}else n=`${t} did not return anything.`;n&&console.error(`Error encountered handling the endpoint ${e.endpointName}.\n ${n}\n It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.\n Object returned was:`,r)}if(r.error)throw new hn(r.error,r.meta);let{data:c}=r;o&&!Fn(b,"rawResponse")&&(c=await Un(o,r.data,"rawResponseSchema",r.meta));let u=await w(c,r.meta,n);return i&&!Fn(b,"response")&&(u=await Un(i,u,"responseSchema",r.meta)),{...r,data:u}}if(S&&"infiniteQueryOptions"in g){const{infiniteQueryOptions:k}=g,{maxPages:O=1/0}=k,C=e.refetchCachedPages??k.refetchCachedPages??!0;let N;const P={pages:[],pageParams:[]},x=i.selectQueryEntry(f(),e.queryCacheKey)?.data,q=_(e,f())&&!e.direction||!x?P:x;if("direction"in e&&e.direction&&q.pages.length){const M="backward"===e.direction,D=(M?zn:$n)(k,q,e.originalArgs);N=await A(q,D,O,M)}else{const{initialPageParam:Q=k.initialPageParam}=e,F=x?.pageParams??[],U=F[0]??Q,L=F.length;if(N=await A(q,U,O),E&&(N={data:N.data.pages[0]}),C)for(let j=1;j<L;j++){const $=$n(k,N.data,e.originalArgs);N=await A(N.data,$,O)}}I=N}else I=await R(e.originalArgs);return v&&!Fn(b,"meta")&&I.meta&&(I.meta=await Un(v,I.meta,"metaSchema",I.meta)),o(I.data,jn({fulfilledTimeStamp:Date.now(),baseQueryMeta:I.meta}))}catch(z){let K=z;if(K instanceof hn){let H=y(g,"transformErrorResponse");const{rawErrorResponseSchema:G,errorResponseSchema:B}=g;let{value:V,meta:W}=K;try{G&&!Fn(b,"rawErrorResponse")&&(V=await Un(G,V,"rawErrorResponseSchema",W)),v&&!Fn(b,"meta")&&(W=await Un(v,W,"metaSchema",W));let J=await H(V,W,e.originalArgs);return B&&!Fn(b,"errorResponse")&&(J=await Un(B,J,"errorResponseSchema",W)),s(J,jn({baseQueryMeta:W}))}catch(X){K=X}}try{if(K instanceof Qn){const Z={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:S?e.queryCacheKey:void 0};g.onSchemaFailure?.(K,Z),u?.(K,Z);const{catchSchemaFailure:Y=d}=g;if(Y)return s(Y(K,Z),jn({baseQueryMeta:K._bqMeta}))}}catch(ee){K=ee}throw"undefined"!=typeof process&&"production"!==process.env.NODE_ENV?console.error(`An unhandled error occurred processing a request for the endpoint "${e.endpointName}".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,K):console.error(K),K}};function _(e,t){const n=i.selectQueryEntry(t,e.queryCacheKey),r=i.selectConfig(t).refetchOnMountOrArgChange,a=n?.fulfilledTimeStamp,s=e.forceRefetch??(e.subscribe&&r);return!!s&&(!0===s||(Number(new Date)-Number(a))/1e3>=s)}const b=()=>a(`${e}/executeQuery`,v,{getPendingMeta({arg:e}){const t=n[e.endpointName];return jn({startedTimeStamp:Date.now(),...Cn(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const r=t(),a=i.selectQueryEntry(r,e.queryCacheKey),s=a?.fulfilledTimeStamp,o=e.originalArgs,c=a?.originalArgs,u=n[e.endpointName],d=e.direction;return!(!Dn(e)&&("pending"===a?.status||!_(e,r)&&(!On(u)||!u?.forceRefetch?.({currentArg:o,previousArg:c,endpointState:a,state:r}))&&s&&!d))},dispatchConditionRejection:!0}),S=b(),w=b();function T(e){return t=>t?.meta?.arg?.endpointName===e}return{queryThunk:S,mutationThunk:a(`${e}/executeMutation`,v,{getPendingMeta:()=>jn({startedTimeStamp:Date.now()})}),infiniteQueryThunk:w,prefetch:(e,t,n={})=>(r,a)=>{const o=(e=>"force"in e)(n)&&n.force,i=(e=>"ifOlderThan"in e)(n)&&n.ifOlderThan,c=(n=!0)=>s.endpoints[e].initiate(t,{forceRefetch:n,subscribe:!1}),u=s.endpoints[e].select(t)(a());if(o)r(c());else if(i){const e=u?.fulfilledTimeStamp;if(!e)return void r(c());(Number(new Date)-Number(new Date(e)))/1e3>=i&&r(c())}else r(c(!1))},updateQueryData:(e,t,n,r=!0)=>(a,o)=>{const i=s.endpoints[e].select(t)(o()),c={patches:[],inversePatches:[],undo:()=>a(s.util.patchQueryData(e,t,c.inversePatches,r))};if(i.status===Wt)return c;let u;if("data"in i)if(De(i.data)){const[e,t,r]=qt(i.data,n);c.patches.push(...t),c.inversePatches.push(...r),u=e}else u=n(i.data),c.patches.push({op:"replace",path:[],value:u}),c.inversePatches.push({op:"replace",path:[],value:i.data});return 0===c.patches.length||a(s.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(s.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[Mn]:()=>({data:n})})),patchQueryData:(e,t,a,i)=>(c,u)=>{const d=n[e],l=r({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(s.internalActions.queryResultPatched({queryCacheKey:l,patches:a})),!i)return;const p=s.endpoints[e].select(t)(u()),f=Pn(d.providesTags,p.data,void 0,t,{},o);c(s.internalActions.updateProvidedBy([{queryCacheKey:l,providedTags:f}]))},buildMatchThunkActions:function(e,t){return{matchPending:f(g(e),T(t)),matchFulfilled:f(c(e),T(t)),matchRejected:f(h(e),T(t))}}}}({baseQuery:v,reducerPath:b,context:C,api:n,serializeQueryArgs:S,assertTagType:N,selectors:P,onSchemaFailure:R,catchSchemaFailure:k,skipSchemaValidation:O}),{reducer:G,actions:B}=function({reducerPath:t,queryThunk:n,mutationThunk:a,serializeQueryArgs:l,context:{endpointDefinitions:f,apiUid:h,extractRehydrationInfo:g,hasRehydrationInfo:m},assertTagType:v,config:_}){const b=r(`${t}/resetApiState`);function S(e,t,n,r){e[t.queryCacheKey]??={status:Wt,endpointName:t.endpointName},Gn(e,t.queryCacheKey,e=>{e.status=Jt,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp,Cn(f[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function w(e,t,n,r){Gn(e,t.arg.queryCacheKey,e=>{if(e.requestId!==t.requestId&&!r)return;const{merge:a}=f[t.arg.endpointName];if(e.status=Xt,a)if(void 0!==e.data){const{fulfilledTimeStamp:r,arg:s,baseQueryMeta:o,requestId:i}=t;let c=y(e.data,e=>a(e,n,{arg:s.originalArgs,baseQueryMeta:o,fulfilledTimeStamp:r,requestId:i}));e.data=c}else e.data=n;else e.data=f[t.arg.endpointName].structuralSharing??1?tn(Me(e.data)?(Me(s=e.data)||Ae(15,s),s[Ee].base_):e.data,n):n;var s;delete e.error,e.fulfilledTimeStamp=t.fulfilledTimeStamp})}const T=s({name:`${t}/queries`,initialState:Wn,reducers:{removeQueryResult:{reducer(e,{payload:{queryCacheKey:t}}){delete e[t]},prepare:o()},cacheEntriesUpserted:{reducer(e,t){for(const n of t.payload){const{queryDescription:r,value:a}=n;S(e,r,!0,{arg:r,requestId:t.meta.requestId,startedTimeStamp:t.meta.timestamp}),w(e,{arg:r,requestId:t.meta.requestId,fulfilledTimeStamp:t.meta.timestamp,baseQueryMeta:{}},a,!0)}},prepare:t=>({payload:t.map(e=>{const{endpointName:t,arg:n,value:r}=e;return{queryDescription:{type:An,endpointName:t,originalArgs:e.arg,queryCacheKey:l({queryArgs:n,endpointDefinition:f[t],endpointName:t})},value:r}}),meta:{[p]:!0,requestId:e(),timestamp:Date.now()}})},queryResultPatched:{reducer(e,{payload:{queryCacheKey:t,patches:n}}){Gn(e,t,e=>{e.data=Mt(e.data,n.concat())})},prepare:o()}},extraReducers(e){e.addCase(n.pending,(e,{meta:t,meta:{arg:n}})=>{S(e,n,Dn(n),t)}).addCase(n.fulfilled,(e,{meta:t,payload:n})=>{w(e,t,n,Dn(t.arg))}).addCase(n.rejected,(e,{meta:{condition:t,arg:n,requestId:r},error:a,payload:s})=>{Gn(e,n.queryCacheKey,e=>{if(t);else{if(e.requestId!==r)return;e.status=Zt,e.error=s??a}})}).addMatcher(m,(e,t)=>{const{queries:n}=g(t);for(const[t,r]of Object.entries(n))r?.status!==Xt&&r?.status!==Zt||(e[t]=r)})}}),E=s({name:`${t}/mutations`,initialState:Wn,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=Bn(t);n in e&&delete e[n]},prepare:o()}},extraReducers(e){e.addCase(a.pending,(e,{meta:t,meta:{requestId:n,arg:r,startedTimeStamp:a}})=>{r.track&&(e[Bn(t)]={requestId:n,status:Jt,endpointName:r.endpointName,startedTimeStamp:a})}).addCase(a.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&Vn(e,n,e=>{e.requestId===n.requestId&&(e.status=Xt,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(a.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&Vn(e,r,e=>{e.requestId===r.requestId&&(e.status=Zt,e.error=t??n)})}).addMatcher(m,(e,t)=>{const{mutations:n}=g(t);for(const[t,r]of Object.entries(n))r?.status!==Xt&&r?.status!==Zt||t===r?.requestId||(e[t]=r)})}}),I=s({name:`${t}/invalidation`,initialState:{tags:{},keys:{}},reducers:{updateProvidedBy:{reducer(e,t){for(const{queryCacheKey:n,providedTags:r}of t.payload){A(e,n);for(const{type:t,id:a}of r){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];r.includes(n)||r.push(n)}e.keys[n]=r}},prepare:o()}},extraReducers(e){e.addCase(T.actions.removeQueryResult,(e,{payload:{queryCacheKey:t}})=>{A(e,t)}).addMatcher(m,(e,t)=>{const{provided:n}=g(t);for(const[t,r]of Object.entries(n.tags??{}))for(const[a,s]of Object.entries(r)){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];for(const t of s)r.includes(t)||r.push(t),e.keys[t]=n.keys[t]}}).addMatcher(i(c(n),u(n)),(e,t)=>{R(e,[t])}).addMatcher(T.actions.cacheEntriesUpserted.match,(e,t)=>{R(e,t.payload.map(({queryDescription:e,value:t})=>({type:"UNKNOWN",payload:t,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:e}})))})}});function A(e,t){const n=Hn(e.keys[t]??[]);for(const r of n){const n=r.type,a=r.id??"__internal_without_id",s=e.tags[n]?.[a];s&&(e.tags[n][a]=Hn(s).filter(e=>e!==t))}delete e.keys[t]}function R(e,t){const n=t.map(e=>{const t=Kn(e,"providesTags",f,v),{queryCacheKey:n}=e.meta.arg;return{queryCacheKey:n,providedTags:t}});I.caseReducers.updateProvidedBy(e,I.actions.updateProvidedBy(n))}const k=s({name:`${t}/subscriptions`,initialState:Wn,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),O=s({name:`${t}/internalSubscriptions`,initialState:Wn,reducers:{subscriptionsUpdated:{reducer:(e,t)=>Mt(e,t.payload),prepare:o()}}}),C=s({name:`${t}/config`,initialState:{online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine,focused:"undefined"==typeof document||"hidden"!==document.visibilityState,middlewareRegistered:!1,..._},reducers:{middlewareRegistered(e,{payload:t}){e.middlewareRegistered="conflict"!==e.middlewareRegistered&&h===t||"conflict"}},extraReducers:e=>{e.addCase(Tn,e=>{e.online=!0}).addCase(En,e=>{e.online=!1}).addCase(Sn,e=>{e.focused=!0}).addCase(wn,e=>{e.focused=!1}).addMatcher(m,e=>({...e}))}}),N=d({queries:T.reducer,mutations:E.reducer,provided:I.reducer,subscriptions:O.reducer,config:C.reducer});return{reducer:(e,t)=>N(b.match(t)?void 0:e,t),actions:{...C.actions,...T.actions,...k.actions,...O.actions,...E.actions,...I.actions,resetApiState:b}}}({context:C,queryThunk:F,mutationThunk:L,serializeQueryArgs:S,reducerPath:b,assertTagType:N,config:{refetchOnFocus:E,refetchOnReconnect:I,refetchOnMountOrArgChange:T,keepUnusedDataFor:w,reducerPath:b,invalidationBehavior:A}});rr(n.util,{patchQueryData:j,updateQueryData:$,upsertQueryData:z,prefetch:K,resetApiState:B.resetApiState,upsertQueryEntries:B.cacheEntriesUpserted}),rr(n.internalActions,B);const V=new WeakMap,W=e=>sn(V,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:J,buildInitiateInfiniteQuery:X,buildInitiateMutation:Z,getRunningMutationThunk:Y,getRunningMutationsThunk:ee,getRunningQueriesThunk:te,getRunningQueryThunk:ne}=function({serializeQueryArgs:e,queryThunk:n,infiniteQueryThunk:r,mutationThunk:a,api:s,context:o,getInternalState:i}){const c=e=>i(e)?.runningQueries,u=e=>i(e)?.runningMutations,{unsubscribeQueryResult:d,removeMutationResult:l,updateSubscriptionOptions:p}=s.internalActions;return{buildInitiateQuery:function(e,t){return h(e,t)},buildInitiateInfiniteQuery:function(e,t){return h(e,t)},buildInitiateMutation:function(e){return(t,{track:n=!0,fixedCacheKey:r}={})=>(s,o)=>{const i=a({type:"mutation",endpointName:e,originalArgs:t,track:n,fixedCacheKey:r}),c=s(i);f(s);const{requestId:d,abort:p,unwrap:h}=c,g=c.unwrap().then(e=>({data:e})).catch(e=>({error:e})),m=Object.assign(g,{arg:c.arg,requestId:d,abort:p,unwrap:h,reset:()=>{s(l({requestId:d,fixedCacheKey:r}))}}),y=u(s);return y.set(d,m),m.then(()=>{y.delete(d)}),r&&(y.set(r,m),m.then(()=>{y.get(r)===m&&y.delete(r)})),m}},getRunningQueryThunk:function(t,n){return r=>{const a=qn(o,t),s=e({queryArgs:n,endpointDefinition:a,endpointName:t});return c(r)?.get(s)}},getRunningMutationThunk:function(e,t){return e=>u(e)?.get(t)},getRunningQueriesThunk:function(){return e=>an(c(e))},getRunningMutationsThunk:function(){return e=>an(u(e))}};function f(e){if("production"!==process.env.NODE_ENV){if(f.triggered)return;const n=e(s.internalActions.internal_getRTKQSubscriptions());if(f.triggered=!0,"object"!=typeof n||"string"==typeof n?.type)throw new Error("production"===process.env.NODE_ENV?t(34):`Warning: Middleware for RTK-Query API at reducerPath "${s.reducerPath}" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`)}}function h(t,a){const o=(i,{subscribe:u=!0,forceRefetch:l,subscriptionOptions:h,[Mn]:g,...m}={})=>(y,v)=>{const _=e({queryArgs:i,endpointDefinition:a,endpointName:t});let b;const S={...m,type:An,subscribe:u,forceRefetch:l,subscriptionOptions:h,endpointName:t,originalArgs:i,queryCacheKey:_,[Mn]:g};if(On(a))b=n(S);else{const{direction:e,initialPageParam:t,refetchCachedPages:n}=m;b=r({...S,direction:e,initialPageParam:t,refetchCachedPages:n})}const w=s.endpoints[t].select(i),T=y(b),E=w(v());f(y);const{requestId:I,abort:A}=T,R=E.requestId!==I,k=c(y)?.get(_),O=()=>w(v()),C=Object.assign(g?T.then(O):R&&!k?Promise.resolve(E):Promise.all([k,T]).then(O),{arg:i,requestId:I,subscriptionOptions:h,queryCacheKey:_,abort:A,async unwrap(){const e=await C;if(e.isError)throw e.error;return e.data},refetch:e=>y(o(i,{subscribe:!1,forceRefetch:!0,...e})),unsubscribe(){u&&y(d({queryCacheKey:_,requestId:I}))},updateSubscriptionOptions(e){C.subscriptionOptions=e,y(p({endpointName:t,requestId:I,queryCacheKey:_,options:e}))}});if(!k&&!R&&!g){const e=c(y);e.set(_,C),C.then(()=>{e.delete(_)})}return C};return o}}({queryThunk:F,mutationThunk:L,infiniteQueryThunk:U,api:n,serializeQueryArgs:S,context:C,getInternalState:W});rr(n.util,{getRunningMutationThunk:Y,getRunningMutationsThunk:ee,getRunningQueryThunk:ne,getRunningQueriesThunk:te});const{middleware:re,actions:ae}=function(e){const{reducerPath:t,api:n,context:a,getInternalState:s}=e,{apiUid:o}=a,i={invalidateTags:r(`${t}/invalidateTags`)},c=e=>e.type.startsWith(`${t}/`),u=[ir,ar,cr,ur,or,dr];return{middleware:r=>{let i=!1;const l=s(r.dispatch),p={...e,internalState:l,refetchQuery:d,isThisApiSliceAction:c,mwApi:r},f=u.map(e=>e(p)),h=(({api:e,queryThunk:t,internalState:n})=>{const r=`${e.reducerPath}/subscriptions`;let a=null,s=null;const{updateSubscriptionOptions:o,unsubscribeQueryResult:i}=e.internalActions,c=()=>n.currentSubscriptions,u={getSubscriptions:c,getSubscriptionCount:e=>{const t=c().get(e);return t?.size??0},isRequestSubscribed:(e,t)=>{const n=c();return!!n?.get(e)?.get(t)}};function d(e){return JSON.parse(JSON.stringify(Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)]))))}return(c,l)=>{if(a||(a=d(n.currentSubscriptions)),e.util.resetApiState.match(c))return a={},n.currentSubscriptions.clear(),s=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(c))return[!1,u];const p=((n,r)=>{if(o.match(r)){const{queryCacheKey:e,requestId:t,options:a}=r.payload,s=n.get(e);return s?.has(t)&&s.set(t,a),!0}if(i.match(r)){const{queryCacheKey:e,requestId:t}=r.payload,a=n.get(e);return a&&a.delete(t),!0}if(e.internalActions.removeQueryResult.match(r))return n.delete(r.payload.queryCacheKey),!0;if(t.pending.match(r)){const{meta:{arg:e,requestId:t}}=r,a=sn(n,e.queryCacheKey,on);return e.subscribe&&a.set(t,e.subscriptionOptions??a.get(t)??{}),!0}let a=!1;if(t.rejected.match(r)){const{meta:{condition:e,arg:t,requestId:s}}=r;if(e&&t.subscribe){const e=sn(n,t.queryCacheKey,on);e.set(s,t.subscriptionOptions??e.get(s)??{}),a=!0}}return a})(n.currentSubscriptions,c);let f=!0;if("test"===process.env.NODE_ENV&&"string"==typeof c.type&&c.type===`${e.reducerPath}/getPolling`)return[!1,n.currentPolls];if(p){s||(s=setTimeout(()=>{const t=d(n.currentSubscriptions),[,r]=qt(a,()=>t);l.next(e.internalActions.subscriptionsUpdated(r)),a=t,s=null},500));const o="string"==typeof c.type&&!!c.type.startsWith(r),i=t.rejected.match(c)&&c.meta.condition&&!!c.meta.arg.subscribe;f=!o&&!i}return[f,!1]}})(p),g=(({reducerPath:e,context:t,api:n,refetchQuery:r,internalState:a})=>{const{removeQueryResult:s}=n.internalActions;function o(n,o){const i=n.getState()[e],c=i.queries,u=a.currentSubscriptions;t.batch(()=>{for(const e of u.keys()){const t=c[e],a=u.get(e);if(!a||!t)continue;const d=[...a.values()];(d.some(e=>!0===e[o])||d.every(e=>void 0===e[o])&&i.config[o])&&(0===a.size?n.dispatch(s({queryCacheKey:e})):t.status!==Wt&&n.dispatch(r(t)))}})}return(e,t)=>{Sn.match(e)&&o(t,"refetchOnFocus"),Tn.match(e)&&o(t,"refetchOnReconnect")}})(p);return e=>s=>{if(!m(s))return e(s);i||(i=!0,r.dispatch(n.internalActions.middlewareRegistered(o)));const u={...r,next:e},d=r.getState(),[l,p]=h(s,u,d);let y;if(y=l?e(s):p,r.getState()[t]&&(g(s,u,d),c(s)||a.hasRehydrationInfo(s)))for(const e of f)e(s,u,d);return y}},actions:i};function d(t){return e.api.endpoints[t.endpointName].initiate(t.originalArgs,{subscribe:!1,forceRefetch:!0})}}({reducerPath:b,context:C,queryThunk:F,mutationThunk:L,infiniteQueryThunk:U,api:n,assertTagType:N,selectors:P,getRunningQueryThunk:ne,getInternalState:W});return rr(n.util,ae),rr(n,{reducer:G,middleware:re}),{name:lr,injectEndpoint(e,t){const r=n,a=r.endpoints[e]??={};On(t)&&rr(a,{name:e,select:M(e,t),initiate:J(e,t)},H(F,e)),t.type===Rn&&rr(a,{name:e,select:Q(),initiate:Z(e)},H(L,e)),Cn(t)&&rr(a,{name:e,select:D(e,t),initiate:X(e,t)},H(F,e))}}}});function fr(e){return e.replace(e[0],e[0].toUpperCase())}function hr(e){let t=0;for(const n in e)t++;return t}function gr(e){return"infinitequery"===e.type}function mr(e,...t){return Object.assign(e,...t)}pr();var yr=Symbol();function vr(e){const t=C(e),n=R(()=>tn(t.current,e),[e]);return O(()=>{t.current!==n&&(t.current=n)},[n]),n}function _r(e){const t=C(e);return O(()=>{E(t.current,e)||(t.current=e)},[e]),E(t.current,e)?t.current:e}var br=(()=>!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement))(),Sr=(()=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product)(),wr=(()=>br||Sr?N:O)(),Tr=e=>e.isUninitialized?{...e,isUninitialized:!1,isFetching:!0,isLoading:void 0===e.data,status:Vt.pending}:e;function Er(e,...t){const n={};return t.forEach(t=>{n[t]=e[t]}),n}var Ir=["data","status","isLoading","isSuccess","isError","error"],Ar=Symbol(),Rr=nr(pr(),(({batch:e=T,hooks:n={useDispatch:w,useSelector:S,useStore:b},createSelector:r=Gt,unstable__sideEffectsInRender:a=!1,...s}={})=>{if("production"!==process.env.NODE_ENV){const e=["useDispatch","useSelector","useStore"];let r=!1;for(const a of e)if(hr(s)>0&&(s[a]&&(r||(console.warn("As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`"),r=!0)),n[a]=s[a]),"function"!=typeof n[a])throw new Error("production"===process.env.NODE_ENV?t(36):`When using custom hooks for context, all ${e.length} hooks need to be provided: ${e.join(", ")}.\nHook ${a} was either not provided or not a function.`)}return{name:Ar,init(s,{serializeQueryArgs:o},i){const c=s,{buildQueryHooks:u,buildInfiniteQueryHooks:d,buildMutationHook:l,usePrefetch:p}=function({api:e,moduleOptions:{batch:n,hooks:{useDispatch:r,useSelector:a,useStore:s},unstable__sideEffectsInRender:o,createSelector:i},serializeQueryArgs:c,context:u}){const d=o?e=>e():O,l=e=>e.current?.unsubscribe?.(),p=u.endpointDefinitions;return{buildQueryHooks:function(a){const s=(e,n={})=>{const[r]=g(a,e,n);return y(r),R(()=>({refetch:()=>function(e){if(!e.current)throw new Error("production"===process.env.NODE_ENV?t(38):"Cannot refetch a query that has not been started yet.");return e.current.refetch()}(r)}),[r])},o=({refetchOnReconnect:t,refetchOnFocus:s,pollingInterval:o=0,skipPollingIfUnfocused:i=!1}={})=>{const{initiate:c}=e.endpoints[a],u=r(),[p,f]=k(yr),h=C(void 0),g=_r({refetchOnReconnect:t,refetchOnFocus:s,pollingInterval:o,skipPollingIfUnfocused:i});d(()=>{const e=h.current?.subscriptionOptions;g!==e&&h.current?.updateSubscriptionOptions(g)},[g]);const m=C(g);d(()=>{m.current=g},[g]);const y=I(function(e,t=!1){let r;return n(()=>{l(h),h.current=r=u(c(e,{subscriptionOptions:m.current,forceRefetch:!t})),f(e)}),r},[u,c]),v=I(()=>{h.current?.queryCacheKey&&u(e.internalActions.removeQueryResult({queryCacheKey:h.current?.queryCacheKey}))},[u]);return O(()=>()=>{l(h)},[]),O(()=>{p===yr||h.current||y(p,!0)},[p,y]),R(()=>[y,p,{reset:v}],[y,p,v])},i=m(a,f);return{useQueryState:i,useQuerySubscription:s,useLazyQuerySubscription:o,useLazyQuery(e){const[t,n,{reset:r}]=o(e),a=i(n,{...e,skip:n===yr}),s=R(()=>({lastArg:n}),[n]);return R(()=>[t,{...a,reset:r},s],[t,a,r,s])},useQuery(e,t){const n=s(e,t),r=i(e,{selectFromResult:e===Jn||t?.skip?void 0:Tr,...t}),a=Er(r,...Ir);return A(a),R(()=>({...r,...n}),[r,n])}}},buildInfiniteQueryHooks:function(e){const r=(r,a={})=>{const[s,o,i,c]=g(e,r,a),u=C(c);d(()=>{u.current=c},[c]);const p=_r(a.refetchCachedPages),f=I(function(e,t){let r;return n(()=>{l(s),s.current=r=o(i(e,{subscriptionOptions:u.current,direction:t}))}),r},[s,o,i]);y(s);const h=vr(a.skip?Jn:r),m=I(e=>{if(!s.current)throw new Error("production"===process.env.NODE_ENV?t(38):"Cannot refetch a query that has not been started yet.");return s.current.refetch({refetchCachedPages:e?.refetchCachedPages??p})},[s,p]);return R(()=>({trigger:f,refetch:m,fetchNextPage:()=>f(h,"forward"),fetchPreviousPage:()=>f(h,"backward")}),[m,f,h])},a=m(e,h);return{useInfiniteQueryState:a,useInfiniteQuerySubscription:r,useInfiniteQuery(e,t){const{refetch:n,fetchNextPage:s,fetchPreviousPage:o}=r(e,t),i=a(e,{selectFromResult:e===Jn||t?.skip?void 0:Tr,...t}),c=Er(i,...Ir,"hasNextPage","hasPreviousPage");return A(c),R(()=>({...i,fetchNextPage:s,fetchPreviousPage:o,refetch:n}),[i,s,o,n])}}},buildMutationHook:function(t){return({selectFromResult:s,fixedCacheKey:o}={})=>{const{select:c,initiate:u}=e.endpoints[t],d=r(),[l,p]=k();O(()=>()=>{l?.arg.fixedCacheKey||l?.reset()},[l]);const f=I(function(e){const t=d(u(e,{fixedCacheKey:o}));return p(t),t},[d,u,o]),{requestId:h}=l||{},g=R(()=>c({fixedCacheKey:o,requestId:l?.requestId}),[o,l,c]),m=R(()=>s?i([g],s):g,[s,g]),y=a(m,E),v=null==o?l?.arg.originalArgs:void 0,_=I(()=>{n(()=>{l&&p(void 0),o&&d(e.internalActions.removeMutationResult({requestId:h,fixedCacheKey:o}))})},[d,o,l,h]),b=Er(y,...Ir,"endpointName");A(b);const S=R(()=>({...y,originalArgs:v,reset:_}),[y,v,_]);return R(()=>[f,S],[f,S])}},usePrefetch:function(t,n){const a=r(),s=_r(n);return I((n,r)=>a(e.util.prefetch(t,n,{...s,...r})),[t,a,s])}};function f(e,t,n){if(t?.endpointName&&e.isUninitialized){const{endpointName:e}=t,r=p[e];n!==Jn&&c({queryArgs:t.originalArgs,endpointDefinition:r,endpointName:e})===c({queryArgs:n,endpointDefinition:r,endpointName:e})&&(t=void 0)}let r=e.isSuccess?e.data:t?.data;void 0===r&&(r=e.data);const a=void 0!==r,s=e.isLoading,o=(!t||t.isLoading||t.isUninitialized)&&!a&&s,i=e.isSuccess||a&&(s&&!t?.isError||e.isUninitialized);return{...e,data:r,currentData:e.data,isFetching:s,isLoading:o,isSuccess:i}}function h(e,t,n){if(t?.endpointName&&e.isUninitialized){const{endpointName:e}=t,r=p[e];n!==Jn&&c({queryArgs:t.originalArgs,endpointDefinition:r,endpointName:e})===c({queryArgs:n,endpointDefinition:r,endpointName:e})&&(t=void 0)}let r=e.isSuccess?e.data:t?.data;void 0===r&&(r=e.data);const a=void 0!==r,s=e.isLoading,o=(!t||t.isLoading||t.isUninitialized)&&!a&&s,i=e.isSuccess||s&&a;return{...e,data:r,currentData:e.data,isFetching:s,isLoading:o,isSuccess:i}}function g(n,a,{refetchOnReconnect:s,refetchOnFocus:o,refetchOnMountOrArgChange:i,skip:c=!1,pollingInterval:u=0,skipPollingIfUnfocused:l=!1,...f}={}){const{initiate:h}=e.endpoints[n],g=r(),m=C(void 0);if(!m.current){const n=g(e.internalActions.internal_getRTKQSubscriptions());if("production"!==process.env.NODE_ENV&&("object"!=typeof n||"string"==typeof n?.type))throw new Error("production"===process.env.NODE_ENV?t(37):`Warning: Middleware for RTK-Query API at reducerPath "${e.reducerPath}" has not been added to the store.\n You must add the middleware for RTK-Query to function correctly!`);m.current=n}const y=vr(c?Jn:a),v=_r({refetchOnReconnect:s,refetchOnFocus:o,pollingInterval:u,skipPollingIfUnfocused:l}),_=_r(f.initialPageParam),b=_r(f.refetchCachedPages),S=C(void 0);let{queryCacheKey:w,requestId:T}=S.current||{},E=!1;w&&T&&(E=m.current.isRequestSubscribed(w,T));const I=!E&&void 0!==S.current;return d(()=>{I&&(S.current=void 0)},[I]),d(()=>{const e=S.current;if("undefined"!=typeof process&&process,y===Jn)return e?.unsubscribe(),void(S.current=void 0);const t=S.current?.subscriptionOptions;if(e&&e.arg===y)v!==t&&e.updateSubscriptionOptions(v);else{e?.unsubscribe();const t=g(h(y,{subscriptionOptions:v,forceRefetch:i,...gr(p[n])?{initialPageParam:_,refetchCachedPages:b}:{}}));S.current=t}},[g,h,i,y,v,I,_,b,n]),[S,g,h,v]}function m(t,n){return(r,{skip:o=!1,selectFromResult:c}={})=>{const{select:u}=e.endpoints[t],d=vr(o?Jn:r),l=C(void 0),p=R(()=>i([u(d),(e,t)=>t,e=>d],n,{memoizeOptions:{resultEqualityCheck:E}}),[u,d]),f=R(()=>c?i([p],c,{devModeChecks:{identityFunctionCheck:"never"}}):p,[p,c]),h=a(e=>f(e,l.current),E),g=s(),m=p(g.getState(),l.current);return wr(()=>{l.current=m},[m]),h}}function y(e){O(()=>()=>{l(e),e.current=void 0},[e])}}({api:s,moduleOptions:{batch:e,hooks:n,unstable__sideEffectsInRender:a,createSelector:r},serializeQueryArgs:o,context:i});return mr(c,{usePrefetch:p}),mr(i,{batch:e}),{injectEndpoint(e,t){if("query"===t.type){const{useQuery:t,useLazyQuery:n,useLazyQuerySubscription:r,useQueryState:a,useQuerySubscription:o}=u(e);mr(c.endpoints[e],{useQuery:t,useLazyQuery:n,useLazyQuerySubscription:r,useQueryState:a,useQuerySubscription:o}),s[`use${fr(e)}Query`]=t,s[`useLazy${fr(e)}Query`]=n}if("mutation"===t.type){const t=l(e);mr(c.endpoints[e],{useMutation:t}),s[`use${fr(e)}Mutation`]=t}else if(gr(t)){const{useInfiniteQuery:t,useInfiniteQuerySubscription:n,useInfiniteQueryState:r}=d(e);mr(c.endpoints[e],{useInfiniteQuery:t,useInfiniteQuerySubscription:n,useInfiniteQueryState:r}),s[`use${fr(e)}InfiniteQuery`]=t}}}}}})());let kr=0;function Or(e){return null!==e&&"object"==typeof e}function Cr(e){return Or(e)?"string"==typeof e.error_message?e.error_message:"string"==typeof e.message?e.message:null:null}const Nr="Something went wrong. Please try again.";function Pr(e){const t=e?.status;return!("number"==typeof t&&t>=400&&t<500)}function xr(e,t){return Pr(e)?Nr:function(e){if(!Or(e))return null;if("string"==typeof e.message){try{const t=Cr(JSON.parse(e.message));if(t)return t}catch{}return e.message}return Cr(e.data)??Cr(e.data?.data)}(e)??t??"An unexpected error occurred."}const qr={NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",PARSE_ERROR:"PARSE_ERROR",TOKEN_EXPIRED:"TOKEN_EXPIRED",TOKEN_REFRESH_FAILED:"TOKEN_REFRESH_FAILED",UNAUTHORIZED:"UNAUTHORIZED",FORBIDDEN:"FORBIDDEN",NOT_FOUND:"NOT_FOUND",VALIDATION_ERROR:"VALIDATION_ERROR",SERVER_ERROR:"SERVER_ERROR",UNKNOWN:"UNKNOWN"};let Mr=null;const Dr=function(e){const{name:t,innerBaseQuery:n,requestInterceptors:r,responseInterceptors:a,defaultOptions:s}=e;return async(e,o,i)=>{let c,u;if("string"==typeof e)c={url:e};else{const{_bridge:t,...n}=e;c=n,u=t}const d={...i,bridge:{...s,...i?.bridge,...u}},l={bridgeName:t,requestId:(p=t,kr+=1,`${p}-${kr}`),startTime:Date.now(),api:o,extraOptions:d};var p;const f=async e=>{let t=e;for(const e of r)t=await e(t,l);return n(t,o,d)};let h=await f(c);for(const e of a)h=await e(h,c,l,f);return h}}({name:"apiBridge",innerBaseQuery:async(e,t,n)=>function({baseUrl:e,prepareHeaders:t=e=>e,fetchFn:n=dn,paramsSerializer:r,isJsonContentType:a=pn,jsonContentType:s="application/json",jsonReplacer:o,timeout:i,responseHandler:c,validateStatus:u,...d}={}){return"undefined"==typeof fetch&&n===dn&&console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments."),async(f,h,g)=>{const{getState:m,extra:y,endpoint:v,forced:_,type:b}=h;let S,{url:w,headers:T=new Headers(d.headers),params:E,responseHandler:I=c??"json",validateStatus:A=u??ln,timeout:R=i,...k}="string"==typeof f?{url:f}:f,O={...d,signal:R?un(h.signal,cn(R)):h.signal,...k};T=new Headers(fn(T)),O.headers=await t(T,{getState:m,arg:f,extra:y,endpoint:v,forced:_,type:b,extraOptions:g})||T;const C="object"==typeof(N=O.body)&&(l(N)||Array.isArray(N)||"function"==typeof N.toJSON);var N;if(null==O.body||C||"string"==typeof O.body||O.headers.delete("content-type"),!O.headers.has("content-type")&&C&&O.headers.set("content-type",s),C&&a(O.headers)&&(O.body=JSON.stringify(O.body,o)),O.headers.has("accept")||("json"===I?O.headers.set("accept","application/json"):"text"===I&&O.headers.set("accept","text/plain, text/html, */*")),E){const e=~w.indexOf("?")?"&":"?";w+=e+(r?r(E):new URLSearchParams(fn(E)))}w=function(e,t){if(!e)return t;if(!t)return e;if(function(e){return new RegExp("(^|:)//").test(e)}(t))return t;const n=e.endsWith("/")||!t.startsWith("?")?"/":"";return e=(e=>e.replace(/\/$/,""))(e),`${e}${n}${t=(e=>e.replace(/^\//,""))(t)}`}(e,w);const P=new Request(w,O);let x;S={request:new Request(w,O)};try{x=await n(P)}catch(e){return{error:{status:(e instanceof Error||"undefined"!=typeof DOMException&&e instanceof DOMException)&&"TimeoutError"===e.name?"TIMEOUT_ERROR":"FETCH_ERROR",error:String(e)},meta:S}}const q=x.clone();let M;S.response=q;let D="";try{let e;if(await Promise.all([p(x,I).then(e=>M=e,t=>e=t),q.text().then(e=>D=e,()=>{})]),e)throw e}catch(e){return{error:{status:"PARSING_ERROR",originalStatus:x.status,data:D,error:String(e)},meta:S}}return A(x,M)?{data:M,meta:S}:{error:{status:x.status,data:M},meta:S}};async function p(e,t){if("function"==typeof t)return t(e);if("content-type"===t&&(t=a(e.headers)?"json":"text"),"json"===t){const t=await e.text();return t.length?JSON.parse(t):null}return e.text()}}({baseUrl:"",prepareHeaders:e=>(e.has("Content-Type")||e.set("Content-Type","application/json"),e.has("Accept")||e.set("Accept","application/json"),e)})(e,t,n),requestInterceptors:[(e,t)=>{if(t.extraOptions.bridge?.skipAuth)return e;const n=t.api.getState(),r=n.auth?.accessToken;return r?{...e,headers:{...e.headers,Authorization:`Bearer ${r}`}}:e},(e,t)=>{const n=q(),r=t.extraOptions.bridge?.customHeaders,a=Object.keys(n).length>0,s=!!r&&Object.keys(r).length>0;return a||s?{...e,headers:{...e.headers,...n,...r??{}}}:e},(e,t)=>{if(!M()||t.extraOptions.bridge?.skipLogging)return e;const n=(e.method||"GET").toUpperCase(),r=e.url||"";return D.debug({message:`${t.bridgeName} ${n} ${r}`,api_name:t.api.endpoint,request_id:t.requestId,method:n,url:r}),e}],responseInterceptors:[async(e,t,n,r)=>{if(n.extraOptions.bridge?.skipTokenRefresh)return e;if(401!==e.error?.status)return e;const a=n.api.getState();if(!a.auth?.accessToken||!a.auth?.isAuthenticated)return e;if(!F())return n.api.dispatch(U()),e;try{const e=await async function(){return Mr||(Mr=async function(){const e=F();if(!e)return null;try{return await e()}catch{return null}}().finally(()=>{Mr=null}),Mr)}();if(e){const a=n.api.getState().auth?.accessToken;return a!==e.accessToken&&n.api.dispatch(L({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresIn:e.expiresIn})),r(t)}D.error({message:"Session cleared: token refresh failed after 401",api_name:"auth-refresh"}),n.api.dispatch(U())}catch{D.error({message:"Session cleared: token refresh threw after 401",api_name:"auth-refresh"}),n.api.dispatch(U())}return e},async(e,t,n)=>{if(!e.error)return e;const r=(a=e.error,s={url:t.url,method:t.method||"GET",timestamp:n.startTime,duration:Date.now()-n.startTime,requestId:n.requestId,bridgeName:n.bridgeName},a&&"object"==typeof a&&"status"in a?function(e,t){const n="PARSING_ERROR"===e.status,r=n?e.originalStatus:void 0,a="number"==typeof r&&r>=400?r:e.status;let s,o="Request failed",i=qr.UNKNOWN;if("data"in e)if(s=e.data,"string"==typeof e.data)o=e.data;else if(e.data&&"object"==typeof e.data){const t=e.data;o=t.message||t.error||t.detail||o}return!n&&"error"in e&&"string"==typeof e.error&&(o=e.error),401===a?i=qr.UNAUTHORIZED:403===a?i=qr.FORBIDDEN:404===a?i=qr.NOT_FOUND:422===a?i=qr.VALIDATION_ERROR:"FETCH_ERROR"===a?i=qr.NETWORK_ERROR:"TIMEOUT_ERROR"===a?i=qr.TIMEOUT:"PARSING_ERROR"===a?i=qr.PARSE_ERROR:"number"==typeof a&&a>=500&&(i=qr.SERVER_ERROR),"number"==typeof a&&a>=500&&(o=Nr),{status:a,message:o,data:s,code:i,meta:{timestamp:Date.now(),...t}}}(a,s):a instanceof Error?{status:"FETCH_ERROR",message:a.message||"An unexpected error occurred",code:qr.UNKNOWN,meta:{timestamp:Date.now(),...s}}:"string"==typeof a?{status:"CUSTOM_ERROR",message:a,code:qr.UNKNOWN,meta:{timestamp:Date.now(),...s}}:{status:"CUSTOM_ERROR",message:"An unknown error occurred",data:a,code:qr.UNKNOWN,meta:{timestamp:Date.now(),...s}});var a,s;return{...e,error:{...e.error,...r}}},async(e,t,n)=>{if(!e.error||n.extraOptions.bridge?.skipErrorToast)return e;const{status:r}=e.error;return"FETCH_ERROR"===r?(Q("Network error. Please check your connection."),e):"TIMEOUT_ERROR"===r?(Q("Request timed out. Please try again."),e):"number"==typeof r&&r>=500?(Q(Nr),e):e},async(e,t,n,r)=>{if(!e.error)return e;const{status:a}=e.error;if("FETCH_ERROR"!==a&&"TIMEOUT_ERROR"!==a)return e;const s=n.extraOptions.bridge?.retry,o=s?.maxRetries??1,i=s?.backoffMs??1e3,c=parseInt(t.headers?.["X-Bridge-Retry-Count"]||"0",10);if(c>=o)return e;const u=i*Math.pow(2,c);return await new Promise(e=>setTimeout(e,u)),r({...t,headers:{...t.headers,"X-Bridge-Retry-Count":String(c+1)}})},async(e,t,n)=>{const r=n.extraOptions.bridge?.skipLogging,a=Date.now()-n.startTime,s=(t.method||"GET").toUpperCase(),o=t.url||"",i=e.meta?.response,c=e.error?e.error.status:i?.status??"OK",u=i?.headers?.get?.("x-request-id")??void 0;return e.error?D.error({message:`${n.bridgeName} ${s} ${o} failed (${c})`,api_name:n.api.endpoint,request_id:u??n.requestId,method:s,url:o,status:c,duration:a,error_data:e.error.data}):M()&&!r&&D.debug({message:`${n.bridgeName} ${s} ${o} ${c} ${a}ms`,api_name:n.api.endpoint,request_id:u??n.requestId,method:s,url:o,status:c,duration:a}),e}]});function Qr(){return j()}let Fr=0;async function Ur(e){const{url:t,method:n="GET",body:r,headers:a={},skipAuth:s=!1,skipLogging:o=!1,skipContentType:i=!1,responseHandler:c="json",signal:u,keepalive:d}=e;Fr+=1;const l=`fetch-${Fr}`,p=Date.now(),f=n.toUpperCase(),h={...a};if(Object.assign(h,q()),!s){const e=Qr();e&&(h.Authorization=`Bearer ${e}`)}let g;i||h["Content-Type"]||(h["Content-Type"]="application/json"),h.Accept||(h.Accept="application/json"),g=null==r?void 0:"string"==typeof r||r instanceof FormData||r instanceof Blob||r instanceof ArrayBuffer?r:JSON.stringify(r),M()&&!o&&D.debug({message:`bridgedFetch ${f} ${t}`,api_name:"bridgedFetch",request_id:l,method:f,url:t});try{const e=await fetch(t,{method:n,headers:h,body:g,signal:u,keepalive:d}),r=Date.now()-p;if(!e.ok){let n;try{n=await e.json()}catch{try{n=await e.text()}catch{n=`HTTP ${e.status}`}}const a=e.headers.get("x-request-id")??void 0;return o||D.error({message:`bridgedFetch ${f} ${t} failed (${e.status})`,api_name:"bridgedFetch",request_id:a??l,method:f,url:t,status:e.status,duration:r,error_data:n}),{error:{status:e.status,data:n},response:e}}let a;if("blob"===c)a=await e.blob();else if("text"===c)a=await e.text();else{const t=await e.text();a=t?JSON.parse(t):void 0}if(M()&&!o){const n=e.headers.get("x-request-id")??void 0;D.debug({message:`bridgedFetch ${f} ${t} ${e.status} ${r}ms`,api_name:"bridgedFetch",request_id:n??l,method:f,url:t,status:e.status,duration:r})}return{data:a,response:e}}catch(e){const n=Date.now()-p;return o||D.error({message:`bridgedFetch ${f} ${t} network error`,api_name:"bridgedFetch",request_id:l,method:f,url:t,status:"FETCH_ERROR",duration:n,error_message:e instanceof Error?e.message:"Network error"}),{error:{status:"FETCH_ERROR",data:e instanceof Error?e.message:"Network error"}}}}const Lr=()=>"",jr=Rr({reducerPath:"chatApi",baseQuery:Dr,keepUnusedDataFor:0,tagTypes:["chat","toolServers"],endpoints:e=>({getConversationHistory:e.query({query:({skip:e=0,limit:t=20})=>({url:`${$.CONVERSATIONS()}`,method:"GET",params:{skip:e,limit:t}}),transformResponse:e=>e?.data??{conversations:[]},providesTags:["chat"]}),getConversationById:e.query({query:({conversationId:e,skip:t,limit:n})=>({url:`${$.CONVERSATIONS()}/${e}`,method:"GET",params:{...void 0!==t&&{skip:t},...void 0!==n&&{limit:n}}}),transformResponse:e=>e?.data??null,providesTags:["chat"]}),createConversatons:e.mutation({query:e=>({url:`${$.CONVERSATIONS()}`,method:"POST",body:e.body||{}}),transformResponse:e=>e?.data??[],extraOptions:{bridge:{skipErrorToast:!0}}}),transcribeAudio:e.mutation({queryFn:async({audioFile:e})=>{const t=new FormData;t.append("file",e);const{data:n,error:r}=await Ur({url:$.TRANSCRIBE,method:"POST",body:t,skipContentType:!0});return r?{error:r}:{data:n}}}),getToolServers:e.query({query:()=>({url:$.TOOL_SERVERS,method:"GET"}),transformResponse:e=>e?.data??{tool_servers:[]},providesTags:["toolServers"]}),startToolServerOAuth:e.mutation({query:e=>({url:$.TOOL_SERVER_AUTH_START(e),method:"POST"}),transformResponse:e=>e?.data??{authorize_url:""}}),deleteToolServerConnection:e.mutation({query:e=>({url:$.TOOL_SERVER_AUTH_CONNECTION(e),method:"DELETE"}),invalidatesTags:["toolServers"]}),exchangeOAuthCode:e.mutation({query:({code:e,state:t})=>({url:$.TOOL_SERVERS_SIGN_IN_EXCHANGE,method:"POST",body:{code:e,state:t}}),invalidatesTags:["toolServers"]}),deleteConversation:e.mutation({query:({conversationId:e})=>({url:`${$.CONVERSATIONS()}/${e}`,method:"DELETE"}),extraOptions:{bridge:{skipErrorToast:!0}}})})}),{useCreateConversatonsMutation:$r,useTranscribeAudioMutation:zr,useExchangeOAuthCodeMutation:Kr,useGetConversationHistoryQuery:Hr,useLazyGetConversationByIdQuery:Gr,useDeleteConversationMutation:Br,useGetToolServersQuery:Vr,useStartToolServerOAuthMutation:Wr,useDeleteToolServerConnectionMutation:Jr}=jr,Xr={bridge:{skipErrorToast:!0,skipTokenRefresh:!0}},Zr=Rr({reducerPath:"brandingApi",baseQuery:Dr,keepUnusedDataFor:0,endpoints:e=>({getBranding:e.query({query:e=>({url:$.BRANDING,method:"GET",_bridge:{skipAuth:!e}}),extraOptions:Xr})})}),{useGetBrandingQuery:Yr}=Zr,ea={bridge:{skipErrorToast:!0,skipTokenRefresh:!0,retry:{maxRetries:0}}},ta=Rr({reducerPath:"configApi",baseQuery:Dr,keepUnusedDataFor:1/0,endpoints:e=>({getConfig:e.query({query:()=>({url:$.CONFIG,method:"GET",_bridge:{skipAuth:!0},timeout:z.CONFIG_TIMEOUT_MS}),extraOptions:ea})})}),{useGetConfigQuery:na}=ta,ra=Rr({reducerPath:"profileApi",baseQuery:Dr,keepUnusedDataFor:0,tagTypes:["profile"],endpoints:e=>({getProfile:e.query({query:()=>({url:$.PROFILE,method:"GET"}),extraOptions:{bridge:{skipErrorToast:!0}},transformResponse:e=>e?.data??null,providesTags:["profile"]}),updateProfile:e.mutation({query:e=>({url:$.PROFILE,method:"PUT",body:e}),async onQueryStarted(e,{dispatch:t,queryFulfilled:n}){try{await n,t(ra.util.updateQueryData("getProfile",void 0,t=>{t&&(void 0!==e.name&&(t.name=e.name),void 0!==e.phone&&(t.phone=e.phone))}))}catch{}}}),deleteAccount:e.mutation({query:()=>({url:$.AUTH_ME,method:"DELETE"})})})}),{useGetProfileQuery:aa,useUpdateProfileMutation:sa,useDeleteAccountMutation:oa}=ra,ia={[jr.reducerPath]:jr.reducer,[Zr.reducerPath]:Zr.reducer,[ta.reducerPath]:ta.reducer,[ra.reducerPath]:ra.reducer},ca=[jr.middleware,Zr.middleware,ta.middleware,ra.middleware],ua={isAgentWorking:!0,statusText:null,responseStartTime:null,messageQueue:[]},da=s({name:"chat",initialState:ua,reducers:{setIsAgentWorking(e,t){e.isAgentWorking=t.payload},setStatusText(e,t){e.statusText=t.payload},setResponseStartTime(e,t){e.responseStartTime=t.payload},enqueueMessage(e,t){e.messageQueue.push(t.payload)},dequeueMessage(e){e.messageQueue.shift()},clearMessageQueue(e){e.messageQueue=[]},resetChatState:()=>ua},extraReducers:e=>{e.addMatcher(i(U,K),()=>ua)}}),{setIsAgentWorking:la,setStatusText:pa,setResponseStartTime:fa,enqueueMessage:ha,dequeueMessage:ga,clearMessageQueue:ma,resetChatState:ya}=da.actions,va=da.reducer,_a={activeConversationId:null,titles:{}},ba=s({name:"conversations",initialState:_a,reducers:{setActiveConversationId(e,t){e.activeConversationId=t.payload},upsertConversationTitle(e,t){const{id:n,title:r}=t.payload;n&&r.trim()&&(e.titles[n]=r)}},extraReducers:e=>{e.addMatcher(i(U,K),()=>_a)}}),{setActiveConversationId:Sa,upsertConversationTitle:wa}=ba.actions,Ta=ba.reducer;let Ea=null;function Ia(e){Ea=e}function Aa(){Ea=null}const Ra=()=>{if(!Ea)return{};const e=Ea(),t=e.auth.user?.id,n=e.auth.selectedOrgId??void 0,r=e.conversations.activeConversationId??void 0;return{...t?{user_id:t}:{},...n?{org_id:n}:{},...r?{conversation_id:r}:{}}},ka=d({...ia,auth:G,chat:va,conversations:Ta,indicator:H}),Oa={ignoredPaths:["chatApi.queries","chatApi.mutations","brandingApi.queries","brandingApi.mutations","configApi.queries","configApi.mutations","profileApi.queries","profileApi.mutations"],ignoredActions:["chatApi/executeQuery/fulfilled","chatApi/executeMutation/fulfilled","brandingApi/executeQuery/rejected","brandingApi/executeQuery/fulfilled","configApi/executeQuery/rejected","configApi/executeQuery/fulfilled","profileApi/executeQuery/rejected","profileApi/executeQuery/fulfilled","profileApi/executeMutation/rejected","profileApi/executeMutation/fulfilled"],ignoredActionPaths:["payload.error","error","meta.baseQueryMeta","meta.arg.originalArgs.audioFile"]},Ca=_({reducer:ka,middleware:e=>e({serializableCheck:Oa}).prepend(B.middleware).concat(ca)});var Na;Na=Ca.dispatch,function(){const[e,t,n,r]=[Sn,wn,Tn,En].map(e=>()=>Na(e())),a=()=>{"visible"===window.document.visibilityState?e():t()};if(!In&&"undefined"!=typeof window&&window.addEventListener){let t=function(e){Object.entries(s).forEach(([t,n])=>{e?window.addEventListener(t,n,!1):window.removeEventListener(t,n)})};const s={[vn]:e,[bn]:a,[mn]:n,[yn]:r};t(!0),In=!0}}(),V(()=>Ca.getState().auth.accessToken),W(()=>Ca.getState().auth.tokenExpiresAt),Ia(()=>Ca.getState());const Pa=()=>{const e=na(),{isError:t,isFetching:n,refetch:r}=e,a=C(!1);return O(()=>{!t||n||a.current||(a.current=!0,r())},[t,n,r]),e},xa=P(void 0),qa=()=>{const e=x(xa);if(!e)throw new Error("useProtocol must be used within a ProtocolProvider");return e},Ma="mtx",Da=5;var Qa=(e=>(e.START="start",e.TEXT="text",e.WIDGET="widget",e.STATUS_UPDATE="status_update",e.CLEAR_STATUS="clear_status",e.PAYMENT="payment",e.SIGN_IN="sign_in",e.CONVERSATION_TITLE="conversation_title",e.END="end",e))(Qa||{});let Fa=class extends Error{constructor(e){super(),this.reopen=e}};class Ua{type="mtx";config;constructor(e){this.config=e}streamMessage(e){const t=e.debugMode?this.config.getDebugUrl():this.config.getStreamUrl(e.conversationId);return this.createStreamHandle(t,{message:e.message,...e.body||{}})}streamInitial(e){const t=this.config.getInitialStreamUrl(e.conversationId);return this.createStreamHandle(t,{...e.body||{}})}normalizeEvent(e){const{parsed:t,eventType:n,isStreamEnd:r,requestId:a}=e;if(r)return{type:"stream_end",data:{isEnd:!0},timestamp:Date.now(),requestId:a};const s=(n||"").toLowerCase(),{type:o,data:i}=this.mapSSEEvent(s,t);return{type:o,data:i,timestamp:Date.now(),requestId:a}}mapSSEEvent(e,t){switch(e){case"text":return{type:"text",data:{text:t.token||""}};case"widget":return{type:"widget",data:{widget:t}};case"status_update":return{type:"status_update",data:{statusText:t.text||""}};case"clear_status":return{type:"status_update",data:{statusText:""}};case"payment":return{type:"payment",data:{payment:t}};case"sign_in":return{type:"sign_in",data:{signIn:{authorize_url:t.authorize_url,state:t.state}}};case"conversation_title":return{type:"conversation_title",data:{conversationTitle:t.text||""}};default:return t.token?{type:"text",data:{text:t.token}}:t.text?{type:"text",data:{text:t.text}}:{type:"text",data:{text:""}}}}createStreamHandle(e,t){let n=new AbortController,r=0,a="",s=!1;const o=[];let i=null,c=!1,u=null;const d=e=>{i?i.onEvent(e):o.push(e)},l=e=>{i?i.onError(e):u=e},p=()=>{c=!0,i&&i.onComplete()},f=async()=>{try{await(this.config.ensureFreshToken?.()),await Se(e,{method:"POST",headers:{"Content-Type":"application/json",...this.config.getAuthToken()?{Authorization:`Bearer ${this.config.getAuthToken()}`}:{},...this.config.getCustomHeaders()},body:JSON.stringify(t),signal:n.signal,onopen:async e=>{if(401===e.status&&!s){s=!0,D.warn({message:"MTX SSE rejected with 401 — refreshing token",api_name:"mtx-sse"});const e=await(this.config.forceRefreshToken?.());throw e||(D.error({message:"MTX SSE 401 refresh failed — clearing session",api_name:"mtx-sse"}),this.config.onAuthExpired?.()),new Fa(Boolean(e))}const t=e.headers.get("x-request-id");t&&(a=t)},onmessage:e=>{if("[DONE]"===e.data)return;const t=(e.event||"").toLowerCase(),n=new Set(Object.values(Qa));if("status_update"!==t&&"clear_status"!==t||D.debug({message:"MTX SSE status event received",api_name:"mtx-sse",sse_event:t,allowed:n.has(t)}),!t||n.has(t))try{const n=t===Qa.END;let r;try{r=JSON.parse(e.data)}catch{return}if(!n&&t!==Qa.CLEAR_STATUS&&r&&"object"==typeof r&&0===Object.keys(r).length)return;const s=this.normalizeEvent({parsed:r,eventType:e.event,isStreamEnd:n,requestId:r.request_id||a||""});d(s),n&&"stream_end"!==s.type&&d({type:"stream_end",data:{isEnd:!0},timestamp:Date.now(),requestId:a})}catch(e){D.error({message:"Failed to parse MTX SSE message",api_name:"mtx-sse",error_message:e instanceof Error?e.message:String(e)})}else D.debug({message:"Ignoring unrecognized MTX SSE event type",api_name:"mtx-sse",sse_event:e.event})},onerror:e=>{if(e instanceof Fa)throw e;if(r++,r>=5)throw n.abort(),l(e instanceof Error?e:new Error(String(e))),e;throw e},onclose:()=>{p()},openWhenHidden:!0})}catch(e){if(e instanceof Fa)return e.reopen&&!n.signal.aborted?(n=new AbortController,f()):void(c||p());c||(n.signal.aborted||l(e instanceof Error?e:new Error(String(e))),p())}};return f(),{subscribe(e){i=e;for(const t of o)e.onEvent(t);return o.length=0,u&&(e.onError(u),u=null),c&&e.onComplete(),()=>{i=null}},abort(){n.abort()}}}}class La extends Error{constructor(e){super(),this.reopen=e}}class ja{type="agui";config;constructor(e){this.config=e}streamMessage(e){const t=e.debugMode?this.config.getDebugUrl():this.config.getStreamUrl(e.conversationId);return this.createStreamHandle(t,{message:e.message,...e.body||{}})}streamInitial(e){const t=this.config.getInitialStreamUrl(e.conversationId);return this.createStreamHandle(t,{...e.body||{}})}normalizeEvent(e){const t=e,{type:n,data:r}=this.mapEventType(t);return{type:n,data:r,timestamp:Date.now(),requestId:t.runId||""}}mapEventType(e){switch((e.type||"").toUpperCase()){case"TEXT_MESSAGE_CONTENT":return{type:"text",data:{text:e.delta||""}};case"TEXT_MESSAGE_END":case"RUN_FINISHED":return{type:"stream_end",data:{isEnd:!0}};case"RUN_ERROR":return{type:"error",data:{error:e.error||"Unknown AG-UI run error"}};case"STATE_SNAPSHOT":return this.mapStateSnapshot(e);case"CUSTOM":return this.mapCustomEvent(e);case"PAYMENT":{const t=e?.value?.data??e.payload;return t?.provider&&t?.config&&J(t)&&("chargebee"!==t.provider||t.config?.hosted_page_url)?{type:"payment",data:{payment:t}}:{type:"text",data:{text:""}}}case"CONVERSATION_TITLE":{const t=e?.value?.data??e.payload,n=t?.text??t?.title;return{type:"conversation_title",data:{conversationTitle:"string"==typeof n?n:""}}}default:return{type:"text",data:{text:""}}}}mapStateSnapshot(e){return{type:"widget",data:{widget:e.state||e.payload||{}}}}mapCustomEvent(e){const t=e.payload||e?.value?.data||{},n=e.name||"custom";return D.debug({message:"AG-UI mapCustomEvent",api_name:"agui-sse",event_name:n}),"widget"===n?{type:"widget",data:{widget:{eventName:n,...e?.value?.data}}}:Object.keys(t).length>0?{type:"widget",data:{widget:{eventName:e.eventName,...t}}}:{type:"text",data:{text:""}}}createStreamHandle(e,t){let n=new AbortController,r=0,a="",s=!1;const o=[];let i=null,c=!1,u=null;const d=e=>{i?i.onEvent(e):o.push(e)},l=e=>{i?i.onError(e):u=e},p=()=>{c=!0,i&&i.onComplete()},f=async()=>{try{await(this.config.ensureFreshToken?.()),await Se(e,{method:"POST",headers:{"Content-Type":"application/json",...this.config.getAuthToken()?{Authorization:`Bearer ${this.config.getAuthToken()}`}:{},...this.config.getCustomHeaders()},body:JSON.stringify(t),signal:n.signal,onopen:async e=>{if(401===e.status&&!s){s=!0,D.warn({message:"AG-UI SSE rejected with 401 — refreshing token",api_name:"agui-sse"});const e=await(this.config.forceRefreshToken?.());throw e||(D.error({message:"AG-UI SSE 401 refresh failed — clearing session",api_name:"agui-sse"}),this.config.onAuthExpired?.()),new La(Boolean(e))}const t=e.headers.get("x-request-id");t&&(a=t)},onmessage:e=>{D.debug({message:"AG-UI SSE event",api_name:"agui-sse",sse_event:e.event});const t=(e.event||"").toLowerCase(),n=new Set(Object.values(Qa));if(!t||n.has(t))if(t!==Qa.END){if("[DONE]"!==e.data)try{let n;try{n=JSON.parse(e.data)}catch(t){return void D.error({message:"AG-UI JSON parse error",api_name:"agui-sse",error_message:t instanceof Error?t.message:String(t),raw_data:e.data})}if(n&&"object"==typeof n&&0===Object.keys(n).length)return;n.runId&&(a=n.runId);const r=t===Qa.CONVERSATION_TITLE?{...n,type:"CONVERSATION_TITLE",payload:n,runId:n.runId||a}:{...n,runId:n.runId||a},s=this.normalizeEvent(r);d(s)}catch(e){D.error({message:"Failed to handle AG-UI message",api_name:"agui-sse",error_message:e instanceof Error?e.message:String(e)})}}else d(this.normalizeEvent({type:"RUN_FINISHED",runId:a}));else D.debug({message:"AG-UI ignoring unknown SSE event type",api_name:"agui-sse",sse_event:e.event})},onerror:e=>{if(e instanceof La)throw e;if(r++,r>=5)throw n.abort(),l(e instanceof Error?e:new Error(String(e))),e;throw e},onclose:()=>{p()},openWhenHidden:!0})}catch(e){if(e instanceof La)return e.reopen&&!n.signal.aborted?(n=new AbortController,f()):void(c||p());c||(n.signal.aborted||l(e instanceof Error?e:new Error(String(e))),p())}};return f(),{subscribe(e){i=e;for(const t of o)e.onEvent(t);return o.length=0,u&&(e.onError(u),u=null),c&&e.onComplete(),()=>{i=null}},abort(){n.abort()}}}}function $a(e,t){switch(e){case"mtx":return new Ua(t);case"agui":return new ja(t);default:throw new Error(`Unknown protocol type: "${e}". Supported types: mtx, agui`)}}function za(e={}){return{getAuthToken:()=>Qr(),getCustomHeaders:()=>q(),onAuthExpired:e.onAuthExpired,getStreamUrl:e=>$.CONVERSATION_STREAM(e),getInitialStreamUrl:e=>$.CONVERSATION_START(e),getDebugUrl:()=>$.DEBUG,ensureFreshToken:async()=>{X(Z())&&await(F()?.())},forceRefreshToken:async()=>Boolean(await(F()?.()))}}class Ka{segments=[];error="";requestId="";statusText="";streamComplete=!1;startTimestamp=null;processEvent(e){null===this.startTimestamp&&(this.startTimestamp=e.timestamp),e.requestId&&(this.requestId=e.requestId);const{data:t}=e;if(!("isEnd"in t))return"error"in t?(this.error=t.error,void("text"in t&&t.text&&this.appendText(t.text))):void("statusText"in t?this.statusText=t.statusText:"payment"in t||("widget"in t?this.segments.push({type:"widget",id:Y(),content:t.widget}):"text"in t&&this.appendText(t.text)));this.streamComplete=!0}appendText(e){const t=this.segments[this.segments.length-1];t&&"text"===t.type?t.text+=e:this.segments.push({type:"text",id:Y(),text:e})}toMessages(){if(0===this.segments.length){const e=Y();return[{id:e,msg_id:e,sender:"agent",message:"",timestamp:(new Date).toISOString(),tookMs:this.startTimestamp?Date.now()-this.startTimestamp:0,error:this.error||void 0,request_id:this.requestId||void 0}]}const e=(new Date).toISOString(),t=this.segments.map(t=>{const n={id:t.id,msg_id:t.id,sender:"agent",message:"",timestamp:e};switch(t.type){case"text":n.message=t.text;break;case"widget":n.widget=[t.content],n.message_type=["widget"]}return n}),n=t[t.length-1];return n.tookMs=this.startTimestamp?Date.now()-this.startTimestamp:0,n.error=this.error||void 0,n.request_id=this.requestId||void 0,t}getStatusText(){return this.statusText}isStreamComplete(){return this.streamComplete}reset(){this.segments=[],this.error="",this.requestId="",this.statusText="",this.streamComplete=!1,this.startTimestamp=null}}async function Ha(e,t){const{data:n,error:r,response:a}=await Ur({url:ee(te.LOGIN),method:"POST",body:{email:e,password:t},skipAuth:!0});if(r||!a)throw n??r;return{body:n,tokens:ne(a)}}async function Ga(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.SIGNUP),method:"POST",body:e,skipAuth:!0});if(n||!r)throw t??n;return{body:t,tokens:ne(r)}}async function Ba(e,t){await Ur({url:ee(te.LOGOUT),method:"POST",body:e,keepalive:t?.keepalive})}async function Va(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.REFRESH),method:"POST",body:e,skipAuth:!0});if(n||!r)throw t??n;return{body:t,tokens:ne(r)}}async function Wa(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.FORGOT_PASSWORD),method:"POST",body:e,skipAuth:!0});if(n||!r)throw t??n;return t?.data?.message}async function Ja(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.RESET_PASSWORD),method:"POST",body:e,skipAuth:!0});if(n||!r)throw t??n;return t?.data?.message}async function Xa(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.SSO_START),method:"POST",body:{idp_hint:e},skipAuth:!0});if(n||!r)throw t??n;return t}async function Za(e,t){const{data:n,error:r,response:a}=await Ur({url:ee(te.SSO_EXCHANGE),method:"POST",body:{code:e,state:t},skipAuth:!0});if(r||!a)throw n??r;return{body:n,tokens:ne(a)}}async function Ya(){try{const{data:e}=await Ur({url:ee(`${te.ORGANIZATIONS}?skip=0&limit=100`),skipAuth:!0});if(e?.success&&Array.isArray(e.data?.organizations))return e.data.organizations}catch{}return[]}async function es(){const e=new AbortController,t=setTimeout(()=>e.abort(),8e3);try{const{data:t,error:n,response:r}=await Ur({url:$.ORGANIZATIONS_EXISTS,method:"GET",skipAuth:!0,skipContentType:!0,signal:e.signal});return n?!r||r.status>=500?"error":"not-found":function(e){const t=e?.data?.exists;return"boolean"!=typeof t?"error":t?"exists":"not-found"}(t)}catch{return"error"}finally{clearTimeout(t)}}function ts(){const e=b(),[t,n]=k(!1);return{login:I(async t=>{n(!0);try{const{body:n,tokens:r}=await Ha(t.email,t.password);return n.success&&n.data?(e.dispatch(L({user:n.data.user,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:n.data.expiry_time})),{success:!0,data:n}):{success:!1,error:n}}catch(e){return{success:!1,error:e}}finally{n(!1)}},[e]),isLoading:t}}function ns(){const e=b(),[t,n]=k(!1);return{signup:I(async t=>{n(!0);try{const{body:n,tokens:r}=await Ga(t);return n.success&&n.data?(e.dispatch(L({user:n.data.user,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:n.data.expiry_time})),{success:!0,data:n}):{success:!1,error:n}}catch(e){return{success:!1,error:e}}finally{n(!1)}},[e]),isLoading:t}}function rs(){const e=b();return{logout:I(async()=>{const t=e.getState(),n=t.auth?.refreshToken,r=t.auth?.user?.email;if(n&&r)try{await Ba({refresh_token:n,user_id:r})}catch{}else D.warn({message:"skipping server-side logout revocation — credentials missing",api_name:"auth-logout",has_refresh_token:Boolean(n),has_user_id:Boolean(r)});e.dispatch(U())},[e])}}function as(){const e=b(),[t,n]=k(!1);return{refresh:I(async()=>{n(!0);try{const t=e.getState(),n=t.auth?.refreshToken,r=t.auth?.user?.email;if(!n||!r)return{success:!1,error:new Error("No refresh token or user available")};const{body:a,tokens:s}=await Va({refresh_token:n,user_id:r});return a?.success&&a?.data?(e.dispatch(L({accessToken:s.accessToken,refreshToken:s.refreshToken,expiresIn:a.data.expiry_time})),{success:!0,data:a}):{success:!1,error:a}}catch(e){return{success:!1,error:e}}finally{n(!1)}},[e]),isLoading:t}}function ss(e){return re({performRefresh:async()=>{const t=e.getState(),n=t.auth?.refreshToken,r=t.auth?.user?.email;if(!n||!r)return D.warn({message:"Session refresh skipped: missing stored credentials",api_name:"auth-refresh",has_refresh_token:Boolean(n),has_user_id:Boolean(r)}),null;const{body:a,tokens:s}=await Va({refresh_token:n,user_id:r});if(a?.success&&a?.data){const t={accessToken:s.accessToken,refreshToken:s.refreshToken,expiresIn:a.data.expiry_time};return D.debug({message:"Session token refreshed",api_name:"auth-refresh",refresh_token_rotated:t.refreshToken!==n}),e.dispatch(L({accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn})),t}return D.warn({message:"Session refresh rejected by server",api_name:"auth-refresh"}),null}})}const os=()=>{const{user:e,accessToken:t,tokenExpiresAt:n,isAuthenticated:r,isLoading:a}=S(e=>e.auth);return{user:e,accessToken:t,isAuthenticated:r,isLoading:a,tokenInfo:{isExpired:!!n&&oe(n),isAboutToExpire:!!n&&X(n),expiresAt:n,timeUntilExpiry:n?se(n):0,timeUntilExpiryFormatted:n?ae(se(n)):"0s"}}},is={SM:640,MD:768,LG:1024,XL:1280,XXL:1536},cs={INITIAL:["Working on it","Just a moment","Reviewing your request","Looking into that","One moment, please","Checking"],LATER:["Almost ready","Gathering the details","Finishing up","Getting things in order","Preparing your answer","Wrapping this up"],ROTATION_INTERVAL_MS:5e3,PHASE_SWITCH_MS:4e3},us={MESSAGE_PAGE_SIZE:25},ds=[500,1500,3e3],ls=28,ps="New Conversation";function fs(e){return!e.widget?.length}function hs(e){const t=Y(),n={id:`agent-${t}`,msg_id:t,sender:"agent",message:"",timestamp:e.created_at?String(e.created_at):""};return"widget"===e.type?e.content&&"object"==typeof e.content&&(n.widget=[e.content],n.message_type=["widget"]):e.content&&"string"==typeof e.content&&(n.message=e.content),n}function gs(e){const t=[];for(const n of e){const e=n.created_at?String(n.created_at):"";if("user"!==n.role)if("system"!==n.role){if("assistant"===n.role){if(n.tool_calls?.length)continue;const e=t[t.length-1];if((!n.type||"text_delta"===n.type)&&"agent"===e?.sender&&fs(e)){e.message=e.message+(n.content||"");continue}t.push(hs(n));continue}}else n.content&&t.push({id:`system-${Y()}`,sender:"system",message:"string"==typeof n.content?n.content:"",timestamp:e});else n.content&&t.push({id:`user-${Y()}`,sender:"user",message:"string"==typeof n.content?n.content:"",timestamp:e})}return t}function ms(e){return"string"==typeof e&&e.trim()?e:null}const ys=()=>{const e=w(),[t,n]=k(null),[r,a]=k([]),s=C(t),o=S(e=>t?e.conversations.titles[t]??null:null),i=I(n=>{t&&n&&e(wa({id:t,title:n}))},[t,e]);O(()=>{s.current=t,e(Sa(t))},[t,e]);const[c,u]=k(!1),[d,l]=k(0),[p,f]=k(!1),[h,g]=k(!1),m=C(!1),{protocolType:y}=qa(),[v]=$r(),[_]=Gr(),b=I(async()=>{try{u(!0);const t=await v({protocol:y,body:{}}).unwrap(),r=t?.id;if(r){n(r);const a=ms(t?.title);return a&&e(wa({id:r,title:a})),r}return Q(t?.error||"Failed to create conversations. Please try again."),null}catch(e){return Q(e?.data?.message||e?.message||"Failed to create conversations. Please try again."),null}finally{u(!1)}},[v,y,e]),T=I(async(t,r)=>{try{const s=ms(r);s&&e(wa({id:t,title:s}));const o=await _({conversationId:t,skip:0,limit:us.MESSAGE_PAGE_SIZE}).unwrap();if(o){n(t);const r=ms(o.title)??s;r&&e(wa({id:t,title:r}));const i=o.messages??[],c=Array.isArray(i)?gs(i):[];return a(c),l(i.length),f(i.length>=us.MESSAGE_PAGE_SIZE),!0}return!1}catch(e){return"AbortError"===e?.name||"AbortError"===e?.error?.name||"ABORTED"===e?.status||(D.error({message:"Failed to load conversation",api_name:"chat-conversation-load",conversation_id:t,error_message:e instanceof Error?e.message:String(e)}),Q("Failed to load conversation. Please try again.")),!1}},[_,e]),E=I(async(n=t)=>{if(!n)return null;try{const t=await _({conversationId:n,skip:0,limit:1}).unwrap(),r=ms(t?.title);return r&&e(wa({id:n,title:r})),r}catch(e){return D.error({message:"Failed to refresh conversation title",api_name:"chat-conversation-title-refresh",conversation_id:n,error_message:e instanceof Error?e.message:String(e)}),null}},[t,_,e]),A=I(async()=>{if(m.current||!t||!p)return;const e=t;g(!0),m.current=!0;try{const n=await _({conversationId:t,skip:d,limit:us.MESSAGE_PAGE_SIZE}).unwrap();if(s.current!==e)return;if(n?.messages&&Array.isArray(n.messages)){const e=gs(n.messages);l(e=>e+n.messages.length),f(n.messages.length>=us.MESSAGE_PAGE_SIZE),a(t=>{const n=new Set(t.map(e=>e.timestamp).filter(Boolean));return[...e.filter(e=>!e.timestamp||!n.has(e.timestamp)),...t]})}}catch(e){D.error({message:"Failed to load more messages",api_name:"chat-conversation-load-more",error_message:e instanceof Error?e.message:String(e)}),Q("Failed to load older messages.")}finally{g(!1),m.current=!1}},[t,d,p,_]),R=I(()=>{a([]),n(null),l(0),f(!1)},[]);return{conversationId:t,setConversationId:n,conversationTitle:o,setConversationTitle:i,messages:r,setMessages:a,isLoadingCreateConversation:c,hasMoreMessages:p,isLoadingMoreMessages:h,startSession:b,loadConversation:T,loadConversationTitle:E,loadMoreMessages:A,resetConversation:R}},vs=e=>null==e||"string"==typeof e&&""===e.trim(),_s=e=>{const t=["widget","error"],n=e=>!(null==e||"string"==typeof e&&""===e.trim()||Array.isArray(e)&&0===e.length||"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length);for(const r of t)if(n(e[r]))return!0;return!1},bs=({conversationId:e,messages:t,setMessages:n,enableTts:r=!1,userLocation:a=null,startSession:s,debugMode:o=!1,onPaymentInit:i,onSignInInit:c,onConversationTitle:u})=>{const{adapter:d}=qa(),l=w(),p=b(),[f,h]=k(""),[g,m]=k(!1),[y,v]=k(!1),_=C(i);_.current=i;const S=C(c);S.current=c;const T=C(u);T.current=u;const E=C(new Ka),A=C(null),R=C(null),N=C(!1),P=C(0),x=C(!1),q=C(null),M=C(e);M.current=e;const F=C(null),U=I((e=ie.KEEP)=>{if(l(pa(null)),l(la(!1)),e===ie.FINALIZE){const e=p.getState().chat.responseStartTime;e&&l(ce(Date.now()-e)),l(fa(null))}else e===ie.CANCEL&&l(fa(null))},[l,p]),L=I(e=>{l(la(e)),m(e),e&&v(!1)},[l]),j=I(()=>{const e=p.getState().chat.responseStartTime;return e&&l(ce(Date.now()-e)),null!==q.current&&clearTimeout(q.current),q.current=setTimeout(()=>{q.current=null,x.current=!1,h(""),m(!1),v(!1),U(ie.CANCEL)},600),()=>{null!==q.current&&clearTimeout(q.current)}},[l,p,U]),$=C({setStatusText:e=>l(pa(e||null)),setIsAgentWorking:e=>l(la(e)),appendStreamText:()=>{},pushWidget:()=>{},onPayment:e=>_.current?.(e),onSignIn:e=>S.current?.(e),onError:()=>{}}),z=I(e=>{if(F.current!==M.current)return A.current?.abort(),void R.current?.();if("payment"===e.type&&"payment"in e.data)return void ue({kind:"payment",payment:e.data.payment},$.current);if("sign_in"===e.type&&"signIn"in e.data)return void ue({kind:"sign_in",signIn:e.data.signIn},$.current);if("conversation_title"===e.type&&"conversationTitle"in e.data){const t=e.data.conversationTitle.trim();return void(t&&T.current?.(t))}const t=E.current;t.processEvent(e),N.current||(N.current=!0,v(!0));const r=function(e){const t=e.data;switch(e.type){case"text":return"text"in t?{kind:"text",text:t.text}:null;case"widget":return"widget"in t?{kind:"widget",widget:t.widget}:null;case"status_update":return"statusText"in t?{kind:"status_update",statusText:t.statusText}:null;case"payment":return"payment"in t?{kind:"payment",payment:t.payment}:null;case"sign_in":return"signIn"in t?{kind:"sign_in",signIn:t.signIn}:null;case"error":return"error"in t?{kind:"error",error:t.error}:null;default:return null}}(e);if(r){const e="status_update"===r.kind?{kind:"status_update",statusText:t.getStatusText()}:r;ue(e,$.current)}const a=t.toMessages(),s=P.current;n(e=>[...e.slice(0,e.length-s),...a]),P.current=a.length,a.some(e=>_s(e)||!vs(e.message))&&l(la(!1)),t.isStreamComplete()&&j()},[l,n,j]),K=I(e=>{Q("Stream connection error. Please try again."),j()},[j]),H=I(()=>{A.current?.abort(),R.current?.(),A.current=null,R.current=null,F.current=null,E.current.reset(),P.current=0,h(""),m(!1),v(!1),U(ie.CANCEL),l(de()),l(ma()),x.current=!1},[l,U]),G=I((e,t)=>{A.current?.abort(),R.current?.(),E.current.reset(),P.current=0,N.current=!1,F.current=t,M.current=t,A.current=e;const n=e.subscribe({onEvent:z,onError:K,onComplete:()=>{j()}});R.current=n},[z,K,j]),B=I(async(t="")=>{x.current=!0;try{let a=e;if(!a){if(!s)return x.current=!1,void Q("Conversation is not ready yet. Please wait a moment.");const e=await s();if(!e)return x.current=!1,void Q("Failed to start conversation. Please try again.");a=e}const i=t.trim();window.dispatchEvent(new CustomEvent("stopAudioPlayback")),l(la(!0)),m(!0),v(!1),l(pa(null)),l(fa(Date.now())),l(de());const c={id:`user-${Y()}`,sender:"user",message:i,timestamp:(new Date).toISOString()};n(e=>[...e,c]);const u=le(),p=d.streamMessage({conversationId:a,message:i,enableTts:r,debugMode:o,...u?{body:{client_metadata:{device_token:u}}}:{}});G(p,a)}catch(e){D.error({message:"Failed to send message",api_name:"chat-send",error_message:e instanceof Error?e.message:String(e)}),Q("Failed to send conversations message. Please try again."),x.current=!1,U(ie.CANCEL)}},[l,t,e,d,r,n,G,s,o,U]),V=C(B);V.current=B;const W=I(async(e="")=>{const t=(e??"").trim();t&&(x.current?l(ha({id:Y(),text:t,queuedAt:(new Date).toISOString()})):await B(t))},[l,B]);O(()=>{if(g||x.current)return;const e=p.getState().chat.messageQueue;if(0===e.length)return;const t=1===e.length?e[0].text:e.map(e=>`- ${e.text}`).join("\n");l(ma()),V.current(t)},[g,l,p]);const J=I(async(e,t)=>{x.current=!0,l(la(!0)),m(!0),v(!1),l(pa(null)),l(fa(Date.now())),l(de());const n=void 0!==t?t:a,s={};n&&(s.user_location=n);const o=le();o&&(s.device_token=o);const i=Object.keys(s).length>0?{client_metadata:s}:{},c=d.streamInitial({conversationId:e,body:i,enableTts:r});G(c,e)},[l,d,r,a,G]);return O(()=>()=>{A.current?.abort(),R.current?.()},[]),{sendMessage:W,startInitialStream:J,setThinkingState:L,abortStream:H,toolCallStatus:f,isProcessThinkingState:g,hasReceivedResponse:y}};function Ss({activeConversationId:e,onSelectConversation:t,onClearChat:n}){const[r,a]=k([]),s=S(e=>e.conversations.titles),[o,i]=k(!0),[c,u]=k(!1),[d,l]=k(!0),[p,f]=k(""),h=C(0),g=C(!1),m=C(d);m.current=d;const y=C(r);y.current=r;const[v]=jr.useLazyGetConversationHistoryQuery(),_=C(v);_.current=v;const[b,{isLoading:w}]=jr.useDeleteConversationMutation(),T=I(async e=>{const t="append"===e?h.current:0;if("append"===e){if(g.current||!m.current)return;g.current=!0,u(!0)}else"replace"===e&&0===y.current.length&&i(!0);try{const n=await _.current({skip:t,limit:20}).unwrap(),r=n?.conversations??[];"append"===e?(a(e=>{const t=new Set(e.map(e=>e.id));return[...e,...r.filter(e=>!t.has(e.id))]}),h.current+=20):"replace"===e?(a(r),h.current=20):a(e=>function(e,t){if(0===t.length)return e;const n=new Set(e.map(e=>e.id)),r=new Map(t.map(e=>[e.id,e])),a=t.filter(e=>!n.has(e.id));let s=a.length>0;const o=e.map(e=>{const t=r.get(e.id);return t?(n=e).id===(a=t).id&&n.title===a.title&&n.created_at===a.created_at&&n.updated_at===a.updated_at?e:(s=!0,t):e;var n,a});return s?[...a,...o]:e}(e,r)),"silent"!==e&&l(r.length>=20)}catch(e){D.error({message:"Failed to load conversations",api_name:"chat-conversation-list",error_message:e instanceof Error?e.message:String(e)})}finally{"append"===e?(g.current=!1,u(!1)):"replace"===e&&i(!1)}},[]);O(()=>{T("replace")},[T]);const E=C(null);O(()=>{!o&&e&&E.current!==e&&(r.some(t=>t.id===e)||(E.current=e,T("silent")))},[e,r,o,T]);const A=I(async s=>{const o=e===s,i=o?function(e,t){const n=e.findIndex(e=>e.id===t);return-1===n?null:n+1<e.length?e[n+1].id:n-1>=0?e[n-1].id:null}(p.trim()?r.filter(e=>e?.title?.toLowerCase().includes(p.toLowerCase())):r,s):null,c=await b({conversationId:s});if(c.error)return D.error({message:"Failed to delete conversation",api_name:"chat-conversation-delete",conversation_id:s,error_message:JSON.stringify(c.error)}),void Q("Failed to delete the conversation. Please try again.");pe("Conversation deleted successfully"),E.current=s;const u=y.current.some(e=>e.id===s);if(a(e=>e.filter(e=>e.id!==s)),u&&(h.current=Math.max(0,h.current-1)),o)if(i){const e=r.find(e=>e.id===i)??null;t(i,e?.title??null)}else n?.()},[e,r,p,b,t,n]),N=R(()=>r.map(e=>s[e.id]?{...e,title:s[e.id]}:e),[r,s]);return{conversations:p.trim()?N.filter(e=>e?.title?.toLowerCase().includes(p.toLowerCase())):N,isLoading:o,isLoadingMore:c,hasMore:d,isDeleting:w,searchQuery:p,setSearchQuery:f,loadConversations:T,deleteConversation:A,isLoadingMoreRef:g}}function ws(){return S(e=>{const t=e.conversations.activeConversationId;return t?e.conversations.titles[t]??null:null})}function Ts(e,t){if(null==e||!t)return null;const n=e/100,r=t.toUpperCase();try{return new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(n)}catch{return`${r} ${n.toFixed(2)}`}}function Es(e){if("success"===e.status){const t=Ts(e.amount,e.currency);return`The payment${t?` of ${t}`:""} is successfully completed.`}return"failure"===e.status?"The payment failed."+(e.paymentId?` The reference ID is ${e.paymentId}.`:""):"Payment cancelled."}const Is=({sendMessageRef:e})=>{const[t,n]=k(null),r=I(()=>n(null),[]),a=I(t=>{"stripe"===t.provider?"cancel"===t.status&&Q("Payment cancelled."):"chargebee"===t.provider&&"cancel"===t.status?Q("Payment cancelled."):"failure"===t.status&&t.message&&Q(t.message),e.current?e.current(Es(t)):D.error({message:"Payment result dropped: sendMessageRef is null",api_name:"payment-result-dispatch",status:t.status}),n(null)},[e]);return{paymentInit:t,setPaymentInit:n,clearPaymentInit:r,handlePaymentResult:a}};function As(e,t,n){const r=C(n);O(()=>{r.current=n},[n]),O(()=>{const n=fe.on(e,t,e=>{r.current(e)});return()=>{n()}},[e,t])}async function Rs(e){try{const t=await e.getItem(he.LOCATION_CACHE);if(!t)return null;const n=JSON.parse(t);return Date.now()-n.timestamp<36e5?n.location:(await e.removeItem(he.LOCATION_CACHE),null)}catch{return null}}const ks=()=>{const[e,t]=k(!1),[n,r]=k(null),a=ge(),s=I(async()=>{const e=await Rs(a);if(e)return e;if(!("geolocation"in navigator))return r("Geolocation is not supported by this browser"),null;if("https:"!==window.location.protocol&&"localhost"!==window.location.hostname)return r("Geolocation requires HTTPS"),null;t(!0),r(null);try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone,t=await new Promise((e,t)=>{navigator.geolocation.getCurrentPosition(e,t,{enableHighAccuracy:!1,timeout:8e3,maximumAge:6e5})}),{latitude:n,longitude:r}=t.coords;let s="";try{const e=await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${n}&lon=${r}&format=json`,{headers:{"Accept-Language":"en","User-Agent":"1interface-chat/1.0"}});e.ok&&(s=(await e.json()).display_name??"")}catch(e){D.warn({message:"Reverse geocoding failed",api_name:"user-location",error_message:e instanceof Error?e.message:String(e)})}const o={latitude:n,longitude:r,address:s,timezone:e};return await async function(e,t){try{const n={location:t,timestamp:Date.now()};await e.setItem(he.LOCATION_CACHE,JSON.stringify(n))}catch{}}(a,o),o}catch(e){if(e&&"number"==typeof e.code)switch(e.code){case 1:r("Location permission denied");break;case 2:r("Location information unavailable");break;case 3:r("Location request timed out");break;default:r("Failed to retrieve location")}else r("Failed to get location");return null}finally{t(!1)}},[a]);return{getUserLocation:s,isLoading:e,error:n}};function Os({hasMore:e,isLoadingRef:t,scrollAreaRef:n,onLoadMore:r,itemCount:a}){const s=C(null),o=I(a=>{if(s.current&&s.current.disconnect(),!a||!e)return;const o=function(e,t){const n=t?.querySelector("[data-radix-scroll-area-viewport]");if(n)return n;if(t&&t.scrollHeight>t.clientHeight)return t;let r=e.parentElement;for(;r&&r!==document.body;){if(r.scrollHeight>r.clientHeight)return r;r=r.parentElement}return null}(a,n.current);o&&(s.current=new IntersectionObserver(e=>{e[0].isIntersecting&&!t.current&&r()},{root:o,rootMargin:"0px",threshold:.1}),s.current.observe(a))},[e,t,n,r]);return O(()=>{if(!e||t.current)return;const a=n.current;if(!a)return;const s=a.querySelector("[data-radix-scroll-area-viewport]")??a;s.clientHeight>0&&s.scrollHeight<=s.clientHeight&&r()},[e,n,r,t,a]),o}const Cs=e=>{const[t,n]=k(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return O(()=>{if("undefined"==typeof window)return;const t=window.matchMedia(e),r=e=>{n(e.matches)};return n(t.matches),t.addEventListener("change",r),()=>{t.removeEventListener("change",r)}},[e]),t},Ns=()=>Cs("(min-width: 1024px)"),Ps=e=>{const t=C(null),[n,r]=k(!1);return O(()=>{const n=t.current;if(!n)return;const a=new ResizeObserver(t=>{for(const n of t)r(n.contentRect.width>=e)});a.observe(n);const s=n.getBoundingClientRect().width;return r(s>=e),()=>{a.disconnect()}},[e]),{containerRef:t,isDesktop:n}},xs=()=>{const[e,t]=k(!1),{getUserLocation:n}=ks(),r=ge(),a=C(!1);return O(()=>{if(a.current)return;a.current=!0;let e=null;const s=()=>{null!==e&&clearTimeout(e),t(!0)};return(async()=>{if("false"===await r.getItem(he.LOCATION_ENABLED))return void s();const t=await Rs(r);t&&0!==t.latitude&&0!==t.longitude?s():(e=setTimeout(s,5e3),n().finally(s))})(),()=>{null!==e&&clearTimeout(e)}},[n,r]),e};function qs({paymentInit:e,onPaymentResult:t,onClearPaymentInit:n}){const r=C(new Set),a=J(e);return{handlePaymentResult:I(e=>{"success"!==e.status&&"failure"!==e.status||a&&r.current.add(a),t?.(e)},[t,a]),handleModalOpenChange:I(s=>{!s&&e&&(!!a&&r.current.has(a)||t?.({status:"cancel",provider:e.provider}),n?.())},[e,a,t,n])}}function Ms(e){const t=e.trim().split(/\s+/);return 1===t.length?e.charAt(0).toUpperCase():(t[0].charAt(0)+t[1].charAt(0)).toUpperCase()}function Ds(){const{themeStyles:e}=me(),{data:t,isLoading:n}=Vr(void 0),[r]=Jr(),a=R(()=>(t?.tool_servers??[]).map(t=>({id:t.id,name:t.name,description:t.description??"",initials:Ms(t.name),accentTextColor:e.statusPrimary.solid,logoUrl:t.logo_url??void 0,connected:t.connected})),[t?.tool_servers,e.statusPrimary.solid]);return{connectors:a,isLoading:n,disconnect:async function(e){const t=a.find(t=>t.id===e)?.name??"App";"error"in await r(e)?Q(`Failed to disconnect ${t}. Please try again.`):pe(`${t} disconnected`)}}}const Qs={NORMAL:"normal",RECORDING:"recording",TRANSCRIBING:"transcribing"},Fs=({onSend:e,disabled:t=!1,transcribedText:n,onTranscribedTextUsed:r,isRecording:a=!1,isTranscribing:s=!1})=>{const[o,i]=k("");O(()=>{if(!n)return;let e=!1;return queueMicrotask(()=>{e||(i(e=>0===e.trim().length?n:`${e.trimEnd()} ${n}`),r?.())}),()=>{e=!0}},[n,r]);const c=o.trim().length>0&&!t,u=I(()=>{const n=o.trim();n&&!t&&(e(n),i(""))},[o,t,e]),d=a?Qs.RECORDING:s?Qs.TRANSCRIBING:Qs.NORMAL;return R(()=>({value:o,setValue:i,send:u,canSend:c,mode:d}),[o,u,c,d])},Us=e=>{for(let t=e.length-1;t>=0;t--)if("user"===e[t].sender)return t;return-1},Ls=e=>{const t=S(e=>!!e.voice?.isAgentWorking),n=S(e=>e.voice?.statusText??null),r=S(e=>e.voice?.responseStartTime??null),a=S(e=>e.chat.isAgentWorking),s=S(e=>e.chat.statusText??null),o=S(e=>e.chat.responseStartTime),i=S(e=>e.indicator.lastResponseTime),c=e?t:a,u=e?n:s,d=e?r:o;return R(()=>({isAgentWorking:c,statusText:u??void 0,responseStartTime:d,lastResponseTime:i}),[c,u,d,i])},js=[],$s=({messages:e,voiceStreamingMessages:t=js,voiceActive:n})=>{const r=R(()=>{if(0===t.length)return e;const n=new Set(t.map(e=>e.id));return e.filter(e=>!n.has(e.id))},[e,t]),a=R(()=>Us(r),[r]),s=Ls(n),o=C(e.length),i=I(()=>{const t=o.current;return o.current=e.length,((e,t)=>{const n=t.length-1,r=Us(t);if(t.length<=e)return{hasNew:!1,newMessages:[],firstNewIndex:e,lastIndex:n,hasNewUserMessage:!1,hasNewWidget:!1,lastUserMessageIndex:r};const a=t.slice(e);return{hasNew:!0,newMessages:a,firstNewIndex:e,lastIndex:n,hasNewUserMessage:a.some(e=>"user"===e.sender),hasNewWidget:a.some(ye),lastUserMessageIndex:r}})(t,e)},[e]);return{visibleMessages:r,lastUserMessageIndex:a,indicator:s,classifyArrival:i}},zs=(e={})=>{const{enabled:t=!0}=e,[n,r]=k(cs.INITIAL),[a,s]=k(0),[o,i]=k(!0),c=C(null),u=C(null),d=C(null);return O(()=>{if(!t)return r(cs.INITIAL),s(0),void i(!0);r(cs.INITIAL),s(0),i(!0);let e=cs.INITIAL;const n=()=>{c.current=setTimeout(()=>{i(!1),d.current=setTimeout(()=>{s(t=>(t+1)%e.length),i(!0),d.current=null},500),n()},cs.ROTATION_INTERVAL_MS)};return n(),u.current=setTimeout(()=>{e=cs.LATER,c.current&&clearTimeout(c.current),d.current&&clearTimeout(d.current),r(cs.LATER),s(0),i(!1),d.current=setTimeout(()=>{i(!0),d.current=null},500),n()},cs.PHASE_SWITCH_MS),()=>{c.current&&clearTimeout(c.current),u.current&&clearTimeout(u.current),d.current&&clearTimeout(d.current),c.current=null,u.current=null,d.current=null}},[t]),{message:n[a],isVisible:o}},Ks=e=>{const[t,n]=k(()=>null===e?0:Math.floor((Date.now()-e)/1e3));return O(()=>{if(null===e)return void n(0);n(Math.floor((Date.now()-e)/1e3));const t=setInterval(()=>{n(Math.floor((Date.now()-e)/1e3))},1e3);return()=>clearInterval(t)},[e]),t};function Hs(e,t=28){const[n,r]=k(e),a=C(e),s=I(e=>{a.current=e,r(e)},[]);return O(()=>{if(a.current===e)return;const n=function(e,t){const n=Math.min(e.length,t.length);let r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}(a.current,e);s(e.slice(0,n));let r=n;const o=globalThis.setInterval(()=>{r+=1,s(e.slice(0,r)),r>=e.length&&globalThis.clearInterval(o)},t);return()=>globalThis.clearInterval(o)},[e,t,s]),n}const Gs=P(null),Bs=()=>{const e=x(Gs);if(!e)throw new Error("useChatSettings must be used within a <SettingsProvider>");return e};let Vs=0;function Ws({refreshSession:e,checkIntervalMs:t=6e4}){const n=b(),r=S(e=>e.auth),a=r?.accessToken??null,s=Boolean(r?.isAuthenticated),o=r?.tokenExpiresAt??null,i=C(null),c=C(null),u=I(()=>{n.dispatch(U())},[n]),d=I(async(t=!1)=>{if(t||!(Date.now()-Vs<3e5))try{await e()?Vs=Date.now():(D.error({message:"Session cleared: proactive token refresh failed",api_name:"auth-refresh"}),u())}catch(e){D.error({message:"Token refresh failed",api_name:"auth-refresh",error_message:e instanceof Error?e.message:String(e)}),u()}},[e,u]),l=I(()=>{s&&(oe(o)?d(!0):X(o)&&d())},[s,o,d]);return O(()=>{a&&oe(o)&&d(!0)},[]),O(()=>{if(s&&a){if(oe(o))return void d(!0);const e=ve(o);return e>0?c.current=setTimeout(()=>{d()},e):X(o)&&d(),i.current=setInterval(()=>{oe(o)?d(!0):X(o)&&d()},t),()=>{i.current&&clearInterval(i.current),c.current&&clearTimeout(c.current)}}Vs=0,i.current&&(clearInterval(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null)},[s,a,o,t,d]),{checkNow:l}}class Js{mediaRecorder=null;audioChunks=[];stream=null;audioContext=null;analyser=null;dataArray=null;animationFrameId=null;onAudioLevel;async startRecording(e){try{if(this.onAudioLevel=e,!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Microphone access requires HTTPS. Please access the app via https:// or localhost.");this.stream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,sampleRate:24e3,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),e&&(this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.audioContext.createMediaStreamSource(this.stream).connect(this.analyser),this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.analyzeAudio());const t=this.getSupportedMimeType();this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:t}),this.audioChunks=[],this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&this.audioChunks.push(e.data)},this.mediaRecorder.start()}catch(e){throw this.cleanup(),e}}async stopRecording(){return new Promise((e,t)=>{this.mediaRecorder?(this.mediaRecorder.onstop=()=>{const t=this.mediaRecorder?.mimeType||"audio/webm",n=t.includes("webm")?"webm":"ogg",r=new Blob(this.audioChunks,{type:t}),a=new File([r],`audio.${n}`,{type:t});this.cleanup(),e(a)},this.mediaRecorder.stop(),this.stream&&this.stream.getTracks().forEach(e=>e.stop())):t(new Error("MediaRecorder not initialized"))})}analyzeAudio(){if(!this.analyser||!this.dataArray)return;this.analyser.getByteFrequencyData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++)e+=this.dataArray[t];const t=Math.min(e/this.dataArray.length/128,1);this.onAudioLevel&&this.onAudioLevel(t),this.animationFrameId=requestAnimationFrame(()=>this.analyzeAudio())}getSupportedMimeType(){const e=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg"];for(const t of e)if(MediaRecorder.isTypeSupported(t))return t;return"audio/webm"}cleanup(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null),this.analyser=null,this.dataArray=null,this.mediaRecorder=null,this.audioChunks=[],this.onAudioLevel=void 0}}const Xs=({onTranscriptionComplete:e,onTranscriptionPopulate:t,autoSendVoice:n=!0}={})=>{const[r,a]=k(!1),[s,o]=k(!1),[i,c]=k(0),u=C(null),d=C(null),l=C(!1),p=C(null),[f]=zr(),h=I(async()=>{try{u.current||(u.current=new Js),d.current=Date.now();const e=()=>{p.current?.(),document.removeEventListener("mouseup",e),document.removeEventListener("touchend",e),document.removeEventListener("pointerup",e)};document.addEventListener("mouseup",e),document.addEventListener("touchend",e),document.addEventListener("pointerup",e),await u.current.startRecording(e=>{c(e)}),l.current=!0,a(!0)}catch(e){D.error({message:"Failed to start STT recording",api_name:"stt-record",error_message:e instanceof Error?e.message:String(e)}),l.current=!1,Q("Microphone access is required. Please allow microphone permissions in your browser settings.")}},[]),g=I(async()=>{try{if(!u.current||!l.current)return;const r=d.current?Date.now()-d.current:0;if(a(!1),c(0),r<500)return u.current?.cleanup(),void(d.current=null);o(!0);const s=await u.current.stopRecording(),i=await f({audioFile:s}).unwrap();i.success?i.data.text&&(n&&e?await e(i.data.text):!n&&t&&t(i.data.text)):Q("Transcription failed")}catch(e){D.error({message:"STT transcription failed",api_name:"stt-transcribe",error_message:e instanceof Error?e.message:String(e)}),Q("Failed to transcribe audio")}finally{o(!1),l.current=!1,u.current?.cleanup(),d.current=null}},[n,e,t,f]);return O(()=>{p.current=g},[g]),O(()=>()=>{u.current?.cleanup()},[]),{isRecording:r,isTranscribing:s,audioLevel:i,startRecording:h,stopRecording:g}},Zs="OAUTH_SUCCESS",Ys="OAUTH_ERROR",eo=Zs,to=Ys;function no({signInInit:e,sendMessageRef:t,clearSignInInit:n,sendResumeMessage:r=!0}){const[a]=Kr();O(()=>{if(!e)return;const s=function(e){try{const t=(new URL(e).searchParams.get("scope")??"").match(/\/auth\/([^./]+)/);if(t?.[1])return t[1].charAt(0).toUpperCase()+t[1].slice(1)}catch{}return"Service"}(e.authorize_url),o=window.open(e.authorize_url,"oauth_popup",`width=500,height=650,left=${Math.round(screen.width/2-250)},top=${Math.round(screen.height/2-325)}`);if(!o)return Q("Please allow popups for this site to sign in to external services."),void n();let i=!1;const c=e=>{i||(i=!0,window.removeEventListener("message",u),clearInterval(d),e?.(),n())},u=async e=>{if(e.origin!==window.location.origin)return;if(i)return;if(e.data?.type===to)return void c(()=>Q(`Failed to sign in to ${s}. Please try again.`));if(e.data?.type!==eo)return;i=!0,window.removeEventListener("message",u),clearInterval(d);const{code:l,state:p}=e.data;"error"in await a({code:l,state:p})?Q(`Failed to sign in to ${s}. Please try again.`):(pe(`${s} connected successfully`),r&&t.current?.(`${s} is now signed in, please continue`)),n(),o?.close()},d=setInterval(()=>{o.closed&&c()},500);return window.addEventListener("message",u),()=>{window.removeEventListener("message",u),clearInterval(d),i||o.close()}},[e,t,n,a,r])}function ro({sendMessageRef:e}){const{paymentInit:t,setPaymentInit:n,clearPaymentInit:r,handlePaymentResult:a}=Is({sendMessageRef:e}),{handlePaymentResult:s,handleModalOpenChange:o}=qs({paymentInit:t,onPaymentResult:a,onClearPaymentInit:r});return{paymentInit:t,setPaymentInit:n,isOpen:!!t,onOpenChange:o,onResult:s,clearPaymentInit:r}}const ao={conversations:{disable_old_widgets:!1,allow_conversation_deletion:!0},voice_agent:{enabled:!0,show_customization_modal:!1,assistant_starts_conversation:!0},features:[_e.SSO],backend_version:""},so=P(void 0),oo=()=>{const{data:e,isLoading:t,error:n}=Pa(),r=e?.success?e.data:null,a=R(()=>{return(e=r)?{conversations:{...ao.conversations,...e.conversations},voice_agent:{...ao.voice_agent,...e.voice_agent},features:e.features??ao.features,backend_version:e.backend_version??ao.backend_version}:ao;var e},[r]);return R(()=>({clientConfig:a,isLoading:t,error:n?new Error("Failed to fetch client configuration"):null}),[a,t,n])},io=()=>{const e=x(so);if(!e)throw new Error("useConfiguration must be used within a ConfigurationProvider");return e},co=P({}),uo=()=>x(co);function lo(e){return Array.isArray(e.message_type)&&e.message_type.includes("widget")}function po(e,t,n){if(!n)return!1;if(!lo(e))return!1;let r=null;for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&lo(n)){r=n;break}}if(!r||r.id!==e.id)return!0;const a=t.findIndex(t=>t.id===e.id);return t.slice(a+1).some(e=>"user"===e.sender)}const fo="moyasar_cb";function ho(e){const t=new URL(window.location.href),n=new URL(`${t.origin}${be()}/moyasar-callback.html`);return n.searchParams.set(fo,"1"),e&&n.searchParams.set("given_id",e),n.toString()}const go=new Set(["paid","authorized","failed","captured"]);function mo(e){if(!e)return null;const t=new URLSearchParams(e);if("1"!==t.get(fo))return null;const n=t.get("status"),r=t.get("id");if(!n||!r)return null;if(!go.has(n))return null;const a=t.get("conversation_id")||null,s=(t.get("given_id")||null)??r;if("paid"===n||"authorized"===n||"captured"===n){const e=t.get("amount"),n=e?Number.parseInt(e,10):void 0;return{result:{status:"success",provider:"moyasar",paymentId:s,amount:Number.isFinite(n)?n:void 0,currency:t.get("currency")??void 0},conversationId:a}}return{result:{status:"failure",provider:"moyasar",code:n,message:yo(t.get("message")??`Payment ${n}`),paymentId:s},conversationId:a}}function yo(e){try{const t=decodeURIComponent(e);return t===e?e:t}catch{return e}}function vo(e,t){const n="dark"===t;return{pageBg:e.bgColor,cardBg:e.widgetBg,text:e.primaryText,heading:e.primaryText,muted:e.secondaryText,divider:e.widgetBorderColor,accent:e.statusDiscovery.solid,accentText:e.statusDiscovery.text,focus:e.statusDiscovery.solid,pillBg:e.inputBgColor,pillBorder:e.inputBorderColor,pillText:e.secondaryText,cardShadow:n?"0 1px 3px rgba(0,0,0,0.4), 0 0 0 1px rgba(255,255,255,0.04)":"0 1px 3px rgba(0,0,0,0.08), 0 0 0 1px rgba(0,0,0,0.04)",radius:e.borderRadius,fontFamily:e.fontFamily,colorScheme:n?"dark":"light"}}const _o="stripe";export{ja as AguiAdapter,Js as AudioRecorder,is as BREAKPOINTS,Qs as CHAT_INPUT_MODES,ds as CONVERSATION_TITLE_REFRESH_DELAYS_MS,co as ChatCallbacksContext,Gs as ChatSettingsContext,so as ConfigurationContext,ps as DEFAULT_CONVERSATION_TITLE,_o as DEFAULT_PAYMENT_PROVIDER,Ma as DEFAULT_PROTOCOL,qr as ERROR_CODES,Ka as EventAggregator,Nr as GENERIC_SERVER_ERROR_MESSAGE,Da as MAX_CONNECTION_RETRIES,fo as MOYASAR_CALLBACK_SENTINEL,Ys as OAUTH_ERROR_TYPE,Zs as OAUTH_SUCCESS_TYPE,us as PAGINATION,Ua as ProprietaryAdapter,xa as ProtocolContext,Qa as SSEEventType,cs as THINKING_MESSAGES,ls as TYPEWRITER_INTERVAL_MS,Dr as apiBridge,ca as apiMiddleware,ia as apiReducers,Ia as bindChatLogger,Zr as brandingApi,Ur as bridgedFetch,vo as buildBrandSkin,ho as buildCallbackUrl,jr as chatApi,ka as chatCoreRootReducer,Ra as chatLoggerContextProvider,va as chatReducer,es as checkOrganizationExistsApi,ma as clearMessageQueue,ta as configApi,Ta as conversationsReducer,$a as createAdapter,za as createDefaultAdapterConfig,ss as createSessionRefresher,ga as dequeueMessage,ha as enqueueMessage,Ya as fetchOrganizations,Wa as forgotPasswordApi,Ts as formatAmount,Es as formatResultMessage,xr as getApiErrorMessage,Qr as getAuthToken,Rs as getCachedLocation,Lr as getLatestRequestId,_s as hasAnyExtraData,Pr as isApiServerError,vs as isEmptyMessage,Ha as loginApi,Ba as logoutApi,mo as parseMoyasarCallbackFromUrl,ra as profileApi,Va as refreshTokenApi,Aa as resetChatLoggerForTests,ya as resetChatState,Ja as resetPasswordApi,Oa as serializableCheck,Sa as setActiveConversationId,la as setIsAgentWorking,fa as setResponseStartTime,pa as setStatusText,po as shouldDisableMessage,Ga as signupApi,Za as ssoExchangeApi,Xa as ssoStartApi,Ca as store,wa as upsertConversationTitle,ws as useActiveConversationTitle,os as useAuth,uo as useChatCallbacks,bs as useChatConnection,Ss as useChatHistory,Fs as useChatInput,Bs as useChatSettings,io as useConfiguration,oo as useConfigurationValue,Ds as useConnectors,Ps as useContainerQuery,ys as useConversation,$r as useCreateConversatonsMutation,oa as useDeleteAccountMutation,Br as useDeleteConversationMutation,Jr as useDeleteToolServerConnectionMutation,Ks as useElapsedSeconds,As as useEventEmitter,Kr as useExchangeOAuthCodeMutation,Yr as useGetBrandingQuery,Pa as useGetConfigQuery,Hr as useGetConversationHistoryQuery,aa as useGetProfileQuery,Vr as useGetToolServersQuery,Os as useInfiniteScroll,Ns as useIsDesktop,Gr as useLazyGetConversationByIdQuery,xs as useLocationInit,ts as useLogin,rs as useLogout,Cs as useMediaQuery,$s as useMessageList,no as useOAuthPopup,ro as usePayment,Is as usePaymentFlow,qs as usePaymentResultDedup,qa as useProtocol,as as useRefreshToken,Ls as useResolvedChatIndicators,Xs as useSTTRecording,ns as useSignup,Wr as useStartToolServerOAuthMutation,zs as useThinkingMessage,Ws as useTokenRefresh,zr as useTranscribeAudioMutation,Hs as useTypewriter,sa as useUpdateProfileMutation,ks as useUserLocation};
|
|
1
|
+
import{nanoid as e,formatProdErrorMessage as t,createSelector as n,createAction as r,createAsyncThunk as a,createSlice as s,prepareAutoBatched as o,isAnyOf as i,isFulfilled as c,isRejectedWithValue as u,combineReducers as d,isPlainObject as l,SHOULD_AUTOBATCH as p,isAllOf as f,isRejected as h,isPending as g,isAction as m,createNextState as y,isAsyncThunkAction as v,configureStore as _}from"@reduxjs/toolkit";import{useStore as b,useSelector as S,useDispatch as w,batch as T,shallowEqual as E}from"react-redux";import{useCallback as I,useDebugValue as A,useMemo as R,useState as k,useEffect as O,useRef as C,useLayoutEffect as N,createContext as P,useContext as x}from"react";import{getCustomHeaders as q,isDevMode as M,logger as D,showErrorToast as Q,getTokenRefreshHandler as F,clearSession as U,setSession as L,readAccessToken as j,API_ENDPOINTS as $,TIMING as z,sessionExpired as K,indicatorReducer as H,sessionReducer as G,sessionListenerMiddleware as B,setAccessTokenReader as V,setTokenExpiresAtReader as W,getPaymentId as J,isTokenAboutToExpire as X,readTokenExpiresAt as Z,generateUniqueId as Y,getApiUrl as ee,AUTH_PATHS as te,extractTokens as ne,createTokenRefresher as re,formatTimeRemaining as ae,getTimeUntilExpiry as se,isTokenExpired as oe,INDICATOR_TIMER_ACTIONS as ie,setLastResponseTime as ce,handleSharedEvent as ue,clearLastResponseTime as de,readDeviceToken as le,showSuccessToast as pe,eventEmitter as fe,STORAGE_KEYS as he,useStorage as ge,useBranding as me,hasWidgets as ye,getTimeUntilRefresh as ve,FEATURE_FLAGS as _e,getBaseUrl as be}from"@1interface/shared-core";import{fetchEventSource as Se}from"@microsoft/fetch-event-source";var we=Symbol.for("immer-nothing"),Te=Symbol.for("immer-draftable"),Ee=Symbol.for("immer-state"),Ie="production"!==process.env.NODE_ENV?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function Ae(e,...t){if("production"!==process.env.NODE_ENV){const n=Ie[e],r=We(n)?n.apply(null,t):n;throw new Error(`[Immer] ${r}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Re=Object,ke=Re.getPrototypeOf,Oe="constructor",Ce="prototype",Ne="configurable",Pe="enumerable",xe="writable",qe="value",Me=e=>!!e&&!!e[Ee];function De(e){return!!e&&(Ue(e)||He(e)||!!e[Te]||!!e[Oe]?.[Te]||Ge(e)||Be(e))}var Qe=Re[Ce][Oe].toString(),Fe=new WeakMap;function Ue(e){if(!e||!Ve(e))return!1;const t=ke(e);if(null===t||t===Re[Ce])return!0;const n=Re.hasOwnProperty.call(t,Oe)&&t[Oe];if(n===Object)return!0;if(!We(n))return!1;let r=Fe.get(n);return void 0===r&&(r=Function.toString.call(n),Fe.set(n,r)),r===Qe}function Le(e,t,n=!0){0===je(e)?(n?Reflect.ownKeys(e):Re.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function je(e){const t=e[Ee];return t?t.type_:He(e)?1:Ge(e)?2:Be(e)?3:0}var $e=(e,t,n=je(e))=>2===n?e.has(t):Re[Ce].hasOwnProperty.call(e,t),ze=(e,t,n=je(e))=>2===n?e.get(t):e[t],Ke=(e,t,n,r=je(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n},He=Array.isArray,Ge=e=>e instanceof Map,Be=e=>e instanceof Set,Ve=e=>"object"==typeof e,We=e=>"function"==typeof e,Je=e=>"boolean"==typeof e,Xe=e=>e.copy_||e.base_,Ze=e=>e.modified_?e.copy_:e.base_;function Ye(e,t){if(Ge(e))return new Map(e);if(Be(e))return new Set(e);if(He(e))return Array[Ce].slice.call(e);const n=Ue(e);if(!0===t||"class_only"===t&&!n){const t=Re.getOwnPropertyDescriptors(e);delete t[Ee];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const a=n[r],s=t[a];!1===s[xe]&&(s[xe]=!0,s[Ne]=!0),(s.get||s.set)&&(t[a]={[Ne]:!0,[xe]:!0,[Pe]:s[Pe],[qe]:e[a]})}return Re.create(ke(e),t)}{const t=ke(e);if(null!==t&&n)return{...e};const r=Re.create(t);return Re.assign(r,e)}}function et(e,t=!1){return nt(e)||Me(e)||!De(e)||(je(e)>1&&Re.defineProperties(e,{set:tt,add:tt,clear:tt,delete:tt}),Re.freeze(e),t&&Le(e,(e,t)=>{et(t,!0)},!1)),e}var tt={[qe]:function(){Ae(2)}};function nt(e){return null===e||!Ve(e)||Re.isFrozen(e)}var rt="MapSet",at="Patches",st="ArrayMethods",ot={};function it(e){const t=ot[e];return t||Ae(0,e),t}var ct,ut=e=>!!ot[e],dt=()=>ct;function lt(e,t){t&&(e.patchPlugin_=it(at),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function pt(e){ft(e),e.drafts_.forEach(gt),e.drafts_=null}function ft(e){e===ct&&(ct=e.parent_)}var ht=e=>ct={drafts_:[],parent_:ct,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:ut(rt)?it(rt):void 0,arrayMethodsPlugin_:ut(st)?it(st):void 0};function gt(e){const t=e[Ee];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function mt(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[Ee].modified_&&(pt(t),Ae(4)),De(e)&&(e=yt(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[Ee].base_,e,t)}else e=yt(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&et(t,n)}(t,e,!0),pt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==we?e:void 0}function yt(e,t){if(nt(t))return t;const n=t[Ee];if(!n)return Tt(t,e.handledSet_,e);if(!_t(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:t}=n;if(t)for(;t.length>0;)t.pop()(e);wt(n,e)}return n.copy_}function vt(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var _t=(e,t)=>e.scope_===t,bt=[];function St(e,t,n,r){const a=Xe(e),s=e.type_;if(void 0!==r&&ze(a,r,s)===t)return void Ke(a,r,n,s);if(!e.draftLocations_){const t=e.draftLocations_=new Map;Le(a,(e,n)=>{if(Me(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const o=e.draftLocations_.get(t)??bt;for(const e of o)Ke(a,e,n,s)}function wt(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||1===e.type_&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){const{patchPlugin_:n}=t;if(n){const r=n.getPath(e);r&&n.generatePatches_(e,r,t)}vt(e)}}function Tt(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Me(e)||t.has(e)||!De(e)||nt(e)||(t.add(e),Le(e,(r,a)=>{if(Me(a)){const t=a[Ee];if(_t(t,n)){const n=Ze(t);Ke(e,r,n,e.type_),vt(t)}}else De(a)&&Tt(a,t,n)})),e}var Et={get(e,t){if(t===Ee)return e;let n=e.scope_.arrayMethodsPlugin_;const r=1===e.type_&&"string"==typeof t;if(r&&n?.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);const a=Xe(e);if(!$e(a,t,e.type_))return function(e,t,n){const r=Rt(t,n);return r?qe in r?r[qe]:r.get?.call(e.draft_):void 0}(e,a,t);const s=a[t];if(e.finalized_||!De(s))return s;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return s;if(s===At(e.base_,t)){Ot(e);const n=1===e.type_?+t:t,r=Ct(0,s,e,n);return e.copy_[n]=r}return s},has:(e,t)=>t in Xe(e),ownKeys:e=>Reflect.ownKeys(Xe(e)),set(e,t,n){const r=Rt(Xe(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=At(Xe(e),t),o=r?.[Ee];if(o&&o.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((a=n)===(s=r)?0!==a||1/a==1/s:a!=a&&s!=s)&&(void 0!==n||$e(e.base_,t,e.type_)))return!0;Ot(e),kt(e)}var a,s;return e.copy_[t]===n&&(void 0!==n||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:r}=e;if(Me(n)){const a=n[Ee];_t(a,r)&&a.callbacks_.push(function(){Ot(e);const r=Ze(a);St(e,n,r,t)})}else De(n)&&e.callbacks_.push(function(){const a=Xe(e);3===e.type_?a.has(n)&&Tt(n,r.handledSet_,r):ze(a,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&Tt(ze(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(Ot(e),void 0!==At(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),kt(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Xe(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[xe]:!0,[Ne]:1!==e.type_||"length"!==t,[Pe]:r[Pe],[qe]:n[t]}:r},defineProperty(){Ae(11)},getPrototypeOf:e=>ke(e.base_),setPrototypeOf(){Ae(12)}},It={};for(let e in Et){let t=Et[e];It[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function At(e,t){const n=e[Ee];return(n?Xe(n):e)[t]}function Rt(e,t){if(!(t in e))return;let n=ke(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=ke(n)}}function kt(e){e.modified_||(e.modified_=!0,e.parent_&&kt(e.parent_))}function Ot(e){e.copy_||(e.assigned_=new Map,e.copy_=Ye(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function Ct(e,t,n,r){const[a,s]=Ge(t)?it(rt).proxyMap_(t,n):Be(t)?it(rt).proxySet_(t,n):function(e,t){const n=He(e),r={type_:n?1:0,scope_:t?t.scope_:dt(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,s=Et;n&&(a=[r],s=It);const{revoke:o,proxy:i}=Proxy.revocable(a,s);return r.draft_=i,r.revoke_=o,[i,r]}(t,n);return(n?.scope_??dt()).drafts_.push(a),s.callbacks_=n?.callbacks_??[],s.key_=r,n&&void 0!==r?function(e,t,n){e.callbacks_.push(function(r){const a=t;if(!a||!_t(a,r))return;r.mapSetPlugin_?.fixSetContents(a);const s=Ze(a);St(e,a.draft_??a,s,n),wt(a,r)})}(n,s,r):s.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(s);const{patchPlugin_:t}=e;s.modified_&&t&&t.generatePatches_(s,[],e)}),a}function Nt(e){return Me(e)||Ae(10,e),Pt(e)}function Pt(e){if(!De(e)||nt(e))return e;const t=e[Ee];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Ye(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=Ye(e,!0);return Le(n,(e,t)=>{Ke(n,e,Pt(t))},r),t&&(t.finalized_=!1),n}It.deleteProperty=function(e,t){return"production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&Ae(13),It.set.call(this,e,t,void 0)},It.set=function(e,t,n){return"production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&Ae(14),Et.set.call(this,e[0],t,n,e[0])};var xt=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(We(e)&&!We(t)){const n=t;t=e;const r=this;return function(e=n,...a){return r.produce(e,e=>t.call(this,e,...a))}}let r;if(We(t)||Ae(6),void 0===n||We(n)||Ae(7),De(e)){const a=ht(this),s=Ct(0,e,void 0);let o=!0;try{r=t(s),o=!1}finally{o?pt(a):ft(a)}return lt(a,n),mt(r,a)}if(!e||!Ve(e)){if(r=t(e),void 0===r&&(r=e),r===we&&(r=void 0),this.autoFreeze_&&et(r,!0),n){const t=[],a=[];it(at).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:a}),n(t,a)}return r}Ae(1,e)},this.produceWithPatches=(e,t)=>{if(We(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},Je(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),Je(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),Je(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){De(e)||Ae(8),Me(e)&&(e=Nt(e));const t=ht(this),n=Ct(0,e,void 0);return n[Ee].isManual_=!0,ft(t),n}finishDraft(e,t){const n=e&&e[Ee];n&&n.isManual_||Ae(9);const{scope_:r}=n;return lt(r,t),mt(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}n>-1&&(t=t.slice(n+1));const r=it(at).applyPatches_;return Me(e)?r(e,t):this.produce(e,e=>r(e,t))}},qt=xt.produceWithPatches.bind(xt),Mt=xt.applyPatches.bind(xt),Dt=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}},Qt=(e,t,n)=>{if(1===t.length&&t[0]===n){let t=!1;try{const n={};e(n)===n&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},Ft=(e,t,n)=>{const{memoize:r,memoizeOptions:a}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,i=r(()=>({}),...a);if(i.apply(null,s)!==i.apply(null,o)){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:n,firstInputs:s,secondInputs:o,stack:e})}},Ut={inputStabilityCheck:"once",identityFunctionCheck:"once"},Lt=e=>Array.isArray(e)?e:[e];function jt(e,t){const n=[],{length:r}=e;for(let a=0;a<r;a++)n.push(e[a].apply(null,t));return n}var $t="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function zt(){return{s:0,v:void 0,o:null,p:null}}function Kt(e,t={}){let n={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:r}=t;let a,s=0;function o(){let t=n;const{length:o}=arguments;for(let e=0,n=o;e<n;e++){const n=arguments[e];if("function"==typeof n||"object"==typeof n&&null!==n){let e=t.o;null===e&&(t.o=e=new WeakMap);const r=e.get(n);void 0===r?(t=zt(),e.set(n,t)):t=r}else{let e=t.p;null===e&&(t.p=e=new Map);const r=e.get(n);void 0===r?(t=zt(),e.set(n,t)):t=r}}const i=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),s++,r){const e=a?.deref?.()??a;null!=e&&r(e,c)&&(c=e,0!==s&&s--),a="object"==typeof c&&null!==c||"function"==typeof c?new $t(c):c}return i.s=1,i.v=c,c}return o.clearCache=()=>{n={s:0,v:void 0,o:null,p:null},o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function Ht(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t,r=0,a=0,s={},o=e.pop();"object"==typeof o&&(s=o,o=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);const i={...n,...s},{memoize:c,memoizeOptions:u=[],argsMemoize:d=Kt,argsMemoizeOptions:l=[],devModeChecks:p={}}=i,f=Lt(u),h=Lt(l),g=function(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const n=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${n}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}(e),m=c(function(){return r++,o.apply(null,arguments)},...f);let y=!0;const v=d(function(){a++;const e=jt(g,arguments);if(t=m.apply(null,e),"production"!==process.env.NODE_ENV){const{identityFunctionCheck:n,inputStabilityCheck:r}=((e,t)=>{const{identityFunctionCheck:n,inputStabilityCheck:r}={...Ut,...t};return{identityFunctionCheck:{shouldRun:"always"===n||"once"===n&&e,run:Qt},inputStabilityCheck:{shouldRun:"always"===r||"once"===r&&e,run:Ft}}})(y,p);if(n.shouldRun&&n.run(o,e,t),r.shouldRun){const t=jt(g,arguments);r.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:f},arguments)}y&&(y=!1)}return t},...h);return Object.assign(v,{resultFunc:o,memoizedResultFunc:m,dependencies:g,dependencyRecomputations:()=>a,resetDependencyRecomputations:()=>{a=0},lastResult:()=>t,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(r,{withTypes:()=>r}),r}var Gt=Ht(Kt),Bt=Object.assign((e,t=Gt)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const n=Object.keys(e);return t(n.map(t=>e[t]),(...e)=>e.reduce((e,t,r)=>(e[n[r]]=t,e),{}))},{withTypes:()=>Bt}),Vt=(e=>(e.uninitialized="uninitialized",e.pending="pending",e.fulfilled="fulfilled",e.rejected="rejected",e))(Vt||{}),Wt="uninitialized",Jt="pending",Xt="fulfilled",Zt="rejected";function Yt(e){return{status:e,isUninitialized:e===Wt,isLoading:e===Jt,isSuccess:e===Xt,isError:e===Zt}}var en=l;function tn(e,t){if(e===t||!(en(e)&&en(t)||Array.isArray(e)&&Array.isArray(t)))return t;const n=Object.keys(t),r=Object.keys(e);let a=n.length===r.length;const s=Array.isArray(t)?[]:{};for(const r of n)s[r]=tn(e[r],t[r]),a&&(a=e[r]===s[r]);return a?e:s}function nn(e,t,n){return e.reduce((e,r,a)=>(t(r,a)&&e.push(n(r,a)),e),[]).flat()}function rn(e){return null!=e}function an(e){return[...e?.values()??[]].filter(rn)}function sn(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var on=()=>new Map,cn=e=>{const t=new AbortController;return setTimeout(()=>{const e="signal timed out",n="TimeoutError";t.abort("undefined"!=typeof DOMException?new DOMException(e,n):Object.assign(new Error(e),{name:n}))},e),t.signal},un=(...e)=>{for(const t of e)if(t.aborted)return AbortSignal.abort(t.reason);const t=new AbortController;for(const n of e)n.addEventListener("abort",()=>t.abort(n.reason),{signal:t.signal,once:!0});return t.signal},dn=(...e)=>fetch(...e),ln=e=>e.status>=200&&e.status<=299,pn=e=>/ion\/(vnd\.api\+)?json/.test(e.get("content-type")||"");function fn(e){if(!l(e))return e;const t={...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];return t}var hn=class{constructor(e,t=void 0){this.value=e,this.meta=t}},gn="__rtkq/",mn="online",yn="offline",vn="focus",_n="focused",bn="visibilitychange",Sn=r(`${gn}${_n}`),wn=r(`${gn}un${_n}`),Tn=r(`${gn}${mn}`),En=r(`${gn}${yn}`),In=!1,An="query",Rn="mutation",kn="infinitequery";function On(e){return e.type===An}function Cn(e){return e.type===kn}function Nn(e){return On(e)||Cn(e)}function Pn(e,t,n,r,a,s){const o="function"==typeof e?e(t,n,r,a):e;return o?nn(o,rn,e=>s(xn(e))):[]}function xn(e){return"string"==typeof e?{type:e}:e}var qn=(e,t)=>e.endpointDefinitions[t],Mn=Symbol("forceQueryFn"),Dn=e=>"function"==typeof e[Mn],Qn=class extends Dt{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}},Fn=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function Un(e,t,n,r){const a=await e["~standard"].validate(t);if(a.issues)throw new Qn(a.issues,t,n,r);return a.value}function Ln(e){return e}var jn=(e={})=>({...e,[p]:!0});function $n(e,{pages:t,pageParams:n},r){const a=t.length-1;return e.getNextPageParam(t[a],t,n[a],n,r)}function zn(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function Kn(e,t,n,r){return Pn(n[e.meta.arg.endpointName][t],c(e)?e.payload:void 0,u(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,r)}function Hn(e){return Me(e)?Nt(e):e}function Gn(e,t,n){const r=e[t];r&&n(r)}function Bn(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function Vn(e,t,n){const r=e[Bn(t)];r&&n(r)}var Wn={},Jn=Symbol.for("RTKQ/skipToken"),Xn={status:Wt},Zn=y(Xn,()=>{}),Yn=y(Xn,()=>{}),er=WeakMap?new WeakMap:void 0,tr=({endpointName:e,queryArgs:t})=>{let n="";const r=er?.get(t);if("string"==typeof r)n=r;else{const e=JSON.stringify(t,(e,t)=>(t="bigint"==typeof t?{$bigint:t.toString()}:t,t=l(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t));l(t)&&er?.set(t,e),n=e}return`${e}(${n})`};function nr(...n){return function(r){const a=Kt(e=>r.extractRehydrationInfo?.(e,{reducerPath:r.reducerPath??"api"})),s={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...r,extractRehydrationInfo:a,serializeQueryArgs(e){let t=tr;if("serializeQueryArgs"in e.endpointDefinition){const n=e.endpointDefinition.serializeQueryArgs;t=e=>{const t=n(e);return"string"==typeof t?t:tr({...e,queryArgs:t})}}else r.serializeQueryArgs&&(t=r.serializeQueryArgs);return t(e)},tagTypes:[...r.tagTypes||[]]},o={endpointDefinitions:{},batch(e){e()},apiUid:e(),extractRehydrationInfo:a,hasRehydrationInfo:Kt(e=>null!=a(e))},i={injectEndpoints:function(e){const n=e.endpoints({query:e=>({...e,type:An}),mutation:e=>({...e,type:Rn}),infiniteQuery:e=>({...e,type:kn})});for(const[r,a]of Object.entries(n))if(!0!==e.overrideExisting&&r in o.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error("production"===process.env.NODE_ENV?t(39):`called \`injectEndpoints\` to override already-existing endpointName ${r} without specifying \`overrideExisting: true\``);"undefined"!=typeof process&&"development"===process.env.NODE_ENV&&console.error(`called \`injectEndpoints\` to override already-existing endpointName ${r} without specifying \`overrideExisting: true\``)}else{if("undefined"!=typeof process&&"development"===process.env.NODE_ENV&&Cn(a)){const{infiniteQueryOptions:e}=a,{maxPages:n,getPreviousPageParam:s}=e;if("number"==typeof n){if(n<1)throw new Error("production"===process.env.NODE_ENV?t(40):`maxPages for endpoint '${r}' must be a number greater than 0`);if("function"!=typeof s)throw new Error("production"===process.env.NODE_ENV?t(41):`getPreviousPageParam for endpoint '${r}' must be a function if maxPages is used`)}}o.endpointDefinitions[r]=a;for(const e of c)e.injectEndpoint(r,a)}return i},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)s.tagTypes.includes(t)||s.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(qn(o,e)):Object.assign(qn(o,e)||{},n);return i}},c=n.map(e=>e.init(i,s,o));return i.injectEndpoints({endpoints:r.endpoints})}}function rr(e,...t){return Object.assign(e,...t)}var ar=({api:e,queryThunk:t,context:n,internalState:r,selectors:{selectQueryEntry:a,selectConfig:s},getRunningQueryThunk:o})=>{const{removeQueryResult:c,unsubscribeQueryResult:u,cacheEntriesUpserted:d}=e.internalActions,l=i(u.match,t.fulfilled,t.rejected,d.match);function p(e){const t=r.currentSubscriptions.get(e);return!!t&&t.size>0}const f={};function h(e){for(const t of e.values())t?.abort?.()}function g(e,t,n){const r=t.getState();for(const s of e){const e=a(r,s);e?.endpointName&&m(s,e.endpointName,t,n)}}function m(e,t,r,s){const i=qn(n,t),u=i?.keepUnusedDataFor??s.keepUnusedDataFor;if(u===1/0)return;const d=Math.max(0,Math.min(u,2147482.647));if(!p(e)){const t=f[e];t&&clearTimeout(t),f[e]=setTimeout(()=>{if(!p(e)){const t=a(r.getState(),e);if(t?.endpointName){const e=r.dispatch(o(t.endpointName,t.originalArgs));e?.abort()}r.dispatch(c({queryCacheKey:e}))}delete f[e]},1e3*d)}}return(t,a)=>{const o=a.getState(),i=s(o);if(l(t)){let e;if(d.match(t))e=t.payload.map(e=>e.queryDescription.queryCacheKey);else{const{queryCacheKey:n}=u.match(t)?t.payload:t.meta.arg;e=[n]}g(e,a,i)}if(e.util.resetApiState.match(t)){for(const[e,t]of Object.entries(f))t&&clearTimeout(t),delete f[e];h(r.runningQueries),h(r.runningMutations)}if(n.hasRehydrationInfo(t)){const{queries:e}=n.extractRehydrationInfo(t);g(Object.keys(e),a,i)}}},sr=new Error("Promise never resolved before cacheEntryRemoved."),or=({api:e,reducerPath:t,context:n,queryThunk:r,mutationThunk:a,selectors:{selectQueryEntry:s}})=>{const o=v(r),i=v(a),u=c(r,a),d={},{removeQueryResult:l,removeMutationResult:p,cacheEntriesUpserted:f}=e.internalActions;function h(e,t,n){const r=d[e];r?.valueResolved&&(r.valueResolved({data:t,meta:n}),delete r.valueResolved)}function g(e){const t=d[e];t&&(delete d[e],t.cacheEntryRemoved())}function m(e){const{arg:t,requestId:n}=e.meta,{endpointName:r,originalArgs:a}=t;return[r,a,n]}function y(t,r,a,s,o){const i=qn(n,t),c=i?.onCacheEntryAdded;if(!c)return;const u={},l=new Promise(e=>{u.cacheEntryRemoved=e}),p=Promise.race([new Promise(e=>{u.valueResolved=e}),l.then(()=>{throw sr})]);p.catch(()=>{}),d[a]=u;const f=e.endpoints[t].select(Nn(i)?r:a),h=s.dispatch((e,t,n)=>n),g={...s,getCacheEntry:()=>f(s.getState()),requestId:o,extra:h,updateCachedData:Nn(i)?n=>s.dispatch(e.util.updateQueryData(t,r,n)):void 0,cacheDataLoaded:p,cacheEntryRemoved:l},m=c(r,g);Promise.resolve(m).catch(e=>{if(e!==sr)throw e})}return(n,c,v)=>{const _=function(e){return o(e)?e.meta.arg.queryCacheKey:i(e)?e.meta.arg.fixedCacheKey??e.meta.requestId:l.match(e)?e.payload.queryCacheKey:p.match(e)?Bn(e.payload):""}(n);function b(e,t,n,r){const a=s(v,t),o=s(c.getState(),t);!a&&o&&y(e,r,t,c,n)}if(r.pending.match(n)){const[e,t,r]=m(n);b(e,_,r,t)}else if(f.match(n))for(const{queryDescription:e,value:t}of n.payload){const{endpointName:r,originalArgs:a,queryCacheKey:s}=e;b(r,s,n.meta.requestId,a),h(s,t,{})}else if(a.pending.match(n)){if(c.getState()[t].mutations[_]){const[e,t,r]=m(n);y(e,t,_,c,r)}}else if(u(n))h(_,n.payload,n.meta.baseQueryMeta);else if(l.match(n)||p.match(n))g(_);else if(e.util.resetApiState.match(n))for(const e of Object.keys(d))g(e)}},ir=({api:e,context:{apiUid:t},reducerPath:n})=>(r,a)=>{e.util.resetApiState.match(r)&&a.dispatch(e.internalActions.middlewareRegistered(t)),"undefined"!=typeof process&&"development"===process.env.NODE_ENV&&e.internalActions.middlewareRegistered.match(r)&&r.payload===t&&"conflict"===a.getState()[n]?.config?.middlewareRegistered&&console.warn(`There is a mismatch between slice and middleware for the reducerPath "${n}".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${"api"===n?"\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!":""}`)},cr=({reducerPath:e,context:t,context:{endpointDefinitions:n},mutationThunk:r,queryThunk:a,api:s,assertTagType:o,refetchQuery:d,internalState:l})=>{const{removeQueryResult:p}=s.internalActions,f=i(c(r),u(r)),g=i(c(a,r),h(a,r));let m=[],y=0;function v(n,r){const a=r.getState(),o=a[e];if(m.push(...n),"delayed"===o.config.invalidationBehavior&&y>0)return;const i=m;if(m=[],0===i.length)return;const c=s.util.selectInvalidatedBy(a,i);t.batch(()=>{const e=Array.from(c.values());for(const{queryCacheKey:t}of e){const e=o.queries[t],n=sn(l.currentSubscriptions,t,on);e&&(0===n.size?r.dispatch(p({queryCacheKey:t})):e.status!==Wt&&r.dispatch(d(e)))}})}return(e,t)=>{(a.pending.match(e)||r.pending.match(e))&&y++,g(e)&&(y=Math.max(0,y-1)),f(e)?v(Kn(e,"invalidatesTags",n,o),t):g(e)?v([],t):s.util.invalidateTags.match(e)&&v(Pn(e.payload,void 0,void 0,void 0,void 0,o),t)}},ur=({reducerPath:e,queryThunk:t,api:n,refetchQuery:r,internalState:a})=>{const{currentPolls:s,currentSubscriptions:o}=a,i=new Set;let c=null;function u(e,t){i.add(e),c||(c=setTimeout(()=>{for(const e of i)l({queryCacheKey:e},t);i.clear(),c=null},0))}function d({queryCacheKey:t},n){const a=n.getState()[e],i=a.queries[t],c=o.get(t);if(!i||i.status===Wt)return;const{lowestPollingInterval:u,skipPollingIfUnfocused:l}=f(c);if(!Number.isFinite(u))return;const p=s.get(t);p?.timeout&&(clearTimeout(p.timeout),p.timeout=void 0);const h=Date.now()+u;s.set(t,{nextPollTimestamp:h,pollingInterval:u,timeout:setTimeout(()=>{!a.config.focused&&l||n.dispatch(r(i)),d({queryCacheKey:t},n)},u)})}function l({queryCacheKey:t},n){const r=n.getState()[e].queries[t],a=o.get(t);if(!r||r.status===Wt)return;const{lowestPollingInterval:i}=f(a);if("test"===process.env.NODE_ENV){const e=s.pollUpdateCounters??={};e[t]??=0,e[t]++}if(!Number.isFinite(i))return void p(t);const c=s.get(t),u=Date.now()+i;(!c||u<c.nextPollTimestamp)&&d({queryCacheKey:t},n)}function p(e){const t=s.get(e);t?.timeout&&clearTimeout(t.timeout),s.delete(e)}function f(e=new Map){let t=!1,n=Number.POSITIVE_INFINITY;for(const r of e.values())r.pollingInterval&&(n=Math.min(r.pollingInterval,n),t=r.skipPollingIfUnfocused||t);return{lowestPollingInterval:n,skipPollingIfUnfocused:t}}return(e,r)=>{(n.internalActions.updateSubscriptionOptions.match(e)||n.internalActions.unsubscribeQueryResult.match(e))&&u(e.payload.queryCacheKey,r),(t.pending.match(e)||t.rejected.match(e)&&e.meta.condition)&&u(e.meta.arg.queryCacheKey,r),(t.fulfilled.match(e)||t.rejected.match(e)&&!e.meta.condition)&&d(e.meta.arg,r),n.util.resetApiState.match(e)&&(function(){for(const e of s.keys())p(e)}(),c&&(clearTimeout(c),c=null),i.clear())}},dr=({api:e,context:t,queryThunk:n,mutationThunk:r})=>{const a=g(n,r),s=h(n,r),o=c(n,r),i={};return(n,r)=>{if(a(n)){const{requestId:a,arg:{endpointName:s,originalArgs:o}}=n.meta,c=qn(t,s),u=c?.onQueryStarted;if(u){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),i[a]=t;const d=e.endpoints[s].select(Nn(c)?o:a),l=r.dispatch((e,t,n)=>n),p={...r,getCacheEntry:()=>d(r.getState()),requestId:a,extra:l,updateCachedData:Nn(c)?t=>r.dispatch(e.util.updateQueryData(s,o,t)):void 0,queryFulfilled:n};u(o,p)}}else if(o(n)){const{requestId:e,baseQueryMeta:t}=n.meta;i[e]?.resolve({data:n.payload,meta:t}),delete i[e]}else if(s(n)){const{requestId:e,rejectedWithValue:t,baseQueryMeta:r}=n.meta;i[e]?.reject({error:n.payload??n.error,isUnhandledError:!t,meta:r}),delete i[e]}}};var lr=Symbol(),pr=({createSelector:l=n}={})=>({name:lr,init(n,{baseQuery:v,tagTypes:_,reducerPath:b,serializeQueryArgs:S,keepUnusedDataFor:w,refetchOnMountOrArgChange:T,refetchOnFocus:E,refetchOnReconnect:I,invalidationBehavior:A,onSchemaFailure:R,catchSchemaFailure:k,skipSchemaValidation:O},C){!function(){"production"!==process.env.NODE_ENV&&Ie.push('Sets cannot have "replace" patches.',function(e){return"Unsupported patch operation: "+e},function(e){return"Cannot apply patch, path doesn't resolve: "+e},"Patching reserved attributes like __proto__, prototype and constructor is not allowed");const e="replace",t="add",n="remove";function r(e){if(!De(e))return e;if(He(e))return e.map(r);if(Ge(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(Be(e))return new Set(Array.from(e).map(r));const t=Object.create(ke(e));for(const n in e)t[n]=r(e[n]);return $e(e,Te)&&(t[Te]=e[Te]),t}function a(e){return Me(e)?r(e):e}var s;ot[s=at]||(ot[s]={applyPatches_:function(a,s){return s.forEach(s=>{const{path:o,op:i}=s;let c=a;for(let e=0;e<o.length-1;e++){const t=je(c);let n=o[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==Oe||Ae(19),We(c)&&n===Ce&&Ae(19),c=ze(c,n),Ve(c)||Ae(18,o.join("/"))}const u=je(c),d=r(s.value),l=o[o.length-1];switch(i){case e:switch(u){case 2:return c.set(l,d);case 3:Ae(16);default:return c[l]=d}case t:switch(u){case 1:return"-"===l?c.push(d):c.splice(l,0,d);case 2:return c.set(l,d);case 3:return c.add(d);default:return c[l]=d}case n:switch(u){case 1:return c.splice(l,1);case 2:return c.delete(l);case 3:return c.delete(s.value);default:return delete c[l]}default:Ae(17,i)}}),a},generatePatches_:function(r,s,o){if(r.scope_.processedForPatches_.has(r))return;r.scope_.processedForPatches_.add(r);const{patches_:i,inversePatches_:c}=o;switch(r.type_){case 0:case 2:return function(r,s,o,i){const{base_:c,copy_:u,type_:d}=r;Le(r.assigned_,(r,l)=>{const p=ze(c,r,d),f=ze(u,r,d),h=l?$e(c,r)?e:t:n;if(p===f&&h===e)return;const g=s.concat(r);o.push(h===n?{op:h,path:g}:{op:h,path:g,value:a(f)}),i.push(h===t?{op:n,path:g}:h===n?{op:t,path:g,value:a(p)}:{op:e,path:g,value:a(p)})})}(r,s,i,c);case 1:return function(r,s,o,i){let{base_:c,assigned_:u}=r,d=r.copy_;d.length<c.length&&([c,d]=[d,c],[o,i]=[i,o]);const l=!0===r.allIndicesReassigned_;for(let t=0;t<c.length;t++){const n=d[t],r=c[t];if((l||u?.get(t.toString()))&&n!==r){const c=n?.[Ee];if(c&&c.modified_)continue;const u=s.concat([t]);o.push({op:e,path:u,value:a(n)}),i.push({op:e,path:u,value:a(r)})}}for(let e=c.length;e<d.length;e++){const n=s.concat([e]);o.push({op:t,path:n,value:a(d[e])})}for(let e=d.length-1;c.length<=e;--e){const t=s.concat([e]);i.push({op:n,path:t})}}(r,s,i,c);case 3:return function(e,r,a,s){let{base_:o,copy_:i}=e,c=0;o.forEach(e=>{if(!i.has(e)){const o=r.concat([c]);a.push({op:n,path:o,value:e}),s.unshift({op:t,path:o,value:e})}c++}),c=0,i.forEach(e=>{if(!o.has(e)){const o=r.concat([c]);a.push({op:t,path:o,value:e}),s.unshift({op:n,path:o,value:e})}c++})}(r,s,i,c)}},generateReplacementPatches_:function(t,n,r){const{patches_:a,inversePatches_:s}=r;a.push({op:e,path:[],value:n===we?void 0:n}),s.push({op:e,path:[],value:t})},getPath:function e(t,n=[]){if(void 0!==t.key_){const e=t.parent_.copy_??t.parent_.base_,a=(r=ze(e,t.key_),Ve(r)?r?.[Ee]:null),s=ze(e,t.key_);if(void 0===s)return null;if(s!==t.draft_&&s!==t.base_&&s!==t.copy_)return null;if(null!=a&&a.base_!==t.base_)return null;const o=3===t.parent_.type_;let i;if(i=o?Array.from(t.parent_.drafts_.keys()).indexOf(t.key_):t.key_,!(o&&e.size>i||$e(e,i)))return null;n.push(i)}var r;if(t.parent_)return e(t.parent_,n);n.reverse();try{!function(e,t){let n=e;for(let e=0;e<t.length-1;e++)if(n=ze(n,t[e]),!Ve(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}(t.copy_,n)}catch(e){return null}return n}})}();const N=e=>("undefined"!=typeof process&&"development"===process.env.NODE_ENV&&(_.includes(e.type)||console.error(`Tag type '${e.type}' was used, but not specified in \`tagTypes\`!`)),e);Object.assign(n,{reducerPath:b,endpoints:{},internalActions:{onOnline:Tn,onOffline:En,onFocus:Sn,onFocusLost:wn},util:{}});const P=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>Zn,a=e=>Yn;return{buildQuerySelector:function(e,t){return u(e,t,s)},buildInfiniteQuerySelector:function(e,t){const{infiniteQueryOptions:n}=t;return u(e,t,function(e){const t={...e,...Yt(e.status)},{isLoading:r,isError:a,direction:s}=t,o="forward"===s,i="backward"===s;return{...t,hasNextPage:(c=n,u=t.data,l=t.originalArgs,!!u&&null!=$n(c,u,l)),hasPreviousPage:d(n,t.data,t.originalArgs),isFetchingNextPage:r&&o,isFetchingPreviousPage:r&&i,isFetchNextPageError:a&&o,isFetchPreviousPageError:a&&i};var c,u,l})},buildMutationSelector:function(){return e=>{let t;return t="object"==typeof e?Bn(e)??Jn:e,n(t===Jn?a:e=>o(e)?.mutations?.[t]??Yn,s)}},selectInvalidatedBy:function(e,n){const r=e[t],a=new Set,s=nn(n,rn,xn);for(const e of s){const t=r.provided.tags[e.type];if(!t)continue;let n=(void 0!==e.id?t[e.id]:Object.values(t).flat())??[];for(const e of n)a.add(e)}return Array.from(a.values()).flatMap(e=>{const t=r.queries[e];return t?{queryCacheKey:e,endpointName:t.endpointName,originalArgs:t.originalArgs}:[]})},selectCachedArgsForQuery:function(e,t){return nn(Object.values(i(e)),e=>e?.endpointName===t&&e.status!==Wt,e=>e.originalArgs)},selectApiState:o,selectQueries:i,selectMutations:function(e){return o(e)?.mutations},selectQueryEntry:c,selectConfig:function(e){return o(e)?.config}};function s(e){return{...e,...Yt(e.status)}}function o(e){const n=e[t];if("production"!==process.env.NODE_ENV&&!n){if(o.triggered)return n;o.triggered=!0,console.error(`Error: No data found at \`state.${t}\`. Did you forget to add the reducer to the store?`)}return n}function i(e){return o(e)?.queries}function c(e,t){return i(e)?.[t]}function u(t,a,s){return o=>{if(o===Jn)return n(r,s);const i=e({queryArgs:o,endpointDefinition:a,endpointName:t});return n(e=>c(e,i)??Zn,s)}}function d(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=zn(e,t,n)}}({serializeQueryArgs:S,reducerPath:b,createSelector:l}),{selectInvalidatedBy:x,selectCachedArgsForQuery:q,buildQuerySelector:M,buildInfiniteQuerySelector:D,buildMutationSelector:Q}=P;rr(n.util,{selectInvalidatedBy:x,selectCachedArgsForQuery:q});const{queryThunk:F,infiniteQueryThunk:U,mutationThunk:L,patchQueryData:j,updateQueryData:$,upsertQueryData:z,prefetch:K,buildMatchThunkActions:H}=function({reducerPath:e,baseQuery:t,context:{endpointDefinitions:n},serializeQueryArgs:r,api:s,assertTagType:o,selectors:i,onSchemaFailure:u,catchSchemaFailure:d,skipSchemaValidation:l}){function p(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}function m(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}const y=(e,t)=>e.query&&e[t]?e[t]:Ln,v=async(e,{signal:r,abort:a,rejectWithValue:s,fulfillWithValue:o,dispatch:c,getState:f,extra:h})=>{const g=n[e.endpointName],{metaSchema:v,skipSchemaValidation:b=l}=g,S=e.type===An;try{let w=Ln;const T={signal:r,abort:a,dispatch:c,getState:f,extra:h,endpoint:e.endpointName,type:e.type,forced:S?_(e,f()):void 0,queryCacheKey:S?e.queryCacheKey:void 0},E=S?e[Mn]:void 0;let I;const A=async(t,n,r,a)=>{if(null==n&&t.pages.length)return Promise.resolve({data:t});const s={queryArg:e.originalArgs,pageParam:n},o=await R(s),i=a?p:m;return{data:{pages:i(t.pages,o.data,r),pageParams:i(t.pageParams,n,r)},meta:o.meta}};async function R(n){let r;const{extraOptions:a,argSchema:s,rawResponseSchema:o,responseSchema:i}=g;if(s&&!Fn(b,"arg")&&(n=await Un(s,n,"argSchema",{})),E?r=E():g.query?(w=y(g,"transformResponse"),r=await t(g.query(n),T,a)):r=await g.queryFn(n,T,a,e=>t(e,T,a)),"undefined"!=typeof process&&"development"===process.env.NODE_ENV){const t=g.query?"`baseQuery`":"`queryFn`";let n;if(r){if("object"!=typeof r)n=`${t} did not return an object.`;else if(r.error&&r.data)n=`${t} returned an object containing both \`error\` and \`result\`.`;else if(void 0===r.error&&void 0===r.data)n=`${t} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;else for(const e of Object.keys(r))if("error"!==e&&"data"!==e&&"meta"!==e){n=`The object returned by ${t} has the unknown property ${e}.`;break}}else n=`${t} did not return anything.`;n&&console.error(`Error encountered handling the endpoint ${e.endpointName}.\n ${n}\n It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.\n Object returned was:`,r)}if(r.error)throw new hn(r.error,r.meta);let{data:c}=r;o&&!Fn(b,"rawResponse")&&(c=await Un(o,r.data,"rawResponseSchema",r.meta));let u=await w(c,r.meta,n);return i&&!Fn(b,"response")&&(u=await Un(i,u,"responseSchema",r.meta)),{...r,data:u}}if(S&&"infiniteQueryOptions"in g){const{infiniteQueryOptions:k}=g,{maxPages:O=1/0}=k,C=e.refetchCachedPages??k.refetchCachedPages??!0;let N;const P={pages:[],pageParams:[]},x=i.selectQueryEntry(f(),e.queryCacheKey)?.data,q=_(e,f())&&!e.direction||!x?P:x;if("direction"in e&&e.direction&&q.pages.length){const M="backward"===e.direction,D=(M?zn:$n)(k,q,e.originalArgs);N=await A(q,D,O,M)}else{const{initialPageParam:Q=k.initialPageParam}=e,F=x?.pageParams??[],U=F[0]??Q,L=F.length;if(N=await A(q,U,O),E&&(N={data:N.data.pages[0]}),C)for(let j=1;j<L;j++){const $=$n(k,N.data,e.originalArgs);N=await A(N.data,$,O)}}I=N}else I=await R(e.originalArgs);return v&&!Fn(b,"meta")&&I.meta&&(I.meta=await Un(v,I.meta,"metaSchema",I.meta)),o(I.data,jn({fulfilledTimeStamp:Date.now(),baseQueryMeta:I.meta}))}catch(z){let K=z;if(K instanceof hn){let H=y(g,"transformErrorResponse");const{rawErrorResponseSchema:G,errorResponseSchema:B}=g;let{value:V,meta:W}=K;try{G&&!Fn(b,"rawErrorResponse")&&(V=await Un(G,V,"rawErrorResponseSchema",W)),v&&!Fn(b,"meta")&&(W=await Un(v,W,"metaSchema",W));let J=await H(V,W,e.originalArgs);return B&&!Fn(b,"errorResponse")&&(J=await Un(B,J,"errorResponseSchema",W)),s(J,jn({baseQueryMeta:W}))}catch(X){K=X}}try{if(K instanceof Qn){const Z={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:S?e.queryCacheKey:void 0};g.onSchemaFailure?.(K,Z),u?.(K,Z);const{catchSchemaFailure:Y=d}=g;if(Y)return s(Y(K,Z),jn({baseQueryMeta:K._bqMeta}))}}catch(ee){K=ee}throw"undefined"!=typeof process&&"production"!==process.env.NODE_ENV?console.error(`An unhandled error occurred processing a request for the endpoint "${e.endpointName}".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,K):console.error(K),K}};function _(e,t){const n=i.selectQueryEntry(t,e.queryCacheKey),r=i.selectConfig(t).refetchOnMountOrArgChange,a=n?.fulfilledTimeStamp,s=e.forceRefetch??(e.subscribe&&r);return!!s&&(!0===s||(Number(new Date)-Number(a))/1e3>=s)}const b=()=>a(`${e}/executeQuery`,v,{getPendingMeta({arg:e}){const t=n[e.endpointName];return jn({startedTimeStamp:Date.now(),...Cn(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const r=t(),a=i.selectQueryEntry(r,e.queryCacheKey),s=a?.fulfilledTimeStamp,o=e.originalArgs,c=a?.originalArgs,u=n[e.endpointName],d=e.direction;return!(!Dn(e)&&("pending"===a?.status||!_(e,r)&&(!On(u)||!u?.forceRefetch?.({currentArg:o,previousArg:c,endpointState:a,state:r}))&&s&&!d))},dispatchConditionRejection:!0}),S=b(),w=b();function T(e){return t=>t?.meta?.arg?.endpointName===e}return{queryThunk:S,mutationThunk:a(`${e}/executeMutation`,v,{getPendingMeta:()=>jn({startedTimeStamp:Date.now()})}),infiniteQueryThunk:w,prefetch:(e,t,n={})=>(r,a)=>{const o=(e=>"force"in e)(n)&&n.force,i=(e=>"ifOlderThan"in e)(n)&&n.ifOlderThan,c=(n=!0)=>s.endpoints[e].initiate(t,{forceRefetch:n,subscribe:!1}),u=s.endpoints[e].select(t)(a());if(o)r(c());else if(i){const e=u?.fulfilledTimeStamp;if(!e)return void r(c());(Number(new Date)-Number(new Date(e)))/1e3>=i&&r(c())}else r(c(!1))},updateQueryData:(e,t,n,r=!0)=>(a,o)=>{const i=s.endpoints[e].select(t)(o()),c={patches:[],inversePatches:[],undo:()=>a(s.util.patchQueryData(e,t,c.inversePatches,r))};if(i.status===Wt)return c;let u;if("data"in i)if(De(i.data)){const[e,t,r]=qt(i.data,n);c.patches.push(...t),c.inversePatches.push(...r),u=e}else u=n(i.data),c.patches.push({op:"replace",path:[],value:u}),c.inversePatches.push({op:"replace",path:[],value:i.data});return 0===c.patches.length||a(s.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(s.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[Mn]:()=>({data:n})})),patchQueryData:(e,t,a,i)=>(c,u)=>{const d=n[e],l=r({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(s.internalActions.queryResultPatched({queryCacheKey:l,patches:a})),!i)return;const p=s.endpoints[e].select(t)(u()),f=Pn(d.providesTags,p.data,void 0,t,{},o);c(s.internalActions.updateProvidedBy([{queryCacheKey:l,providedTags:f}]))},buildMatchThunkActions:function(e,t){return{matchPending:f(g(e),T(t)),matchFulfilled:f(c(e),T(t)),matchRejected:f(h(e),T(t))}}}}({baseQuery:v,reducerPath:b,context:C,api:n,serializeQueryArgs:S,assertTagType:N,selectors:P,onSchemaFailure:R,catchSchemaFailure:k,skipSchemaValidation:O}),{reducer:G,actions:B}=function({reducerPath:t,queryThunk:n,mutationThunk:a,serializeQueryArgs:l,context:{endpointDefinitions:f,apiUid:h,extractRehydrationInfo:g,hasRehydrationInfo:m},assertTagType:v,config:_}){const b=r(`${t}/resetApiState`);function S(e,t,n,r){e[t.queryCacheKey]??={status:Wt,endpointName:t.endpointName},Gn(e,t.queryCacheKey,e=>{e.status=Jt,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp,Cn(f[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function w(e,t,n,r){Gn(e,t.arg.queryCacheKey,e=>{if(e.requestId!==t.requestId&&!r)return;const{merge:a}=f[t.arg.endpointName];if(e.status=Xt,a)if(void 0!==e.data){const{fulfilledTimeStamp:r,arg:s,baseQueryMeta:o,requestId:i}=t;let c=y(e.data,e=>a(e,n,{arg:s.originalArgs,baseQueryMeta:o,fulfilledTimeStamp:r,requestId:i}));e.data=c}else e.data=n;else e.data=f[t.arg.endpointName].structuralSharing??1?tn(Me(e.data)?(Me(s=e.data)||Ae(15,s),s[Ee].base_):e.data,n):n;var s;delete e.error,e.fulfilledTimeStamp=t.fulfilledTimeStamp})}const T=s({name:`${t}/queries`,initialState:Wn,reducers:{removeQueryResult:{reducer(e,{payload:{queryCacheKey:t}}){delete e[t]},prepare:o()},cacheEntriesUpserted:{reducer(e,t){for(const n of t.payload){const{queryDescription:r,value:a}=n;S(e,r,!0,{arg:r,requestId:t.meta.requestId,startedTimeStamp:t.meta.timestamp}),w(e,{arg:r,requestId:t.meta.requestId,fulfilledTimeStamp:t.meta.timestamp,baseQueryMeta:{}},a,!0)}},prepare:t=>({payload:t.map(e=>{const{endpointName:t,arg:n,value:r}=e;return{queryDescription:{type:An,endpointName:t,originalArgs:e.arg,queryCacheKey:l({queryArgs:n,endpointDefinition:f[t],endpointName:t})},value:r}}),meta:{[p]:!0,requestId:e(),timestamp:Date.now()}})},queryResultPatched:{reducer(e,{payload:{queryCacheKey:t,patches:n}}){Gn(e,t,e=>{e.data=Mt(e.data,n.concat())})},prepare:o()}},extraReducers(e){e.addCase(n.pending,(e,{meta:t,meta:{arg:n}})=>{S(e,n,Dn(n),t)}).addCase(n.fulfilled,(e,{meta:t,payload:n})=>{w(e,t,n,Dn(t.arg))}).addCase(n.rejected,(e,{meta:{condition:t,arg:n,requestId:r},error:a,payload:s})=>{Gn(e,n.queryCacheKey,e=>{if(t);else{if(e.requestId!==r)return;e.status=Zt,e.error=s??a}})}).addMatcher(m,(e,t)=>{const{queries:n}=g(t);for(const[t,r]of Object.entries(n))r?.status!==Xt&&r?.status!==Zt||(e[t]=r)})}}),E=s({name:`${t}/mutations`,initialState:Wn,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=Bn(t);n in e&&delete e[n]},prepare:o()}},extraReducers(e){e.addCase(a.pending,(e,{meta:t,meta:{requestId:n,arg:r,startedTimeStamp:a}})=>{r.track&&(e[Bn(t)]={requestId:n,status:Jt,endpointName:r.endpointName,startedTimeStamp:a})}).addCase(a.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&Vn(e,n,e=>{e.requestId===n.requestId&&(e.status=Xt,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(a.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&Vn(e,r,e=>{e.requestId===r.requestId&&(e.status=Zt,e.error=t??n)})}).addMatcher(m,(e,t)=>{const{mutations:n}=g(t);for(const[t,r]of Object.entries(n))r?.status!==Xt&&r?.status!==Zt||t===r?.requestId||(e[t]=r)})}}),I=s({name:`${t}/invalidation`,initialState:{tags:{},keys:{}},reducers:{updateProvidedBy:{reducer(e,t){for(const{queryCacheKey:n,providedTags:r}of t.payload){A(e,n);for(const{type:t,id:a}of r){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];r.includes(n)||r.push(n)}e.keys[n]=r}},prepare:o()}},extraReducers(e){e.addCase(T.actions.removeQueryResult,(e,{payload:{queryCacheKey:t}})=>{A(e,t)}).addMatcher(m,(e,t)=>{const{provided:n}=g(t);for(const[t,r]of Object.entries(n.tags??{}))for(const[a,s]of Object.entries(r)){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];for(const t of s)r.includes(t)||r.push(t),e.keys[t]=n.keys[t]}}).addMatcher(i(c(n),u(n)),(e,t)=>{R(e,[t])}).addMatcher(T.actions.cacheEntriesUpserted.match,(e,t)=>{R(e,t.payload.map(({queryDescription:e,value:t})=>({type:"UNKNOWN",payload:t,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:e}})))})}});function A(e,t){const n=Hn(e.keys[t]??[]);for(const r of n){const n=r.type,a=r.id??"__internal_without_id",s=e.tags[n]?.[a];s&&(e.tags[n][a]=Hn(s).filter(e=>e!==t))}delete e.keys[t]}function R(e,t){const n=t.map(e=>{const t=Kn(e,"providesTags",f,v),{queryCacheKey:n}=e.meta.arg;return{queryCacheKey:n,providedTags:t}});I.caseReducers.updateProvidedBy(e,I.actions.updateProvidedBy(n))}const k=s({name:`${t}/subscriptions`,initialState:Wn,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),O=s({name:`${t}/internalSubscriptions`,initialState:Wn,reducers:{subscriptionsUpdated:{reducer:(e,t)=>Mt(e,t.payload),prepare:o()}}}),C=s({name:`${t}/config`,initialState:{online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine,focused:"undefined"==typeof document||"hidden"!==document.visibilityState,middlewareRegistered:!1,..._},reducers:{middlewareRegistered(e,{payload:t}){e.middlewareRegistered="conflict"!==e.middlewareRegistered&&h===t||"conflict"}},extraReducers:e=>{e.addCase(Tn,e=>{e.online=!0}).addCase(En,e=>{e.online=!1}).addCase(Sn,e=>{e.focused=!0}).addCase(wn,e=>{e.focused=!1}).addMatcher(m,e=>({...e}))}}),N=d({queries:T.reducer,mutations:E.reducer,provided:I.reducer,subscriptions:O.reducer,config:C.reducer});return{reducer:(e,t)=>N(b.match(t)?void 0:e,t),actions:{...C.actions,...T.actions,...k.actions,...O.actions,...E.actions,...I.actions,resetApiState:b}}}({context:C,queryThunk:F,mutationThunk:L,serializeQueryArgs:S,reducerPath:b,assertTagType:N,config:{refetchOnFocus:E,refetchOnReconnect:I,refetchOnMountOrArgChange:T,keepUnusedDataFor:w,reducerPath:b,invalidationBehavior:A}});rr(n.util,{patchQueryData:j,updateQueryData:$,upsertQueryData:z,prefetch:K,resetApiState:B.resetApiState,upsertQueryEntries:B.cacheEntriesUpserted}),rr(n.internalActions,B);const V=new WeakMap,W=e=>sn(V,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:J,buildInitiateInfiniteQuery:X,buildInitiateMutation:Z,getRunningMutationThunk:Y,getRunningMutationsThunk:ee,getRunningQueriesThunk:te,getRunningQueryThunk:ne}=function({serializeQueryArgs:e,queryThunk:n,infiniteQueryThunk:r,mutationThunk:a,api:s,context:o,getInternalState:i}){const c=e=>i(e)?.runningQueries,u=e=>i(e)?.runningMutations,{unsubscribeQueryResult:d,removeMutationResult:l,updateSubscriptionOptions:p}=s.internalActions;return{buildInitiateQuery:function(e,t){return h(e,t)},buildInitiateInfiniteQuery:function(e,t){return h(e,t)},buildInitiateMutation:function(e){return(t,{track:n=!0,fixedCacheKey:r}={})=>(s,o)=>{const i=a({type:"mutation",endpointName:e,originalArgs:t,track:n,fixedCacheKey:r}),c=s(i);f(s);const{requestId:d,abort:p,unwrap:h}=c,g=c.unwrap().then(e=>({data:e})).catch(e=>({error:e})),m=Object.assign(g,{arg:c.arg,requestId:d,abort:p,unwrap:h,reset:()=>{s(l({requestId:d,fixedCacheKey:r}))}}),y=u(s);return y.set(d,m),m.then(()=>{y.delete(d)}),r&&(y.set(r,m),m.then(()=>{y.get(r)===m&&y.delete(r)})),m}},getRunningQueryThunk:function(t,n){return r=>{const a=qn(o,t),s=e({queryArgs:n,endpointDefinition:a,endpointName:t});return c(r)?.get(s)}},getRunningMutationThunk:function(e,t){return e=>u(e)?.get(t)},getRunningQueriesThunk:function(){return e=>an(c(e))},getRunningMutationsThunk:function(){return e=>an(u(e))}};function f(e){if("production"!==process.env.NODE_ENV){if(f.triggered)return;const n=e(s.internalActions.internal_getRTKQSubscriptions());if(f.triggered=!0,"object"!=typeof n||"string"==typeof n?.type)throw new Error("production"===process.env.NODE_ENV?t(34):`Warning: Middleware for RTK-Query API at reducerPath "${s.reducerPath}" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`)}}function h(t,a){const o=(i,{subscribe:u=!0,forceRefetch:l,subscriptionOptions:h,[Mn]:g,...m}={})=>(y,v)=>{const _=e({queryArgs:i,endpointDefinition:a,endpointName:t});let b;const S={...m,type:An,subscribe:u,forceRefetch:l,subscriptionOptions:h,endpointName:t,originalArgs:i,queryCacheKey:_,[Mn]:g};if(On(a))b=n(S);else{const{direction:e,initialPageParam:t,refetchCachedPages:n}=m;b=r({...S,direction:e,initialPageParam:t,refetchCachedPages:n})}const w=s.endpoints[t].select(i),T=y(b),E=w(v());f(y);const{requestId:I,abort:A}=T,R=E.requestId!==I,k=c(y)?.get(_),O=()=>w(v()),C=Object.assign(g?T.then(O):R&&!k?Promise.resolve(E):Promise.all([k,T]).then(O),{arg:i,requestId:I,subscriptionOptions:h,queryCacheKey:_,abort:A,async unwrap(){const e=await C;if(e.isError)throw e.error;return e.data},refetch:e=>y(o(i,{subscribe:!1,forceRefetch:!0,...e})),unsubscribe(){u&&y(d({queryCacheKey:_,requestId:I}))},updateSubscriptionOptions(e){C.subscriptionOptions=e,y(p({endpointName:t,requestId:I,queryCacheKey:_,options:e}))}});if(!k&&!R&&!g){const e=c(y);e.set(_,C),C.then(()=>{e.delete(_)})}return C};return o}}({queryThunk:F,mutationThunk:L,infiniteQueryThunk:U,api:n,serializeQueryArgs:S,context:C,getInternalState:W});rr(n.util,{getRunningMutationThunk:Y,getRunningMutationsThunk:ee,getRunningQueryThunk:ne,getRunningQueriesThunk:te});const{middleware:re,actions:ae}=function(e){const{reducerPath:t,api:n,context:a,getInternalState:s}=e,{apiUid:o}=a,i={invalidateTags:r(`${t}/invalidateTags`)},c=e=>e.type.startsWith(`${t}/`),u=[ir,ar,cr,ur,or,dr];return{middleware:r=>{let i=!1;const l=s(r.dispatch),p={...e,internalState:l,refetchQuery:d,isThisApiSliceAction:c,mwApi:r},f=u.map(e=>e(p)),h=(({api:e,queryThunk:t,internalState:n})=>{const r=`${e.reducerPath}/subscriptions`;let a=null,s=null;const{updateSubscriptionOptions:o,unsubscribeQueryResult:i}=e.internalActions,c=()=>n.currentSubscriptions,u={getSubscriptions:c,getSubscriptionCount:e=>{const t=c().get(e);return t?.size??0},isRequestSubscribed:(e,t)=>{const n=c();return!!n?.get(e)?.get(t)}};function d(e){return JSON.parse(JSON.stringify(Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)]))))}return(c,l)=>{if(a||(a=d(n.currentSubscriptions)),e.util.resetApiState.match(c))return a={},n.currentSubscriptions.clear(),s=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(c))return[!1,u];const p=((n,r)=>{if(o.match(r)){const{queryCacheKey:e,requestId:t,options:a}=r.payload,s=n.get(e);return s?.has(t)&&s.set(t,a),!0}if(i.match(r)){const{queryCacheKey:e,requestId:t}=r.payload,a=n.get(e);return a&&a.delete(t),!0}if(e.internalActions.removeQueryResult.match(r))return n.delete(r.payload.queryCacheKey),!0;if(t.pending.match(r)){const{meta:{arg:e,requestId:t}}=r,a=sn(n,e.queryCacheKey,on);return e.subscribe&&a.set(t,e.subscriptionOptions??a.get(t)??{}),!0}let a=!1;if(t.rejected.match(r)){const{meta:{condition:e,arg:t,requestId:s}}=r;if(e&&t.subscribe){const e=sn(n,t.queryCacheKey,on);e.set(s,t.subscriptionOptions??e.get(s)??{}),a=!0}}return a})(n.currentSubscriptions,c);let f=!0;if("test"===process.env.NODE_ENV&&"string"==typeof c.type&&c.type===`${e.reducerPath}/getPolling`)return[!1,n.currentPolls];if(p){s||(s=setTimeout(()=>{const t=d(n.currentSubscriptions),[,r]=qt(a,()=>t);l.next(e.internalActions.subscriptionsUpdated(r)),a=t,s=null},500));const o="string"==typeof c.type&&!!c.type.startsWith(r),i=t.rejected.match(c)&&c.meta.condition&&!!c.meta.arg.subscribe;f=!o&&!i}return[f,!1]}})(p),g=(({reducerPath:e,context:t,api:n,refetchQuery:r,internalState:a})=>{const{removeQueryResult:s}=n.internalActions;function o(n,o){const i=n.getState()[e],c=i.queries,u=a.currentSubscriptions;t.batch(()=>{for(const e of u.keys()){const t=c[e],a=u.get(e);if(!a||!t)continue;const d=[...a.values()];(d.some(e=>!0===e[o])||d.every(e=>void 0===e[o])&&i.config[o])&&(0===a.size?n.dispatch(s({queryCacheKey:e})):t.status!==Wt&&n.dispatch(r(t)))}})}return(e,t)=>{Sn.match(e)&&o(t,"refetchOnFocus"),Tn.match(e)&&o(t,"refetchOnReconnect")}})(p);return e=>s=>{if(!m(s))return e(s);i||(i=!0,r.dispatch(n.internalActions.middlewareRegistered(o)));const u={...r,next:e},d=r.getState(),[l,p]=h(s,u,d);let y;if(y=l?e(s):p,r.getState()[t]&&(g(s,u,d),c(s)||a.hasRehydrationInfo(s)))for(const e of f)e(s,u,d);return y}},actions:i};function d(t){return e.api.endpoints[t.endpointName].initiate(t.originalArgs,{subscribe:!1,forceRefetch:!0})}}({reducerPath:b,context:C,queryThunk:F,mutationThunk:L,infiniteQueryThunk:U,api:n,assertTagType:N,selectors:P,getRunningQueryThunk:ne,getInternalState:W});return rr(n.util,ae),rr(n,{reducer:G,middleware:re}),{name:lr,injectEndpoint(e,t){const r=n,a=r.endpoints[e]??={};On(t)&&rr(a,{name:e,select:M(e,t),initiate:J(e,t)},H(F,e)),t.type===Rn&&rr(a,{name:e,select:Q(),initiate:Z(e)},H(L,e)),Cn(t)&&rr(a,{name:e,select:D(e,t),initiate:X(e,t)},H(F,e))}}}});function fr(e){return e.replace(e[0],e[0].toUpperCase())}function hr(e){let t=0;for(const n in e)t++;return t}function gr(e){return"infinitequery"===e.type}function mr(e,...t){return Object.assign(e,...t)}pr();var yr=Symbol();function vr(e){const t=C(e),n=R(()=>tn(t.current,e),[e]);return O(()=>{t.current!==n&&(t.current=n)},[n]),n}function _r(e){const t=C(e);return O(()=>{E(t.current,e)||(t.current=e)},[e]),E(t.current,e)?t.current:e}var br=(()=>!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement))(),Sr=(()=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product)(),wr=(()=>br||Sr?N:O)(),Tr=e=>e.isUninitialized?{...e,isUninitialized:!1,isFetching:!0,isLoading:void 0===e.data,status:Vt.pending}:e;function Er(e,...t){const n={};return t.forEach(t=>{n[t]=e[t]}),n}var Ir=["data","status","isLoading","isSuccess","isError","error"],Ar=Symbol(),Rr=nr(pr(),(({batch:e=T,hooks:n={useDispatch:w,useSelector:S,useStore:b},createSelector:r=Gt,unstable__sideEffectsInRender:a=!1,...s}={})=>{if("production"!==process.env.NODE_ENV){const e=["useDispatch","useSelector","useStore"];let r=!1;for(const a of e)if(hr(s)>0&&(s[a]&&(r||(console.warn("As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`"),r=!0)),n[a]=s[a]),"function"!=typeof n[a])throw new Error("production"===process.env.NODE_ENV?t(36):`When using custom hooks for context, all ${e.length} hooks need to be provided: ${e.join(", ")}.\nHook ${a} was either not provided or not a function.`)}return{name:Ar,init(s,{serializeQueryArgs:o},i){const c=s,{buildQueryHooks:u,buildInfiniteQueryHooks:d,buildMutationHook:l,usePrefetch:p}=function({api:e,moduleOptions:{batch:n,hooks:{useDispatch:r,useSelector:a,useStore:s},unstable__sideEffectsInRender:o,createSelector:i},serializeQueryArgs:c,context:u}){const d=o?e=>e():O,l=e=>e.current?.unsubscribe?.(),p=u.endpointDefinitions;return{buildQueryHooks:function(a){const s=(e,n={})=>{const[r]=g(a,e,n);return y(r),R(()=>({refetch:()=>function(e){if(!e.current)throw new Error("production"===process.env.NODE_ENV?t(38):"Cannot refetch a query that has not been started yet.");return e.current.refetch()}(r)}),[r])},o=({refetchOnReconnect:t,refetchOnFocus:s,pollingInterval:o=0,skipPollingIfUnfocused:i=!1}={})=>{const{initiate:c}=e.endpoints[a],u=r(),[p,f]=k(yr),h=C(void 0),g=_r({refetchOnReconnect:t,refetchOnFocus:s,pollingInterval:o,skipPollingIfUnfocused:i});d(()=>{const e=h.current?.subscriptionOptions;g!==e&&h.current?.updateSubscriptionOptions(g)},[g]);const m=C(g);d(()=>{m.current=g},[g]);const y=I(function(e,t=!1){let r;return n(()=>{l(h),h.current=r=u(c(e,{subscriptionOptions:m.current,forceRefetch:!t})),f(e)}),r},[u,c]),v=I(()=>{h.current?.queryCacheKey&&u(e.internalActions.removeQueryResult({queryCacheKey:h.current?.queryCacheKey}))},[u]);return O(()=>()=>{l(h)},[]),O(()=>{p===yr||h.current||y(p,!0)},[p,y]),R(()=>[y,p,{reset:v}],[y,p,v])},i=m(a,f);return{useQueryState:i,useQuerySubscription:s,useLazyQuerySubscription:o,useLazyQuery(e){const[t,n,{reset:r}]=o(e),a=i(n,{...e,skip:n===yr}),s=R(()=>({lastArg:n}),[n]);return R(()=>[t,{...a,reset:r},s],[t,a,r,s])},useQuery(e,t){const n=s(e,t),r=i(e,{selectFromResult:e===Jn||t?.skip?void 0:Tr,...t}),a=Er(r,...Ir);return A(a),R(()=>({...r,...n}),[r,n])}}},buildInfiniteQueryHooks:function(e){const r=(r,a={})=>{const[s,o,i,c]=g(e,r,a),u=C(c);d(()=>{u.current=c},[c]);const p=_r(a.refetchCachedPages),f=I(function(e,t){let r;return n(()=>{l(s),s.current=r=o(i(e,{subscriptionOptions:u.current,direction:t}))}),r},[s,o,i]);y(s);const h=vr(a.skip?Jn:r),m=I(e=>{if(!s.current)throw new Error("production"===process.env.NODE_ENV?t(38):"Cannot refetch a query that has not been started yet.");return s.current.refetch({refetchCachedPages:e?.refetchCachedPages??p})},[s,p]);return R(()=>({trigger:f,refetch:m,fetchNextPage:()=>f(h,"forward"),fetchPreviousPage:()=>f(h,"backward")}),[m,f,h])},a=m(e,h);return{useInfiniteQueryState:a,useInfiniteQuerySubscription:r,useInfiniteQuery(e,t){const{refetch:n,fetchNextPage:s,fetchPreviousPage:o}=r(e,t),i=a(e,{selectFromResult:e===Jn||t?.skip?void 0:Tr,...t}),c=Er(i,...Ir,"hasNextPage","hasPreviousPage");return A(c),R(()=>({...i,fetchNextPage:s,fetchPreviousPage:o,refetch:n}),[i,s,o,n])}}},buildMutationHook:function(t){return({selectFromResult:s,fixedCacheKey:o}={})=>{const{select:c,initiate:u}=e.endpoints[t],d=r(),[l,p]=k();O(()=>()=>{l?.arg.fixedCacheKey||l?.reset()},[l]);const f=I(function(e){const t=d(u(e,{fixedCacheKey:o}));return p(t),t},[d,u,o]),{requestId:h}=l||{},g=R(()=>c({fixedCacheKey:o,requestId:l?.requestId}),[o,l,c]),m=R(()=>s?i([g],s):g,[s,g]),y=a(m,E),v=null==o?l?.arg.originalArgs:void 0,_=I(()=>{n(()=>{l&&p(void 0),o&&d(e.internalActions.removeMutationResult({requestId:h,fixedCacheKey:o}))})},[d,o,l,h]),b=Er(y,...Ir,"endpointName");A(b);const S=R(()=>({...y,originalArgs:v,reset:_}),[y,v,_]);return R(()=>[f,S],[f,S])}},usePrefetch:function(t,n){const a=r(),s=_r(n);return I((n,r)=>a(e.util.prefetch(t,n,{...s,...r})),[t,a,s])}};function f(e,t,n){if(t?.endpointName&&e.isUninitialized){const{endpointName:e}=t,r=p[e];n!==Jn&&c({queryArgs:t.originalArgs,endpointDefinition:r,endpointName:e})===c({queryArgs:n,endpointDefinition:r,endpointName:e})&&(t=void 0)}let r=e.isSuccess?e.data:t?.data;void 0===r&&(r=e.data);const a=void 0!==r,s=e.isLoading,o=(!t||t.isLoading||t.isUninitialized)&&!a&&s,i=e.isSuccess||a&&(s&&!t?.isError||e.isUninitialized);return{...e,data:r,currentData:e.data,isFetching:s,isLoading:o,isSuccess:i}}function h(e,t,n){if(t?.endpointName&&e.isUninitialized){const{endpointName:e}=t,r=p[e];n!==Jn&&c({queryArgs:t.originalArgs,endpointDefinition:r,endpointName:e})===c({queryArgs:n,endpointDefinition:r,endpointName:e})&&(t=void 0)}let r=e.isSuccess?e.data:t?.data;void 0===r&&(r=e.data);const a=void 0!==r,s=e.isLoading,o=(!t||t.isLoading||t.isUninitialized)&&!a&&s,i=e.isSuccess||s&&a;return{...e,data:r,currentData:e.data,isFetching:s,isLoading:o,isSuccess:i}}function g(n,a,{refetchOnReconnect:s,refetchOnFocus:o,refetchOnMountOrArgChange:i,skip:c=!1,pollingInterval:u=0,skipPollingIfUnfocused:l=!1,...f}={}){const{initiate:h}=e.endpoints[n],g=r(),m=C(void 0);if(!m.current){const n=g(e.internalActions.internal_getRTKQSubscriptions());if("production"!==process.env.NODE_ENV&&("object"!=typeof n||"string"==typeof n?.type))throw new Error("production"===process.env.NODE_ENV?t(37):`Warning: Middleware for RTK-Query API at reducerPath "${e.reducerPath}" has not been added to the store.\n You must add the middleware for RTK-Query to function correctly!`);m.current=n}const y=vr(c?Jn:a),v=_r({refetchOnReconnect:s,refetchOnFocus:o,pollingInterval:u,skipPollingIfUnfocused:l}),_=_r(f.initialPageParam),b=_r(f.refetchCachedPages),S=C(void 0);let{queryCacheKey:w,requestId:T}=S.current||{},E=!1;w&&T&&(E=m.current.isRequestSubscribed(w,T));const I=!E&&void 0!==S.current;return d(()=>{I&&(S.current=void 0)},[I]),d(()=>{const e=S.current;if("undefined"!=typeof process&&process,y===Jn)return e?.unsubscribe(),void(S.current=void 0);const t=S.current?.subscriptionOptions;if(e&&e.arg===y)v!==t&&e.updateSubscriptionOptions(v);else{e?.unsubscribe();const t=g(h(y,{subscriptionOptions:v,forceRefetch:i,...gr(p[n])?{initialPageParam:_,refetchCachedPages:b}:{}}));S.current=t}},[g,h,i,y,v,I,_,b,n]),[S,g,h,v]}function m(t,n){return(r,{skip:o=!1,selectFromResult:c}={})=>{const{select:u}=e.endpoints[t],d=vr(o?Jn:r),l=C(void 0),p=R(()=>i([u(d),(e,t)=>t,e=>d],n,{memoizeOptions:{resultEqualityCheck:E}}),[u,d]),f=R(()=>c?i([p],c,{devModeChecks:{identityFunctionCheck:"never"}}):p,[p,c]),h=a(e=>f(e,l.current),E),g=s(),m=p(g.getState(),l.current);return wr(()=>{l.current=m},[m]),h}}function y(e){O(()=>()=>{l(e),e.current=void 0},[e])}}({api:s,moduleOptions:{batch:e,hooks:n,unstable__sideEffectsInRender:a,createSelector:r},serializeQueryArgs:o,context:i});return mr(c,{usePrefetch:p}),mr(i,{batch:e}),{injectEndpoint(e,t){if("query"===t.type){const{useQuery:t,useLazyQuery:n,useLazyQuerySubscription:r,useQueryState:a,useQuerySubscription:o}=u(e);mr(c.endpoints[e],{useQuery:t,useLazyQuery:n,useLazyQuerySubscription:r,useQueryState:a,useQuerySubscription:o}),s[`use${fr(e)}Query`]=t,s[`useLazy${fr(e)}Query`]=n}if("mutation"===t.type){const t=l(e);mr(c.endpoints[e],{useMutation:t}),s[`use${fr(e)}Mutation`]=t}else if(gr(t)){const{useInfiniteQuery:t,useInfiniteQuerySubscription:n,useInfiniteQueryState:r}=d(e);mr(c.endpoints[e],{useInfiniteQuery:t,useInfiniteQuerySubscription:n,useInfiniteQueryState:r}),s[`use${fr(e)}InfiniteQuery`]=t}}}}}})());let kr=0;function Or(e){return null!==e&&"object"==typeof e}function Cr(e){return Or(e)?"string"==typeof e.error_message?e.error_message:"string"==typeof e.message?e.message:null:null}const Nr="Something went wrong. Please try again.";function Pr(e){const t=e?.status;return!("number"==typeof t&&t>=400&&t<500)}function xr(e,t){return Pr(e)?Nr:function(e){if(!Or(e))return null;if("string"==typeof e.message){try{const t=Cr(JSON.parse(e.message));if(t)return t}catch{}return e.message}return Cr(e.data)??Cr(e.data?.data)}(e)??t??"An unexpected error occurred."}const qr={NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",PARSE_ERROR:"PARSE_ERROR",TOKEN_EXPIRED:"TOKEN_EXPIRED",TOKEN_REFRESH_FAILED:"TOKEN_REFRESH_FAILED",UNAUTHORIZED:"UNAUTHORIZED",FORBIDDEN:"FORBIDDEN",NOT_FOUND:"NOT_FOUND",VALIDATION_ERROR:"VALIDATION_ERROR",SERVER_ERROR:"SERVER_ERROR",UNKNOWN:"UNKNOWN"};let Mr=null;const Dr=function(e){const{name:t,innerBaseQuery:n,requestInterceptors:r,responseInterceptors:a,defaultOptions:s}=e;return async(e,o,i)=>{let c,u;if("string"==typeof e)c={url:e};else{const{_bridge:t,...n}=e;c=n,u=t}const d={...i,bridge:{...s,...i?.bridge,...u}},l={bridgeName:t,requestId:(p=t,kr+=1,`${p}-${kr}`),startTime:Date.now(),api:o,extraOptions:d};var p;const f=async e=>{let t=e;for(const e of r)t=await e(t,l);return n(t,o,d)};let h=await f(c);for(const e of a)h=await e(h,c,l,f);return h}}({name:"apiBridge",innerBaseQuery:async(e,t,n)=>function({baseUrl:e,prepareHeaders:t=e=>e,fetchFn:n=dn,paramsSerializer:r,isJsonContentType:a=pn,jsonContentType:s="application/json",jsonReplacer:o,timeout:i,responseHandler:c,validateStatus:u,...d}={}){return"undefined"==typeof fetch&&n===dn&&console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments."),async(f,h,g)=>{const{getState:m,extra:y,endpoint:v,forced:_,type:b}=h;let S,{url:w,headers:T=new Headers(d.headers),params:E,responseHandler:I=c??"json",validateStatus:A=u??ln,timeout:R=i,...k}="string"==typeof f?{url:f}:f,O={...d,signal:R?un(h.signal,cn(R)):h.signal,...k};T=new Headers(fn(T)),O.headers=await t(T,{getState:m,arg:f,extra:y,endpoint:v,forced:_,type:b,extraOptions:g})||T;const C="object"==typeof(N=O.body)&&(l(N)||Array.isArray(N)||"function"==typeof N.toJSON);var N;if(null==O.body||C||"string"==typeof O.body||O.headers.delete("content-type"),!O.headers.has("content-type")&&C&&O.headers.set("content-type",s),C&&a(O.headers)&&(O.body=JSON.stringify(O.body,o)),O.headers.has("accept")||("json"===I?O.headers.set("accept","application/json"):"text"===I&&O.headers.set("accept","text/plain, text/html, */*")),E){const e=~w.indexOf("?")?"&":"?";w+=e+(r?r(E):new URLSearchParams(fn(E)))}w=function(e,t){if(!e)return t;if(!t)return e;if(function(e){return new RegExp("(^|:)//").test(e)}(t))return t;const n=e.endsWith("/")||!t.startsWith("?")?"/":"";return e=(e=>e.replace(/\/$/,""))(e),`${e}${n}${t=(e=>e.replace(/^\//,""))(t)}`}(e,w);const P=new Request(w,O);let x;S={request:new Request(w,O)};try{x=await n(P)}catch(e){return{error:{status:(e instanceof Error||"undefined"!=typeof DOMException&&e instanceof DOMException)&&"TimeoutError"===e.name?"TIMEOUT_ERROR":"FETCH_ERROR",error:String(e)},meta:S}}const q=x.clone();let M;S.response=q;let D="";try{let e;if(await Promise.all([p(x,I).then(e=>M=e,t=>e=t),q.text().then(e=>D=e,()=>{})]),e)throw e}catch(e){return{error:{status:"PARSING_ERROR",originalStatus:x.status,data:D,error:String(e)},meta:S}}return A(x,M)?{data:M,meta:S}:{error:{status:x.status,data:M},meta:S}};async function p(e,t){if("function"==typeof t)return t(e);if("content-type"===t&&(t=a(e.headers)?"json":"text"),"json"===t){const t=await e.text();return t.length?JSON.parse(t):null}return e.text()}}({baseUrl:"",prepareHeaders:e=>(e.has("Content-Type")||e.set("Content-Type","application/json"),e.has("Accept")||e.set("Accept","application/json"),e)})(e,t,n),requestInterceptors:[(e,t)=>{if(t.extraOptions.bridge?.skipAuth)return e;const n=t.api.getState(),r=n.auth?.accessToken;return r?{...e,headers:{...e.headers,Authorization:`Bearer ${r}`}}:e},(e,t)=>{const n=q(),r=t.extraOptions.bridge?.customHeaders,a=Object.keys(n).length>0,s=!!r&&Object.keys(r).length>0;return a||s?{...e,headers:{...e.headers,...n,...r??{}}}:e},(e,t)=>{if(!M()||t.extraOptions.bridge?.skipLogging)return e;const n=(e.method||"GET").toUpperCase(),r=e.url||"";return D.debug({message:`${t.bridgeName} ${n} ${r}`,api_name:t.api.endpoint,request_id:t.requestId,method:n,url:r}),e}],responseInterceptors:[async(e,t,n,r)=>{if(n.extraOptions.bridge?.skipTokenRefresh)return e;if(401!==e.error?.status)return e;const a=n.api.getState();if(!a.auth?.accessToken||!a.auth?.isAuthenticated)return e;if(!F())return n.api.dispatch(U()),e;try{const e=await async function(){return Mr||(Mr=async function(){const e=F();if(!e)return null;try{return await e()}catch{return null}}().finally(()=>{Mr=null}),Mr)}();if(e){const a=n.api.getState().auth?.accessToken;return a!==e.accessToken&&n.api.dispatch(L({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresIn:e.expiresIn})),r(t)}D.error({message:"Session cleared: token refresh failed after 401",api_name:"auth-refresh"}),n.api.dispatch(U())}catch{D.error({message:"Session cleared: token refresh threw after 401",api_name:"auth-refresh"}),n.api.dispatch(U())}return e},async(e,t,n)=>{if(!e.error)return e;const r=(a=e.error,s={url:t.url,method:t.method||"GET",timestamp:n.startTime,duration:Date.now()-n.startTime,requestId:n.requestId,bridgeName:n.bridgeName},a&&"object"==typeof a&&"status"in a?function(e,t){const n="PARSING_ERROR"===e.status,r=n?e.originalStatus:void 0,a="number"==typeof r&&r>=400?r:e.status;let s,o="Request failed",i=qr.UNKNOWN;if("data"in e)if(s=e.data,"string"==typeof e.data)o=e.data;else if(e.data&&"object"==typeof e.data){const t=e.data;o=t.message||t.error||t.detail||o}return!n&&"error"in e&&"string"==typeof e.error&&(o=e.error),401===a?i=qr.UNAUTHORIZED:403===a?i=qr.FORBIDDEN:404===a?i=qr.NOT_FOUND:422===a?i=qr.VALIDATION_ERROR:"FETCH_ERROR"===a?i=qr.NETWORK_ERROR:"TIMEOUT_ERROR"===a?i=qr.TIMEOUT:"PARSING_ERROR"===a?i=qr.PARSE_ERROR:"number"==typeof a&&a>=500&&(i=qr.SERVER_ERROR),"number"==typeof a&&a>=500&&(o=Nr),{status:a,message:o,data:s,code:i,meta:{timestamp:Date.now(),...t}}}(a,s):a instanceof Error?{status:"FETCH_ERROR",message:a.message||"An unexpected error occurred",code:qr.UNKNOWN,meta:{timestamp:Date.now(),...s}}:"string"==typeof a?{status:"CUSTOM_ERROR",message:a,code:qr.UNKNOWN,meta:{timestamp:Date.now(),...s}}:{status:"CUSTOM_ERROR",message:"An unknown error occurred",data:a,code:qr.UNKNOWN,meta:{timestamp:Date.now(),...s}});var a,s;return{...e,error:{...e.error,...r}}},async(e,t,n)=>{if(!e.error||n.extraOptions.bridge?.skipErrorToast)return e;const{status:r}=e.error;return"FETCH_ERROR"===r?(Q("Network error. Please check your connection."),e):"TIMEOUT_ERROR"===r?(Q("Request timed out. Please try again."),e):"number"==typeof r&&r>=500?(Q(Nr),e):e},async(e,t,n,r)=>{if(!e.error)return e;const{status:a}=e.error;if("FETCH_ERROR"!==a&&"TIMEOUT_ERROR"!==a)return e;const s=n.extraOptions.bridge?.retry,o=s?.maxRetries??1,i=s?.backoffMs??1e3,c=parseInt(t.headers?.["X-Bridge-Retry-Count"]||"0",10);if(c>=o)return e;const u=i*Math.pow(2,c);return await new Promise(e=>setTimeout(e,u)),r({...t,headers:{...t.headers,"X-Bridge-Retry-Count":String(c+1)}})},async(e,t,n)=>{const r=n.extraOptions.bridge?.skipLogging,a=Date.now()-n.startTime,s=(t.method||"GET").toUpperCase(),o=t.url||"",i=e.meta?.response,c=e.error?e.error.status:i?.status??"OK",u=i?.headers?.get?.("x-request-id")??void 0;return e.error?D.error({message:`${n.bridgeName} ${s} ${o} failed (${c})`,api_name:n.api.endpoint,request_id:u??n.requestId,method:s,url:o,status:c,duration:a,error_data:e.error.data}):M()&&!r&&D.debug({message:`${n.bridgeName} ${s} ${o} ${c} ${a}ms`,api_name:n.api.endpoint,request_id:u??n.requestId,method:s,url:o,status:c,duration:a}),e}]});function Qr(){return j()}let Fr=0;async function Ur(e){const{url:t,method:n="GET",body:r,headers:a={},skipAuth:s=!1,skipLogging:o=!1,skipContentType:i=!1,responseHandler:c="json",signal:u,keepalive:d}=e;Fr+=1;const l=`fetch-${Fr}`,p=Date.now(),f=n.toUpperCase(),h={...a};if(Object.assign(h,q()),!s){const e=Qr();e&&(h.Authorization=`Bearer ${e}`)}let g;i||h["Content-Type"]||(h["Content-Type"]="application/json"),h.Accept||(h.Accept="application/json"),g=null==r?void 0:"string"==typeof r||r instanceof FormData||r instanceof Blob||r instanceof ArrayBuffer?r:JSON.stringify(r),M()&&!o&&D.debug({message:`bridgedFetch ${f} ${t}`,api_name:"bridgedFetch",request_id:l,method:f,url:t});try{const e=await fetch(t,{method:n,headers:h,body:g,signal:u,keepalive:d}),r=Date.now()-p;if(!e.ok){let n;try{n=await e.json()}catch{try{n=await e.text()}catch{n=`HTTP ${e.status}`}}const a=e.headers.get("x-request-id")??void 0;return o||D.error({message:`bridgedFetch ${f} ${t} failed (${e.status})`,api_name:"bridgedFetch",request_id:a??l,method:f,url:t,status:e.status,duration:r,error_data:n}),{error:{status:e.status,data:n},response:e}}let a;if("blob"===c)a=await e.blob();else if("text"===c)a=await e.text();else{const t=await e.text();a=t?JSON.parse(t):void 0}if(M()&&!o){const n=e.headers.get("x-request-id")??void 0;D.debug({message:`bridgedFetch ${f} ${t} ${e.status} ${r}ms`,api_name:"bridgedFetch",request_id:n??l,method:f,url:t,status:e.status,duration:r})}return{data:a,response:e}}catch(e){const n=Date.now()-p;return o||D.error({message:`bridgedFetch ${f} ${t} network error`,api_name:"bridgedFetch",request_id:l,method:f,url:t,status:"FETCH_ERROR",duration:n,error_message:e instanceof Error?e.message:"Network error"}),{error:{status:"FETCH_ERROR",data:e instanceof Error?e.message:"Network error"}}}}const Lr=()=>"",jr=Rr({reducerPath:"chatApi",baseQuery:Dr,keepUnusedDataFor:0,tagTypes:["chat","toolServers"],endpoints:e=>({getConversationHistory:e.query({query:({skip:e=0,limit:t=20})=>({url:`${$.CONVERSATIONS()}`,method:"GET",params:{skip:e,limit:t}}),transformResponse:e=>e?.data??{conversations:[]},providesTags:["chat"]}),getConversationById:e.query({query:({conversationId:e,skip:t,limit:n})=>({url:`${$.CONVERSATIONS()}/${e}`,method:"GET",params:{...void 0!==t&&{skip:t},...void 0!==n&&{limit:n}}}),transformResponse:e=>e?.data??null,providesTags:["chat"]}),createConversatons:e.mutation({query:e=>({url:`${$.CONVERSATIONS()}`,method:"POST",body:e.body||{}}),transformResponse:e=>e?.data??[],extraOptions:{bridge:{skipErrorToast:!0}}}),transcribeAudio:e.mutation({queryFn:async({audioFile:e})=>{const t=new FormData;t.append("file",e);const{data:n,error:r}=await Ur({url:$.TRANSCRIBE,method:"POST",body:t,skipContentType:!0});return r?{error:r}:{data:n}}}),getToolServers:e.query({query:()=>({url:$.TOOL_SERVERS,method:"GET"}),transformResponse:e=>e?.data??{tool_servers:[]},providesTags:["toolServers"]}),startToolServerOAuth:e.mutation({query:e=>({url:$.TOOL_SERVER_AUTH_START(e),method:"POST"}),transformResponse:e=>e?.data??{authorize_url:""}}),deleteToolServerConnection:e.mutation({query:e=>({url:$.TOOL_SERVER_AUTH_CONNECTION(e),method:"DELETE"}),invalidatesTags:["toolServers"]}),exchangeOAuthCode:e.mutation({query:({code:e,state:t})=>({url:$.TOOL_SERVERS_SIGN_IN_EXCHANGE,method:"POST",body:{code:e,state:t}}),invalidatesTags:["toolServers"]}),deleteConversation:e.mutation({query:({conversationId:e})=>({url:`${$.CONVERSATIONS()}/${e}`,method:"DELETE"}),extraOptions:{bridge:{skipErrorToast:!0}}})})}),{useCreateConversatonsMutation:$r,useTranscribeAudioMutation:zr,useExchangeOAuthCodeMutation:Kr,useGetConversationHistoryQuery:Hr,useLazyGetConversationByIdQuery:Gr,useDeleteConversationMutation:Br,useGetToolServersQuery:Vr,useStartToolServerOAuthMutation:Wr,useDeleteToolServerConnectionMutation:Jr}=jr,Xr={bridge:{skipErrorToast:!0,skipTokenRefresh:!0}},Zr=Rr({reducerPath:"brandingApi",baseQuery:Dr,keepUnusedDataFor:0,endpoints:e=>({getBranding:e.query({query:e=>({url:$.BRANDING,method:"GET",_bridge:{skipAuth:!e}}),extraOptions:Xr})})}),{useGetBrandingQuery:Yr}=Zr,ea={bridge:{skipErrorToast:!0,skipTokenRefresh:!0,retry:{maxRetries:0}}},ta=Rr({reducerPath:"configApi",baseQuery:Dr,keepUnusedDataFor:1/0,endpoints:e=>({getConfig:e.query({query:()=>({url:$.CONFIG,method:"GET",_bridge:{skipAuth:!0},timeout:z.CONFIG_TIMEOUT_MS}),extraOptions:ea})})}),{useGetConfigQuery:na}=ta,ra=Rr({reducerPath:"profileApi",baseQuery:Dr,keepUnusedDataFor:0,tagTypes:["profile"],endpoints:e=>({getProfile:e.query({query:()=>({url:$.PROFILE,method:"GET"}),extraOptions:{bridge:{skipErrorToast:!0}},transformResponse:e=>e?.data??null,providesTags:["profile"]}),updateProfile:e.mutation({query:e=>({url:$.PROFILE,method:"PUT",body:e}),async onQueryStarted(e,{dispatch:t,queryFulfilled:n}){try{await n,t(ra.util.updateQueryData("getProfile",void 0,t=>{t&&(void 0!==e.name&&(t.name=e.name),void 0!==e.phone&&(t.phone=e.phone))}))}catch{}}}),deleteAccount:e.mutation({query:()=>({url:$.AUTH_ME,method:"DELETE"})})})}),{useGetProfileQuery:aa,useUpdateProfileMutation:sa,useDeleteAccountMutation:oa}=ra,ia={[jr.reducerPath]:jr.reducer,[Zr.reducerPath]:Zr.reducer,[ta.reducerPath]:ta.reducer,[ra.reducerPath]:ra.reducer},ca=[jr.middleware,Zr.middleware,ta.middleware,ra.middleware],ua={isAgentWorking:!0,statusText:null,responseStartTime:null,messageQueue:[]},da=s({name:"chat",initialState:ua,reducers:{setIsAgentWorking(e,t){e.isAgentWorking=t.payload},setStatusText(e,t){e.statusText=t.payload},setResponseStartTime(e,t){e.responseStartTime=t.payload},enqueueMessage(e,t){e.messageQueue.push(t.payload)},dequeueMessage(e){e.messageQueue.shift()},clearMessageQueue(e){e.messageQueue=[]},resetChatState:()=>ua},extraReducers:e=>{e.addMatcher(i(U,K),()=>ua)}}),{setIsAgentWorking:la,setStatusText:pa,setResponseStartTime:fa,enqueueMessage:ha,dequeueMessage:ga,clearMessageQueue:ma,resetChatState:ya}=da.actions,va=da.reducer,_a={activeConversationId:null,titles:{}},ba=s({name:"conversations",initialState:_a,reducers:{setActiveConversationId(e,t){e.activeConversationId=t.payload},upsertConversationTitle(e,t){const{id:n,title:r}=t.payload;n&&r.trim()&&(e.titles[n]=r)}},extraReducers:e=>{e.addMatcher(i(U,K),()=>_a)}}),{setActiveConversationId:Sa,upsertConversationTitle:wa}=ba.actions,Ta=ba.reducer;let Ea=null;function Ia(e){Ea=e}function Aa(){Ea=null}const Ra=()=>{if(!Ea)return{};const e=Ea(),t=e.auth.user?.id,n=e.auth.selectedOrgId??void 0,r=e.conversations.activeConversationId??void 0;return{...t?{user_id:t}:{},...n?{org_id:n}:{},...r?{conversation_id:r}:{}}},ka=d({...ia,auth:G,chat:va,conversations:Ta,indicator:H}),Oa={ignoredPaths:["chatApi.queries","chatApi.mutations","brandingApi.queries","brandingApi.mutations","configApi.queries","configApi.mutations","profileApi.queries","profileApi.mutations"],ignoredActions:["chatApi/executeQuery/fulfilled","chatApi/executeMutation/fulfilled","brandingApi/executeQuery/rejected","brandingApi/executeQuery/fulfilled","configApi/executeQuery/rejected","configApi/executeQuery/fulfilled","profileApi/executeQuery/rejected","profileApi/executeQuery/fulfilled","profileApi/executeMutation/rejected","profileApi/executeMutation/fulfilled"],ignoredActionPaths:["payload.error","error","meta.baseQueryMeta","meta.arg.originalArgs.audioFile"]},Ca=_({reducer:ka,middleware:e=>e({serializableCheck:Oa}).prepend(B.middleware).concat(ca)});var Na;Na=Ca.dispatch,function(){const[e,t,n,r]=[Sn,wn,Tn,En].map(e=>()=>Na(e())),a=()=>{"visible"===window.document.visibilityState?e():t()};if(!In&&"undefined"!=typeof window&&window.addEventListener){let t=function(e){Object.entries(s).forEach(([t,n])=>{e?window.addEventListener(t,n,!1):window.removeEventListener(t,n)})};const s={[vn]:e,[bn]:a,[mn]:n,[yn]:r};t(!0),In=!0}}(),V(()=>Ca.getState().auth.accessToken),W(()=>Ca.getState().auth.tokenExpiresAt),Ia(()=>Ca.getState());const Pa=()=>{const e=na(),{isError:t,isFetching:n,refetch:r}=e,a=C(!1);return O(()=>{!t||n||a.current||(a.current=!0,r())},[t,n,r]),e},xa=P(void 0),qa=()=>{const e=x(xa);if(!e)throw new Error("useProtocol must be used within a ProtocolProvider");return e},Ma="mtx",Da=5;var Qa=(e=>(e.START="start",e.TEXT="text",e.WIDGET="widget",e.STATUS_UPDATE="status_update",e.CLEAR_STATUS="clear_status",e.PAYMENT="payment",e.SIGN_IN="sign_in",e.CONVERSATION_TITLE="conversation_title",e.END="end",e))(Qa||{});let Fa=class extends Error{constructor(e){super(),this.reopen=e}};class Ua{type="mtx";config;constructor(e){this.config=e}streamMessage(e){const t=e.debugMode?this.config.getDebugUrl():this.config.getStreamUrl(e.conversationId);return this.createStreamHandle(t,{message:e.message,...e.body||{}})}streamInitial(e){const t=this.config.getInitialStreamUrl(e.conversationId);return this.createStreamHandle(t,{...e.body||{}})}normalizeEvent(e){const{parsed:t,eventType:n,isStreamEnd:r,requestId:a}=e;if(r)return{type:"stream_end",data:{isEnd:!0},timestamp:Date.now(),requestId:a};const s=(n||"").toLowerCase(),{type:o,data:i}=this.mapSSEEvent(s,t);return{type:o,data:i,timestamp:Date.now(),requestId:a}}mapSSEEvent(e,t){switch(e){case"text":return{type:"text",data:{text:t.token||""}};case"widget":return{type:"widget",data:{widget:t}};case"status_update":return{type:"status_update",data:{statusText:t.text||""}};case"clear_status":return{type:"status_update",data:{statusText:""}};case"payment":return{type:"payment",data:{payment:t}};case"sign_in":return{type:"sign_in",data:{signIn:{authorize_url:t.authorize_url,state:t.state}}};case"conversation_title":return{type:"conversation_title",data:{conversationTitle:t.text||""}};default:return t.token?{type:"text",data:{text:t.token}}:t.text?{type:"text",data:{text:t.text}}:{type:"text",data:{text:""}}}}createStreamHandle(e,t){let n=new AbortController,r=0,a="",s=!1;const o=[];let i=null,c=!1,u=null;const d=e=>{i?i.onEvent(e):o.push(e)},l=e=>{i?i.onError(e):u=e},p=()=>{c=!0,i&&i.onComplete()},f=async()=>{try{await(this.config.ensureFreshToken?.()),await Se(e,{method:"POST",headers:{"Content-Type":"application/json",...this.config.getAuthToken()?{Authorization:`Bearer ${this.config.getAuthToken()}`}:{},...this.config.getCustomHeaders()},body:JSON.stringify(t),signal:n.signal,onopen:async e=>{if(401===e.status&&!s){s=!0,D.warn({message:"MTX SSE rejected with 401 — refreshing token",api_name:"mtx-sse"});const e=await(this.config.forceRefreshToken?.());throw e||(D.error({message:"MTX SSE 401 refresh failed — clearing session",api_name:"mtx-sse"}),this.config.onAuthExpired?.()),new Fa(Boolean(e))}const t=e.headers.get("x-request-id");t&&(a=t)},onmessage:e=>{if("[DONE]"===e.data)return;const t=(e.event||"").toLowerCase(),n=new Set(Object.values(Qa));if("status_update"!==t&&"clear_status"!==t||D.debug({message:"MTX SSE status event received",api_name:"mtx-sse",sse_event:t,allowed:n.has(t)}),!t||n.has(t))try{const n=t===Qa.END;let r;try{r=JSON.parse(e.data)}catch{return}if(!n&&t!==Qa.CLEAR_STATUS&&r&&"object"==typeof r&&0===Object.keys(r).length)return;const s=this.normalizeEvent({parsed:r,eventType:e.event,isStreamEnd:n,requestId:r.request_id||a||""});d(s),n&&"stream_end"!==s.type&&d({type:"stream_end",data:{isEnd:!0},timestamp:Date.now(),requestId:a})}catch(e){D.error({message:"Failed to parse MTX SSE message",api_name:"mtx-sse",error_message:e instanceof Error?e.message:String(e)})}else D.debug({message:"Ignoring unrecognized MTX SSE event type",api_name:"mtx-sse",sse_event:e.event})},onerror:e=>{if(e instanceof Fa)throw e;if(r++,r>=5)throw n.abort(),l(e instanceof Error?e:new Error(String(e))),e;throw e},onclose:()=>{p()},openWhenHidden:!0})}catch(e){if(e instanceof Fa)return e.reopen&&!n.signal.aborted?(n=new AbortController,f()):void(c||p());c||(n.signal.aborted||l(e instanceof Error?e:new Error(String(e))),p())}};return f(),{subscribe(e){i=e;for(const t of o)e.onEvent(t);return o.length=0,u&&(e.onError(u),u=null),c&&e.onComplete(),()=>{i=null}},abort(){n.abort()}}}}class La extends Error{constructor(e){super(),this.reopen=e}}class ja{type="agui";config;constructor(e){this.config=e}streamMessage(e){const t=e.debugMode?this.config.getDebugUrl():this.config.getStreamUrl(e.conversationId);return this.createStreamHandle(t,{message:e.message,...e.body||{}})}streamInitial(e){const t=this.config.getInitialStreamUrl(e.conversationId);return this.createStreamHandle(t,{...e.body||{}})}normalizeEvent(e){const t=e,{type:n,data:r}=this.mapEventType(t);return{type:n,data:r,timestamp:Date.now(),requestId:t.runId||""}}mapEventType(e){switch((e.type||"").toUpperCase()){case"TEXT_MESSAGE_CONTENT":return{type:"text",data:{text:e.delta||""}};case"TEXT_MESSAGE_END":case"RUN_FINISHED":return{type:"stream_end",data:{isEnd:!0}};case"RUN_ERROR":return{type:"error",data:{error:e.error||"Unknown AG-UI run error"}};case"STATE_SNAPSHOT":return this.mapStateSnapshot(e);case"CUSTOM":return this.mapCustomEvent(e);case"PAYMENT":{const t=e?.value?.data??e.payload;return t?.provider&&t?.config&&J(t)&&("chargebee"!==t.provider||t.config?.hosted_page_url)?{type:"payment",data:{payment:t}}:{type:"text",data:{text:""}}}case"CONVERSATION_TITLE":{const t=e?.value?.data??e.payload,n=t?.text??t?.title;return{type:"conversation_title",data:{conversationTitle:"string"==typeof n?n:""}}}default:return{type:"text",data:{text:""}}}}mapStateSnapshot(e){return{type:"widget",data:{widget:e.state||e.payload||{}}}}mapCustomEvent(e){const t=e.payload||e?.value?.data||{},n=e.name||"custom";return D.debug({message:"AG-UI mapCustomEvent",api_name:"agui-sse",event_name:n}),"widget"===n?{type:"widget",data:{widget:{eventName:n,...e?.value?.data}}}:Object.keys(t).length>0?{type:"widget",data:{widget:{eventName:e.eventName,...t}}}:{type:"text",data:{text:""}}}createStreamHandle(e,t){let n=new AbortController,r=0,a="",s=!1;const o=[];let i=null,c=!1,u=null;const d=e=>{i?i.onEvent(e):o.push(e)},l=e=>{i?i.onError(e):u=e},p=()=>{c=!0,i&&i.onComplete()},f=async()=>{try{await(this.config.ensureFreshToken?.()),await Se(e,{method:"POST",headers:{"Content-Type":"application/json",...this.config.getAuthToken()?{Authorization:`Bearer ${this.config.getAuthToken()}`}:{},...this.config.getCustomHeaders()},body:JSON.stringify(t),signal:n.signal,onopen:async e=>{if(401===e.status&&!s){s=!0,D.warn({message:"AG-UI SSE rejected with 401 — refreshing token",api_name:"agui-sse"});const e=await(this.config.forceRefreshToken?.());throw e||(D.error({message:"AG-UI SSE 401 refresh failed — clearing session",api_name:"agui-sse"}),this.config.onAuthExpired?.()),new La(Boolean(e))}const t=e.headers.get("x-request-id");t&&(a=t)},onmessage:e=>{D.debug({message:"AG-UI SSE event",api_name:"agui-sse",sse_event:e.event});const t=(e.event||"").toLowerCase(),n=new Set(Object.values(Qa));if(!t||n.has(t))if(t!==Qa.END){if("[DONE]"!==e.data)try{let n;try{n=JSON.parse(e.data)}catch(t){return void D.error({message:"AG-UI JSON parse error",api_name:"agui-sse",error_message:t instanceof Error?t.message:String(t),raw_data:e.data})}if(n&&"object"==typeof n&&0===Object.keys(n).length)return;n.runId&&(a=n.runId);const r=t===Qa.CONVERSATION_TITLE?{...n,type:"CONVERSATION_TITLE",payload:n,runId:n.runId||a}:{...n,runId:n.runId||a},s=this.normalizeEvent(r);d(s)}catch(e){D.error({message:"Failed to handle AG-UI message",api_name:"agui-sse",error_message:e instanceof Error?e.message:String(e)})}}else d(this.normalizeEvent({type:"RUN_FINISHED",runId:a}));else D.debug({message:"AG-UI ignoring unknown SSE event type",api_name:"agui-sse",sse_event:e.event})},onerror:e=>{if(e instanceof La)throw e;if(r++,r>=5)throw n.abort(),l(e instanceof Error?e:new Error(String(e))),e;throw e},onclose:()=>{p()},openWhenHidden:!0})}catch(e){if(e instanceof La)return e.reopen&&!n.signal.aborted?(n=new AbortController,f()):void(c||p());c||(n.signal.aborted||l(e instanceof Error?e:new Error(String(e))),p())}};return f(),{subscribe(e){i=e;for(const t of o)e.onEvent(t);return o.length=0,u&&(e.onError(u),u=null),c&&e.onComplete(),()=>{i=null}},abort(){n.abort()}}}}function $a(e,t){switch(e){case"mtx":return new Ua(t);case"agui":return new ja(t);default:throw new Error(`Unknown protocol type: "${e}". Supported types: mtx, agui`)}}function za(e={}){return{getAuthToken:()=>Qr(),getCustomHeaders:()=>q(),onAuthExpired:e.onAuthExpired,getStreamUrl:e=>$.CONVERSATION_STREAM(e),getInitialStreamUrl:e=>$.CONVERSATION_START(e),getDebugUrl:()=>$.DEBUG,ensureFreshToken:async()=>{X(Z())&&await(F()?.())},forceRefreshToken:async()=>Boolean(await(F()?.()))}}class Ka{segments=[];error="";requestId="";statusText="";streamComplete=!1;startTimestamp=null;processEvent(e){null===this.startTimestamp&&(this.startTimestamp=e.timestamp),e.requestId&&(this.requestId=e.requestId);const{data:t}=e;if(!("isEnd"in t))return"error"in t?(this.error=t.error,void("text"in t&&t.text&&this.appendText(t.text))):void("statusText"in t?this.statusText=t.statusText:"payment"in t||("widget"in t?this.segments.push({type:"widget",id:Y(),content:t.widget}):"text"in t&&this.appendText(t.text)));this.streamComplete=!0}appendText(e){const t=this.segments[this.segments.length-1];t&&"text"===t.type?t.text+=e:this.segments.push({type:"text",id:Y(),text:e})}toMessages(){if(0===this.segments.length){const e=Y();return[{id:e,msg_id:e,sender:"agent",message:"",timestamp:(new Date).toISOString(),tookMs:this.startTimestamp?Date.now()-this.startTimestamp:0,error:this.error||void 0,request_id:this.requestId||void 0}]}const e=(new Date).toISOString(),t=this.segments.map(t=>{const n={id:t.id,msg_id:t.id,sender:"agent",message:"",timestamp:e};switch(t.type){case"text":n.message=t.text;break;case"widget":n.widget=[t.content],n.message_type=["widget"]}return n}),n=t[t.length-1];return n.tookMs=this.startTimestamp?Date.now()-this.startTimestamp:0,n.error=this.error||void 0,n.request_id=this.requestId||void 0,t}getStatusText(){return this.statusText}isStreamComplete(){return this.streamComplete}reset(){this.segments=[],this.error="",this.requestId="",this.statusText="",this.streamComplete=!1,this.startTimestamp=null}}async function Ha(e,t){const{data:n,error:r,response:a}=await Ur({url:ee(te.LOGIN),method:"POST",body:{email:e,password:t},skipAuth:!0});if(r||!a)throw n??r;return{body:n,tokens:ne(a)}}async function Ga(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.SIGNUP),method:"POST",body:e,skipAuth:!0});if(n||!r)throw t??n;return{body:t,tokens:ne(r)}}async function Ba(e,t){await Ur({url:ee(te.LOGOUT),method:"POST",body:e,keepalive:t?.keepalive})}async function Va(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.REFRESH),method:"POST",body:e,skipAuth:!0});if(n||!r)throw t??n;return{body:t,tokens:ne(r)}}async function Wa(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.FORGOT_PASSWORD),method:"POST",body:e,skipAuth:!0});if(n||!r)throw t??n;return t?.data?.message}async function Ja(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.RESET_PASSWORD),method:"POST",body:e,skipAuth:!0});if(n||!r)throw t??n;return t?.data?.message}async function Xa(e){const{data:t,error:n,response:r}=await Ur({url:ee(te.SSO_START),method:"POST",body:{idp_hint:e},skipAuth:!0});if(n||!r)throw t??n;return t}async function Za(e,t){const{data:n,error:r,response:a}=await Ur({url:ee(te.SSO_EXCHANGE),method:"POST",body:{code:e,state:t},skipAuth:!0});if(r||!a)throw n??r;return{body:n,tokens:ne(a)}}async function Ya(){try{const{data:e}=await Ur({url:ee(`${te.ORGANIZATIONS}?skip=0&limit=100`),skipAuth:!0});if(e?.success&&Array.isArray(e.data?.organizations))return e.data.organizations}catch{}return[]}async function es(){const e=new AbortController,t=setTimeout(()=>e.abort(),8e3);try{const{data:t,error:n,response:r}=await Ur({url:$.ORGANIZATIONS_EXISTS,method:"GET",skipAuth:!0,skipContentType:!0,signal:e.signal});return n?!r||r.status>=500?"error":"not-found":function(e){const t=e?.data?.exists;return"boolean"!=typeof t?"error":t?"exists":"not-found"}(t)}catch{return"error"}finally{clearTimeout(t)}}function ts(){const e=b(),[t,n]=k(!1);return{login:I(async t=>{n(!0);try{const{body:n,tokens:r}=await Ha(t.email,t.password);return n.success&&n.data?(e.dispatch(L({user:n.data.user,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:n.data.expiry_time})),{success:!0,data:n}):{success:!1,error:n}}catch(e){return{success:!1,error:e}}finally{n(!1)}},[e]),isLoading:t}}function ns(){const e=b(),[t,n]=k(!1);return{signup:I(async t=>{n(!0);try{const{body:n,tokens:r}=await Ga(t);return n.success&&n.data?(e.dispatch(L({user:n.data.user,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:n.data.expiry_time})),{success:!0,data:n}):{success:!1,error:n}}catch(e){return{success:!1,error:e}}finally{n(!1)}},[e]),isLoading:t}}function rs(){const e=b();return{logout:I(async()=>{const t=e.getState(),n=t.auth?.refreshToken,r=t.auth?.user?.email;if(n&&r)try{await Ba({refresh_token:n,user_id:r})}catch{}else D.warn({message:"skipping server-side logout revocation — credentials missing",api_name:"auth-logout",has_refresh_token:Boolean(n),has_user_id:Boolean(r)});e.dispatch(U())},[e])}}function as(){const e=b(),[t,n]=k(!1);return{refresh:I(async()=>{n(!0);try{const t=e.getState(),n=t.auth?.refreshToken,r=t.auth?.user?.email;if(!n||!r)return{success:!1,error:new Error("No refresh token or user available")};const{body:a,tokens:s}=await Va({refresh_token:n,user_id:r});return a?.success&&a?.data?(e.dispatch(L({accessToken:s.accessToken,refreshToken:s.refreshToken,expiresIn:a.data.expiry_time})),{success:!0,data:a}):{success:!1,error:a}}catch(e){return{success:!1,error:e}}finally{n(!1)}},[e]),isLoading:t}}function ss(e){return re({performRefresh:async()=>{const t=e.getState(),n=t.auth?.refreshToken,r=t.auth?.user?.email;if(!n||!r)return D.warn({message:"Session refresh skipped: missing stored credentials",api_name:"auth-refresh",has_refresh_token:Boolean(n),has_user_id:Boolean(r)}),null;const{body:a,tokens:s}=await Va({refresh_token:n,user_id:r});if(a?.success&&a?.data){const t={accessToken:s.accessToken,refreshToken:s.refreshToken,expiresIn:a.data.expiry_time};return D.debug({message:"Session token refreshed",api_name:"auth-refresh",refresh_token_rotated:t.refreshToken!==n}),e.dispatch(L({accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn})),t}return D.warn({message:"Session refresh rejected by server",api_name:"auth-refresh"}),null}})}const os=()=>{const{user:e,accessToken:t,tokenExpiresAt:n,isAuthenticated:r,isLoading:a}=S(e=>e.auth);return{user:e,accessToken:t,isAuthenticated:r,isLoading:a,tokenInfo:{isExpired:!!n&&oe(n),isAboutToExpire:!!n&&X(n),expiresAt:n,timeUntilExpiry:n?se(n):0,timeUntilExpiryFormatted:n?ae(se(n)):"0s"}}},is={SM:640,MD:768,LG:1024,XL:1280,XXL:1536},cs={INITIAL:["Working on it","Just a moment","Reviewing your request","Looking into that","One moment, please","Checking"],LATER:["Almost ready","Gathering the details","Finishing up","Getting things in order","Preparing your answer","Wrapping this up"],ROTATION_INTERVAL_MS:5e3,PHASE_SWITCH_MS:4e3},us={MESSAGE_PAGE_SIZE:25},ds=[500,1500,3e3],ls=28,ps="New Conversation";function fs(e){return!e.widget?.length}function hs(e){const t=Y(),n={id:`agent-${t}`,msg_id:t,sender:"agent",message:"",timestamp:e.created_at?String(e.created_at):""};return"widget"===e.type?e.content&&"object"==typeof e.content&&(n.widget=[e.content],n.message_type=["widget"]):e.content&&"string"==typeof e.content&&(n.message=e.content),n}function gs(e){const t=[];for(const n of e){const e=n.created_at?String(n.created_at):"";if("user"!==n.role)if("system"!==n.role){if("assistant"===n.role){if(n.tool_calls?.length)continue;const e=t[t.length-1];if((!n.type||"text_delta"===n.type)&&"agent"===e?.sender&&fs(e)){e.message=e.message+(n.content||"");continue}t.push(hs(n));continue}}else n.content&&t.push({id:`system-${Y()}`,sender:"system",message:"string"==typeof n.content?n.content:"",timestamp:e});else n.content&&t.push({id:`user-${Y()}`,sender:"user",message:"string"==typeof n.content?n.content:"",timestamp:e})}return t}function ms(e){return"string"==typeof e&&e.trim()?e:null}const ys=()=>{const e=w(),[t,n]=k(null),[r,a]=k([]),s=C(t),o=S(e=>t?e.conversations.titles[t]??null:null),i=I(n=>{t&&n&&e(wa({id:t,title:n}))},[t,e]);O(()=>{s.current=t,e(Sa(t))},[t,e]);const[c,u]=k(!1),[d,l]=k(0),[p,f]=k(!1),[h,g]=k(!1),m=C(!1),{protocolType:y}=qa(),[v]=$r(),[_]=Gr(),b=I(async()=>{try{u(!0);const t=await v({protocol:y,body:{}}).unwrap(),r=t?.id;if(r){n(r);const a=ms(t?.title);return a&&e(wa({id:r,title:a})),r}return Q(t?.error||"Failed to create conversations. Please try again."),null}catch(e){return Q(e?.data?.message||e?.message||"Failed to create conversations. Please try again."),null}finally{u(!1)}},[v,y,e]),T=I(async(t,r)=>{try{const s=ms(r);s&&e(wa({id:t,title:s}));const o=await _({conversationId:t,skip:0,limit:us.MESSAGE_PAGE_SIZE}).unwrap();if(o){n(t);const r=ms(o.title)??s;r&&e(wa({id:t,title:r}));const i=o.messages??[],c=Array.isArray(i)?gs(i):[];return a(c),l(i.length),f(i.length>=us.MESSAGE_PAGE_SIZE),!0}return!1}catch(e){return"AbortError"===e?.name||"AbortError"===e?.error?.name||"ABORTED"===e?.status||(D.error({message:"Failed to load conversation",api_name:"chat-conversation-load",conversation_id:t,error_message:e instanceof Error?e.message:String(e)}),Q("Failed to load conversation. Please try again.")),!1}},[_,e]),E=I(async(n=t)=>{if(!n)return null;try{const t=await _({conversationId:n,skip:0,limit:1}).unwrap(),r=ms(t?.title);return r&&e(wa({id:n,title:r})),r}catch(e){return D.error({message:"Failed to refresh conversation title",api_name:"chat-conversation-title-refresh",conversation_id:n,error_message:e instanceof Error?e.message:String(e)}),null}},[t,_,e]),A=I(async()=>{if(m.current||!t||!p)return;const e=t;g(!0),m.current=!0;try{const n=await _({conversationId:t,skip:d,limit:us.MESSAGE_PAGE_SIZE}).unwrap();if(s.current!==e)return;if(n?.messages&&Array.isArray(n.messages)){const e=gs(n.messages);l(e=>e+n.messages.length),f(n.messages.length>=us.MESSAGE_PAGE_SIZE),a(t=>{const n=new Set(t.map(e=>e.timestamp).filter(Boolean));return[...e.filter(e=>!e.timestamp||!n.has(e.timestamp)),...t]})}}catch(e){D.error({message:"Failed to load more messages",api_name:"chat-conversation-load-more",error_message:e instanceof Error?e.message:String(e)}),Q("Failed to load older messages.")}finally{g(!1),m.current=!1}},[t,d,p,_]),R=I(()=>{a([]),n(null),l(0),f(!1)},[]);return{conversationId:t,setConversationId:n,conversationTitle:o,setConversationTitle:i,messages:r,setMessages:a,isLoadingCreateConversation:c,hasMoreMessages:p,isLoadingMoreMessages:h,startSession:b,loadConversation:T,loadConversationTitle:E,loadMoreMessages:A,resetConversation:R}},vs=e=>null==e||"string"==typeof e&&""===e.trim(),_s=e=>{const t=["widget","error"],n=e=>!(null==e||"string"==typeof e&&""===e.trim()||Array.isArray(e)&&0===e.length||"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length);for(const r of t)if(n(e[r]))return!0;return!1},bs=({conversationId:e,messages:t,setMessages:n,enableTts:r=!1,userLocation:a=null,startSession:s,debugMode:o=!1,onPaymentInit:i,onSignInInit:c,onConversationTitle:u})=>{const{adapter:d}=qa(),l=w(),p=b(),[f,h]=k(""),[g,m]=k(!1),[y,v]=k(!1),_=C(i);_.current=i;const S=C(c);S.current=c;const T=C(u);T.current=u;const E=C(new Ka),A=C(null),R=C(null),N=C(!1),P=C(0),x=C(!1),q=C(null),M=C(e);M.current=e;const F=C(null),U=I((e=ie.KEEP)=>{if(l(pa(null)),l(la(!1)),e===ie.FINALIZE){const e=p.getState().chat.responseStartTime;e&&l(ce(Date.now()-e)),l(fa(null))}else e===ie.CANCEL&&l(fa(null))},[l,p]),L=I(e=>{l(la(e)),m(e),e&&v(!1)},[l]),j=I(()=>{const e=p.getState().chat.responseStartTime;return e&&l(ce(Date.now()-e)),null!==q.current&&clearTimeout(q.current),q.current=setTimeout(()=>{q.current=null,x.current=!1,h(""),m(!1),v(!1),U(ie.CANCEL)},600),()=>{null!==q.current&&clearTimeout(q.current)}},[l,p,U]),$=C({setStatusText:e=>l(pa(e||null)),setIsAgentWorking:e=>l(la(e)),appendStreamText:()=>{},pushWidget:()=>{},onPayment:e=>_.current?.(e),onSignIn:e=>S.current?.(e),onError:()=>{}}),z=I(e=>{if(F.current!==M.current)return A.current?.abort(),void R.current?.();if("payment"===e.type&&"payment"in e.data)return void ue({kind:"payment",payment:e.data.payment},$.current);if("sign_in"===e.type&&"signIn"in e.data)return void ue({kind:"sign_in",signIn:e.data.signIn},$.current);if("conversation_title"===e.type&&"conversationTitle"in e.data){const t=e.data.conversationTitle.trim();return void(t&&T.current?.(t))}const t=E.current;t.processEvent(e),N.current||(N.current=!0,v(!0));const r=function(e){const t=e.data;switch(e.type){case"text":return"text"in t?{kind:"text",text:t.text}:null;case"widget":return"widget"in t?{kind:"widget",widget:t.widget}:null;case"status_update":return"statusText"in t?{kind:"status_update",statusText:t.statusText}:null;case"payment":return"payment"in t?{kind:"payment",payment:t.payment}:null;case"sign_in":return"signIn"in t?{kind:"sign_in",signIn:t.signIn}:null;case"error":return"error"in t?{kind:"error",error:t.error}:null;default:return null}}(e);if(r){const e="status_update"===r.kind?{kind:"status_update",statusText:t.getStatusText()}:r;ue(e,$.current)}const a=t.toMessages(),s=P.current;n(e=>[...e.slice(0,e.length-s),...a]),P.current=a.length,a.some(e=>_s(e)||!vs(e.message))&&l(la(!1)),t.isStreamComplete()&&j()},[l,n,j]),K=I(e=>{Q("Stream connection error. Please try again."),j()},[j]),H=I(()=>{A.current?.abort(),R.current?.(),A.current=null,R.current=null,F.current=null,E.current.reset(),P.current=0,h(""),m(!1),v(!1),U(ie.CANCEL),l(de()),l(ma()),x.current=!1},[l,U]),G=I((e,t)=>{A.current?.abort(),R.current?.(),E.current.reset(),P.current=0,N.current=!1,F.current=t,M.current=t,A.current=e;const n=e.subscribe({onEvent:z,onError:K,onComplete:()=>{j()}});R.current=n},[z,K,j]),B=I(async(t="")=>{x.current=!0;try{let a=e;if(!a){if(!s)return x.current=!1,void Q("Conversation is not ready yet. Please wait a moment.");const e=await s();if(!e)return x.current=!1,void Q("Failed to start conversation. Please try again.");a=e}const i=t.trim();window.dispatchEvent(new CustomEvent("stopAudioPlayback")),l(la(!0)),m(!0),v(!1),l(pa(null)),l(fa(Date.now())),l(de());const c={id:`user-${Y()}`,sender:"user",message:i,timestamp:(new Date).toISOString()};n(e=>[...e,c]);const u=le(),p=d.streamMessage({conversationId:a,message:i,enableTts:r,debugMode:o,...u?{body:{client_metadata:{device_token:u}}}:{}});G(p,a)}catch(e){D.error({message:"Failed to send message",api_name:"chat-send",error_message:e instanceof Error?e.message:String(e)}),Q("Failed to send conversations message. Please try again."),x.current=!1,U(ie.CANCEL)}},[l,t,e,d,r,n,G,s,o,U]),V=C(B);V.current=B;const W=I(async(e="")=>{const t=(e??"").trim();t&&(x.current?l(ha({id:Y(),text:t,queuedAt:(new Date).toISOString()})):await B(t))},[l,B]);O(()=>{if(g||x.current)return;const e=p.getState().chat.messageQueue;if(0===e.length)return;const t=1===e.length?e[0].text:e.map(e=>`- ${e.text}`).join("\n");l(ma()),V.current(t)},[g,l,p]);const J=I(async(e,t)=>{x.current=!0,l(la(!0)),m(!0),v(!1),l(pa(null)),l(fa(Date.now())),l(de());const n=void 0!==t?t:a,s={};n&&(s.user_location=n);const o=le();o&&(s.device_token=o);const i=Object.keys(s).length>0?{client_metadata:s}:{},c=d.streamInitial({conversationId:e,body:i,enableTts:r});G(c,e)},[l,d,r,a,G]);return O(()=>()=>{A.current?.abort(),R.current?.()},[]),{sendMessage:W,startInitialStream:J,setThinkingState:L,abortStream:H,toolCallStatus:f,isProcessThinkingState:g,hasReceivedResponse:y}};function Ss({activeConversationId:e,onSelectConversation:t,onClearChat:n}){const[r,a]=k([]),s=S(e=>e.conversations.titles),[o,i]=k(!0),[c,u]=k(!1),[d,l]=k(!0),[p,f]=k(""),h=C(0),g=C(!1),m=C(d);m.current=d;const y=C(r);y.current=r;const[v]=jr.useLazyGetConversationHistoryQuery(),_=C(v);_.current=v;const[b,{isLoading:w}]=jr.useDeleteConversationMutation(),T=I(async e=>{const t="append"===e?h.current:0;if("append"===e){if(g.current||!m.current)return;g.current=!0,u(!0)}else"replace"===e&&0===y.current.length&&i(!0);try{const n=await _.current({skip:t,limit:20}).unwrap(),r=n?.conversations??[];"append"===e?(a(e=>{const t=new Set(e.map(e=>e.id));return[...e,...r.filter(e=>!t.has(e.id))]}),h.current+=20):"replace"===e?(a(r),h.current=20):a(e=>function(e,t){if(0===t.length)return e;const n=new Set(e.map(e=>e.id)),r=new Map(t.map(e=>[e.id,e])),a=t.filter(e=>!n.has(e.id));let s=a.length>0;const o=e.map(e=>{const t=r.get(e.id);return t?(n=e).id===(a=t).id&&n.title===a.title&&n.created_at===a.created_at&&n.updated_at===a.updated_at?e:(s=!0,t):e;var n,a});return s?[...a,...o]:e}(e,r)),"silent"!==e&&l(r.length>=20)}catch(e){D.error({message:"Failed to load conversations",api_name:"chat-conversation-list",error_message:e instanceof Error?e.message:String(e)})}finally{"append"===e?(g.current=!1,u(!1)):"replace"===e&&i(!1)}},[]);O(()=>{T("replace")},[T]);const E=C(null);O(()=>{!o&&e&&E.current!==e&&(r.some(t=>t.id===e)||(E.current=e,T("silent")))},[e,r,o,T]);const A=I(async s=>{const o=e===s,i=o?function(e,t){const n=e.findIndex(e=>e.id===t);return-1===n?null:n+1<e.length?e[n+1].id:n-1>=0?e[n-1].id:null}(p.trim()?r.filter(e=>e?.title?.toLowerCase().includes(p.toLowerCase())):r,s):null,c=await b({conversationId:s});if(c.error)return D.error({message:"Failed to delete conversation",api_name:"chat-conversation-delete",conversation_id:s,error_message:JSON.stringify(c.error)}),void Q("Failed to delete the conversation. Please try again.");pe("Conversation deleted successfully"),E.current=s;const u=y.current.some(e=>e.id===s);if(a(e=>e.filter(e=>e.id!==s)),u&&(h.current=Math.max(0,h.current-1)),o)if(i){const e=r.find(e=>e.id===i)??null;t(i,e?.title??null)}else n?.()},[e,r,p,b,t,n]),N=R(()=>r.map(e=>s[e.id]?{...e,title:s[e.id]}:e),[r,s]);return{conversations:p.trim()?N.filter(e=>e?.title?.toLowerCase().includes(p.toLowerCase())):N,isLoading:o,isLoadingMore:c,hasMore:d,isDeleting:w,searchQuery:p,setSearchQuery:f,loadConversations:T,deleteConversation:A,isLoadingMoreRef:g}}function ws(){return S(e=>{const t=e.conversations.activeConversationId;return t?e.conversations.titles[t]??null:null})}function Ts(e,t){if(null==e||!t)return null;const n=e/100,r=t.toUpperCase();try{return new Intl.NumberFormat("en-US",{style:"currency",currency:r}).format(n)}catch{return`${r} ${n.toFixed(2)}`}}function Es(e){if("success"===e.status){const t=Ts(e.amount,e.currency);return`The payment${t?` of ${t}`:""} is successfully completed.`}return"failure"===e.status?"The payment failed."+(e.paymentId?` The reference ID is ${e.paymentId}.`:""):"Payment cancelled."}const Is=({sendMessageRef:e})=>{const[t,n]=k(null),r=I(()=>n(null),[]),a=I(t=>{"stripe"===t.provider?"cancel"===t.status&&Q("Payment cancelled."):"chargebee"===t.provider&&"cancel"===t.status?Q("Payment cancelled."):"failure"===t.status&&t.message&&Q(t.message),e.current?e.current(Es(t)):D.error({message:"Payment result dropped: sendMessageRef is null",api_name:"payment-result-dispatch",status:t.status}),n(null)},[e]);return{paymentInit:t,setPaymentInit:n,clearPaymentInit:r,handlePaymentResult:a}};function As(e,t,n){const r=C(n);O(()=>{r.current=n},[n]),O(()=>{const n=fe.on(e,t,e=>{r.current(e)});return()=>{n()}},[e,t])}async function Rs(e){try{const t=await e.getItem(he.LOCATION_CACHE);if(!t)return null;const n=JSON.parse(t);return Date.now()-n.timestamp<36e5?n.location:(await e.removeItem(he.LOCATION_CACHE),null)}catch{return null}}const ks=()=>{const[e,t]=k(!1),[n,r]=k(null),a=ge(),s=I(async()=>{const e=await Rs(a);if(e)return e;if(!("geolocation"in navigator))return r("Geolocation is not supported by this browser"),null;if("https:"!==window.location.protocol&&"localhost"!==window.location.hostname)return r("Geolocation requires HTTPS"),null;t(!0),r(null);try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone,t=await new Promise((e,t)=>{navigator.geolocation.getCurrentPosition(e,t,{enableHighAccuracy:!1,timeout:8e3,maximumAge:6e5})}),{latitude:n,longitude:r}=t.coords;let s="";try{const e=await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${n}&lon=${r}&format=json`,{headers:{"Accept-Language":"en","User-Agent":"1interface-chat/1.0"}});e.ok&&(s=(await e.json()).display_name??"")}catch(e){D.warn({message:"Reverse geocoding failed",api_name:"user-location",error_message:e instanceof Error?e.message:String(e)})}const o={latitude:n,longitude:r,address:s,timezone:e};return await async function(e,t){try{const n={location:t,timestamp:Date.now()};await e.setItem(he.LOCATION_CACHE,JSON.stringify(n))}catch{}}(a,o),o}catch(e){if(e&&"number"==typeof e.code)switch(e.code){case 1:r("Location permission denied");break;case 2:r("Location information unavailable");break;case 3:r("Location request timed out");break;default:r("Failed to retrieve location")}else r("Failed to get location");return null}finally{t(!1)}},[a]);return{getUserLocation:s,isLoading:e,error:n}};function Os({hasMore:e,isLoadingRef:t,scrollAreaRef:n,onLoadMore:r,itemCount:a}){const s=C(null),o=I(a=>{if(s.current&&s.current.disconnect(),!a||!e)return;const o=function(e,t){const n=t?.querySelector("[data-radix-scroll-area-viewport]");if(n)return n;if(t&&t.scrollHeight>t.clientHeight)return t;let r=e.parentElement;for(;r&&r!==document.body;){if(r.scrollHeight>r.clientHeight)return r;r=r.parentElement}return null}(a,n.current);o&&(s.current=new IntersectionObserver(e=>{e[0].isIntersecting&&!t.current&&r()},{root:o,rootMargin:"0px",threshold:.1}),s.current.observe(a))},[e,t,n,r]);return O(()=>{if(!e||t.current)return;const a=n.current;if(!a)return;const s=a.querySelector("[data-radix-scroll-area-viewport]")??a;s.clientHeight>0&&s.scrollHeight<=s.clientHeight&&r()},[e,n,r,t,a]),o}const Cs=e=>{const[t,n]=k(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return O(()=>{if("undefined"==typeof window)return;const t=window.matchMedia(e),r=e=>{n(e.matches)};return n(t.matches),t.addEventListener("change",r),()=>{t.removeEventListener("change",r)}},[e]),t},Ns=()=>Cs("(min-width: 1024px)"),Ps=e=>{const t=C(null),[n,r]=k(!1);return O(()=>{const n=t.current;if(!n)return;const a=new ResizeObserver(t=>{for(const n of t)r(n.contentRect.width>=e)});a.observe(n);const s=n.getBoundingClientRect().width;return r(s>=e),()=>{a.disconnect()}},[e]),{containerRef:t,isDesktop:n}},xs=()=>{const[e,t]=k(!1),{getUserLocation:n}=ks(),r=ge(),a=C(!1);return O(()=>{if(a.current)return;a.current=!0;let e=null;const s=()=>{null!==e&&clearTimeout(e),t(!0)};return(async()=>{if("false"===await r.getItem(he.LOCATION_ENABLED))return void s();const t=await Rs(r);t&&0!==t.latitude&&0!==t.longitude?s():(e=setTimeout(s,5e3),n().finally(s))})(),()=>{null!==e&&clearTimeout(e)}},[n,r]),e};function qs({paymentInit:e,onPaymentResult:t,onClearPaymentInit:n}){const r=C(new Set),a=J(e);return{handlePaymentResult:I(e=>{"success"!==e.status&&"failure"!==e.status||a&&r.current.add(a),t?.(e)},[t,a]),handleModalOpenChange:I(s=>{!s&&e&&(!!a&&r.current.has(a)||t?.({status:"cancel",provider:e.provider}),n?.())},[e,a,t,n])}}function Ms(e){const t=e.trim().split(/\s+/);return 1===t.length?e.charAt(0).toUpperCase():(t[0].charAt(0)+t[1].charAt(0)).toUpperCase()}function Ds(){const{themeStyles:e}=me(),{data:t,isLoading:n}=Vr(void 0),[r]=Jr(),a=R(()=>(t?.tool_servers??[]).map(t=>({id:t.id,name:t.name,description:t.description??"",initials:Ms(t.name),accentTextColor:e.statusPrimary.solid,logoUrl:t.logo_url??void 0,connected:t.connected})),[t?.tool_servers,e.statusPrimary.solid]);return{connectors:a,isLoading:n,disconnect:async function(e){const t=a.find(t=>t.id===e)?.name??"App";"error"in await r(e)?Q(`Failed to disconnect ${t}. Please try again.`):pe(`${t} disconnected`)}}}const Qs={NORMAL:"normal",RECORDING:"recording",TRANSCRIBING:"transcribing"},Fs=({onSend:e,disabled:t=!1,transcribedText:n,onTranscribedTextUsed:r,isRecording:a=!1,isTranscribing:s=!1})=>{const[o,i]=k("");O(()=>{if(!n)return;let e=!1;return queueMicrotask(()=>{e||(i(e=>0===e.trim().length?n:`${e.trimEnd()} ${n}`),r?.())}),()=>{e=!0}},[n,r]);const c=o.trim().length>0&&!t,u=I(()=>{const n=o.trim();n&&!t&&(e(n),i(""))},[o,t,e]),d=a?Qs.RECORDING:s?Qs.TRANSCRIBING:Qs.NORMAL;return R(()=>({value:o,setValue:i,send:u,canSend:c,mode:d}),[o,u,c,d])},Us=e=>{for(let t=e.length-1;t>=0;t--)if("user"===e[t].sender)return t;return-1},Ls=e=>{const t=S(e=>!!e.voice?.isAgentWorking),n=S(e=>e.voice?.statusText??null),r=S(e=>e.voice?.responseStartTime??null),a=S(e=>e.chat.isAgentWorking),s=S(e=>e.chat.statusText??null),o=S(e=>e.chat.responseStartTime),i=S(e=>e.indicator.lastResponseTime),c=e?t:a,u=e?n:s,d=e?r:o;return R(()=>({isAgentWorking:c,statusText:u??void 0,responseStartTime:d,lastResponseTime:i}),[c,u,d,i])},js=[],$s=({messages:e,voiceStreamingMessages:t=js,voiceActive:n})=>{const r=R(()=>{if(0===t.length)return e;const n=new Set(t.map(e=>e.id));return e.filter(e=>!n.has(e.id))},[e,t]),a=R(()=>Us(r),[r]),s=Ls(n),o=C(e.length),i=I(()=>{const t=o.current;return o.current=e.length,((e,t)=>{const n=t.length-1,r=Us(t);if(t.length<=e)return{hasNew:!1,newMessages:[],firstNewIndex:e,lastIndex:n,hasNewUserMessage:!1,hasNewWidget:!1,lastUserMessageIndex:r};const a=t.slice(e);return{hasNew:!0,newMessages:a,firstNewIndex:e,lastIndex:n,hasNewUserMessage:a.some(e=>"user"===e.sender),hasNewWidget:a.some(ye),lastUserMessageIndex:r}})(t,e)},[e]);return{visibleMessages:r,lastUserMessageIndex:a,indicator:s,classifyArrival:i}},zs=(e={})=>{const{enabled:t=!0}=e,[n,r]=k(cs.INITIAL),[a,s]=k(0),[o,i]=k(!0),c=C(null),u=C(null),d=C(null);return O(()=>{if(!t)return r(cs.INITIAL),s(0),void i(!0);r(cs.INITIAL),s(0),i(!0);let e=cs.INITIAL;const n=()=>{c.current=setTimeout(()=>{i(!1),d.current=setTimeout(()=>{s(t=>(t+1)%e.length),i(!0),d.current=null},500),n()},cs.ROTATION_INTERVAL_MS)};return n(),u.current=setTimeout(()=>{e=cs.LATER,c.current&&clearTimeout(c.current),d.current&&clearTimeout(d.current),r(cs.LATER),s(0),i(!1),d.current=setTimeout(()=>{i(!0),d.current=null},500),n()},cs.PHASE_SWITCH_MS),()=>{c.current&&clearTimeout(c.current),u.current&&clearTimeout(u.current),d.current&&clearTimeout(d.current),c.current=null,u.current=null,d.current=null}},[t]),{message:n[a],isVisible:o}},Ks=e=>{const[t,n]=k(()=>null===e?0:Math.floor((Date.now()-e)/1e3));return O(()=>{if(null===e)return void n(0);n(Math.floor((Date.now()-e)/1e3));const t=setInterval(()=>{n(Math.floor((Date.now()-e)/1e3))},1e3);return()=>clearInterval(t)},[e]),t};function Hs(e,t=28){const[n,r]=k(e),a=C(e),s=I(e=>{a.current=e,r(e)},[]);return O(()=>{if(a.current===e)return;const n=function(e,t){const n=Math.min(e.length,t.length);let r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}(a.current,e);s(e.slice(0,n));let r=n;const o=globalThis.setInterval(()=>{r+=1,s(e.slice(0,r)),r>=e.length&&globalThis.clearInterval(o)},t);return()=>globalThis.clearInterval(o)},[e,t,s]),n}const Gs=P(null),Bs=()=>{const e=x(Gs);if(!e)throw new Error("useChatSettings must be used within a <SettingsProvider>");return e};let Vs=0;function Ws({refreshSession:e,checkIntervalMs:t=6e4}){const n=b(),r=S(e=>e.auth),a=r?.accessToken??null,s=Boolean(r?.isAuthenticated),o=r?.tokenExpiresAt??null,i=C(null),c=C(null),u=I(()=>{n.dispatch(U())},[n]),d=I(async(t=!1)=>{if(t||!(Date.now()-Vs<3e5))try{await e()?Vs=Date.now():(D.error({message:"Session cleared: proactive token refresh failed",api_name:"auth-refresh"}),u())}catch(e){D.error({message:"Token refresh failed",api_name:"auth-refresh",error_message:e instanceof Error?e.message:String(e)}),u()}},[e,u]),l=I(()=>{s&&(oe(o)?d(!0):X(o)&&d())},[s,o,d]);return O(()=>{a&&oe(o)&&d(!0)},[]),O(()=>{if(s&&a){if(oe(o))return void d(!0);const e=ve(o);return e>0?c.current=setTimeout(()=>{d()},e):X(o)&&d(),i.current=setInterval(()=>{oe(o)?d(!0):X(o)&&d()},t),()=>{i.current&&clearInterval(i.current),c.current&&clearTimeout(c.current)}}Vs=0,i.current&&(clearInterval(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null)},[s,a,o,t,d]),{checkNow:l}}class Js{mediaRecorder=null;audioChunks=[];stream=null;audioContext=null;analyser=null;dataArray=null;animationFrameId=null;onAudioLevel;async startRecording(e){try{if(this.onAudioLevel=e,!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Microphone access requires HTTPS. Please access the app via https:// or localhost.");this.stream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,sampleRate:24e3,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),e&&(this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.audioContext.createMediaStreamSource(this.stream).connect(this.analyser),this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.analyzeAudio());const t=this.getSupportedMimeType();this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:t}),this.audioChunks=[],this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&this.audioChunks.push(e.data)},this.mediaRecorder.start()}catch(e){throw this.cleanup(),e}}async stopRecording(){return new Promise((e,t)=>{this.mediaRecorder?(this.mediaRecorder.onstop=()=>{const t=this.mediaRecorder?.mimeType||"audio/webm",n=t.includes("webm")?"webm":"ogg",r=new Blob(this.audioChunks,{type:t}),a=new File([r],`audio.${n}`,{type:t});this.cleanup(),e(a)},this.mediaRecorder.stop(),this.stream&&this.stream.getTracks().forEach(e=>e.stop())):t(new Error("MediaRecorder not initialized"))})}analyzeAudio(){if(!this.analyser||!this.dataArray)return;this.analyser.getByteFrequencyData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++)e+=this.dataArray[t];const t=Math.min(e/this.dataArray.length/128,1);this.onAudioLevel&&this.onAudioLevel(t),this.animationFrameId=requestAnimationFrame(()=>this.analyzeAudio())}getSupportedMimeType(){const e=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg"];for(const t of e)if(MediaRecorder.isTypeSupported(t))return t;return"audio/webm"}cleanup(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null),this.analyser=null,this.dataArray=null,this.mediaRecorder=null,this.audioChunks=[],this.onAudioLevel=void 0}}const Xs=({onTranscriptionComplete:e,onTranscriptionPopulate:t,autoSendVoice:n=!0}={})=>{const[r,a]=k(!1),[s,o]=k(!1),[i,c]=k(0),u=C(null),d=C(null),l=C(!1),p=C(null),[f]=zr(),h=I(async()=>{try{u.current||(u.current=new Js),d.current=Date.now();const e=()=>{p.current?.(),document.removeEventListener("mouseup",e),document.removeEventListener("touchend",e),document.removeEventListener("pointerup",e)};document.addEventListener("mouseup",e),document.addEventListener("touchend",e),document.addEventListener("pointerup",e),await u.current.startRecording(e=>{c(e)}),l.current=!0,a(!0)}catch(e){D.error({message:"Failed to start STT recording",api_name:"stt-record",error_message:e instanceof Error?e.message:String(e)}),l.current=!1,Q("Microphone access is required. Please allow microphone permissions in your browser settings.")}},[]),g=I(async()=>{try{if(!u.current||!l.current)return;const r=d.current?Date.now()-d.current:0;if(a(!1),c(0),r<500)return u.current?.cleanup(),void(d.current=null);o(!0);const s=await u.current.stopRecording(),i=await f({audioFile:s}).unwrap();i.success?i.data.text&&(n&&e?await e(i.data.text):!n&&t&&t(i.data.text)):Q("Transcription failed")}catch(e){D.error({message:"STT transcription failed",api_name:"stt-transcribe",error_message:e instanceof Error?e.message:String(e)}),Q("Failed to transcribe audio")}finally{o(!1),l.current=!1,u.current?.cleanup(),d.current=null}},[n,e,t,f]);return O(()=>{p.current=g},[g]),O(()=>()=>{u.current?.cleanup()},[]),{isRecording:r,isTranscribing:s,audioLevel:i,startRecording:h,stopRecording:g}},Zs="OAUTH_SUCCESS",Ys="OAUTH_ERROR",eo=Zs,to=Ys;function no({signInInit:e,sendMessageRef:t,clearSignInInit:n,sendResumeMessage:r=!0}){const[a]=Kr();O(()=>{if(!e)return;const s=function(e){try{const t=(new URL(e).searchParams.get("scope")??"").match(/\/auth\/([^./]+)/);if(t?.[1])return t[1].charAt(0).toUpperCase()+t[1].slice(1)}catch{}return"Service"}(e.authorize_url),o=window.open(e.authorize_url,"oauth_popup",`width=500,height=650,left=${Math.round(screen.width/2-250)},top=${Math.round(screen.height/2-325)}`);if(!o)return Q("Please allow popups for this site to sign in to external services."),void n();let i=!1;const c=e=>{i||(i=!0,window.removeEventListener("message",u),clearInterval(d),e?.(),n())},u=async e=>{if(e.origin!==window.location.origin)return;if(i)return;if(e.data?.type===to)return void c(()=>Q(`Failed to sign in to ${s}. Please try again.`));if(e.data?.type!==eo)return;i=!0,window.removeEventListener("message",u),clearInterval(d);const{code:l,state:p}=e.data;"error"in await a({code:l,state:p})?Q(`Failed to sign in to ${s}. Please try again.`):(pe(`${s} connected successfully`),r&&t.current?.(`${s} is now signed in, please continue`)),n(),o?.close()},d=setInterval(()=>{o.closed&&c()},500);return window.addEventListener("message",u),()=>{window.removeEventListener("message",u),clearInterval(d),i||o.close()}},[e,t,n,a,r])}function ro({sendMessageRef:e}){const{paymentInit:t,setPaymentInit:n,clearPaymentInit:r,handlePaymentResult:a}=Is({sendMessageRef:e}),{handlePaymentResult:s,handleModalOpenChange:o}=qs({paymentInit:t,onPaymentResult:a,onClearPaymentInit:r});return{paymentInit:t,setPaymentInit:n,isOpen:!!t,onOpenChange:o,onResult:s,clearPaymentInit:r}}const ao={conversations:{disable_old_widgets:!1,allow_conversation_deletion:!0},voice_agent:{enabled:!0,show_customization_modal:!1,assistant_starts_conversation:!0},features:[_e.SSO],backend_version:"",panel_switcher_enabled:!0},so=P(void 0),oo=()=>{const{data:e,isLoading:t,error:n}=Pa(),r=e?.success?e.data:null,a=R(()=>{return(e=r)?{conversations:{...ao.conversations,...e.conversations},voice_agent:{...ao.voice_agent,...e.voice_agent},features:e.features??ao.features,backend_version:e.backend_version??ao.backend_version,panel_switcher_enabled:e.panel_switcher_enabled??ao.panel_switcher_enabled}:ao;var e},[r]);return R(()=>({clientConfig:a,isLoading:t,error:n?new Error("Failed to fetch client configuration"):null}),[a,t,n])},io=()=>{const e=x(so);if(!e)throw new Error("useConfiguration must be used within a ConfigurationProvider");return e},co=P({}),uo=()=>x(co);function lo(e){return Array.isArray(e.message_type)&&e.message_type.includes("widget")}function po(e,t,n){if(!n)return!1;if(!lo(e))return!1;let r=null;for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&lo(n)){r=n;break}}if(!r||r.id!==e.id)return!0;const a=t.findIndex(t=>t.id===e.id);return t.slice(a+1).some(e=>"user"===e.sender)}const fo="moyasar_cb";function ho(e){const t=new URL(window.location.href),n=new URL(`${t.origin}${be()}/moyasar-callback.html`);return n.searchParams.set(fo,"1"),e&&n.searchParams.set("given_id",e),n.toString()}const go=new Set(["paid","authorized","failed","captured"]);function mo(e){if(!e)return null;const t=new URLSearchParams(e);if("1"!==t.get(fo))return null;const n=t.get("status"),r=t.get("id");if(!n||!r)return null;if(!go.has(n))return null;const a=t.get("conversation_id")||null,s=(t.get("given_id")||null)??r;if("paid"===n||"authorized"===n||"captured"===n){const e=t.get("amount"),n=e?Number.parseInt(e,10):void 0;return{result:{status:"success",provider:"moyasar",paymentId:s,amount:Number.isFinite(n)?n:void 0,currency:t.get("currency")??void 0},conversationId:a}}return{result:{status:"failure",provider:"moyasar",code:n,message:yo(t.get("message")??`Payment ${n}`),paymentId:s},conversationId:a}}function yo(e){try{const t=decodeURIComponent(e);return t===e?e:t}catch{return e}}function vo(e,t){const n="dark"===t;return{pageBg:e.bgColor,cardBg:e.widgetBg,text:e.primaryText,heading:e.primaryText,muted:e.secondaryText,divider:e.widgetBorderColor,accent:e.statusDiscovery.solid,accentText:e.statusDiscovery.text,focus:e.statusDiscovery.solid,pillBg:e.inputBgColor,pillBorder:e.inputBorderColor,pillText:e.secondaryText,cardShadow:n?"0 1px 3px rgba(0,0,0,0.4), 0 0 0 1px rgba(255,255,255,0.04)":"0 1px 3px rgba(0,0,0,0.08), 0 0 0 1px rgba(0,0,0,0.04)",radius:e.borderRadius,fontFamily:e.fontFamily,colorScheme:n?"dark":"light"}}const _o="stripe";export{ja as AguiAdapter,Js as AudioRecorder,is as BREAKPOINTS,Qs as CHAT_INPUT_MODES,ds as CONVERSATION_TITLE_REFRESH_DELAYS_MS,co as ChatCallbacksContext,Gs as ChatSettingsContext,so as ConfigurationContext,ps as DEFAULT_CONVERSATION_TITLE,_o as DEFAULT_PAYMENT_PROVIDER,Ma as DEFAULT_PROTOCOL,qr as ERROR_CODES,Ka as EventAggregator,Nr as GENERIC_SERVER_ERROR_MESSAGE,Da as MAX_CONNECTION_RETRIES,fo as MOYASAR_CALLBACK_SENTINEL,Ys as OAUTH_ERROR_TYPE,Zs as OAUTH_SUCCESS_TYPE,us as PAGINATION,Ua as ProprietaryAdapter,xa as ProtocolContext,Qa as SSEEventType,cs as THINKING_MESSAGES,ls as TYPEWRITER_INTERVAL_MS,Dr as apiBridge,ca as apiMiddleware,ia as apiReducers,Ia as bindChatLogger,Zr as brandingApi,Ur as bridgedFetch,vo as buildBrandSkin,ho as buildCallbackUrl,jr as chatApi,ka as chatCoreRootReducer,Ra as chatLoggerContextProvider,va as chatReducer,es as checkOrganizationExistsApi,ma as clearMessageQueue,ta as configApi,Ta as conversationsReducer,$a as createAdapter,za as createDefaultAdapterConfig,ss as createSessionRefresher,ga as dequeueMessage,ha as enqueueMessage,Ya as fetchOrganizations,Wa as forgotPasswordApi,Ts as formatAmount,Es as formatResultMessage,xr as getApiErrorMessage,Qr as getAuthToken,Rs as getCachedLocation,Lr as getLatestRequestId,_s as hasAnyExtraData,Pr as isApiServerError,vs as isEmptyMessage,Ha as loginApi,Ba as logoutApi,mo as parseMoyasarCallbackFromUrl,ra as profileApi,Va as refreshTokenApi,Aa as resetChatLoggerForTests,ya as resetChatState,Ja as resetPasswordApi,Oa as serializableCheck,Sa as setActiveConversationId,la as setIsAgentWorking,fa as setResponseStartTime,pa as setStatusText,po as shouldDisableMessage,Ga as signupApi,Za as ssoExchangeApi,Xa as ssoStartApi,Ca as store,wa as upsertConversationTitle,ws as useActiveConversationTitle,os as useAuth,uo as useChatCallbacks,bs as useChatConnection,Ss as useChatHistory,Fs as useChatInput,Bs as useChatSettings,io as useConfiguration,oo as useConfigurationValue,Ds as useConnectors,Ps as useContainerQuery,ys as useConversation,$r as useCreateConversatonsMutation,oa as useDeleteAccountMutation,Br as useDeleteConversationMutation,Jr as useDeleteToolServerConnectionMutation,Ks as useElapsedSeconds,As as useEventEmitter,Kr as useExchangeOAuthCodeMutation,Yr as useGetBrandingQuery,Pa as useGetConfigQuery,Hr as useGetConversationHistoryQuery,aa as useGetProfileQuery,Vr as useGetToolServersQuery,Os as useInfiniteScroll,Ns as useIsDesktop,Gr as useLazyGetConversationByIdQuery,xs as useLocationInit,ts as useLogin,rs as useLogout,Cs as useMediaQuery,$s as useMessageList,no as useOAuthPopup,ro as usePayment,Is as usePaymentFlow,qs as usePaymentResultDedup,qa as useProtocol,as as useRefreshToken,Ls as useResolvedChatIndicators,Xs as useSTTRecording,ns as useSignup,Wr as useStartToolServerOAuthMutation,zs as useThinkingMessage,Ws as useTokenRefresh,zr as useTranscribeAudioMutation,Hs as useTypewriter,sa as useUpdateProfileMutation,ks as useUserLocation};
|