@1interface/chat-shell 0.1.0 → 0.1.1

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.
@@ -1 +0,0 @@
1
- import{createAction as e,nanoid as t,formatProdErrorMessage as n,createSelector as r,createAsyncThunk as o,createSlice as i,prepareAutoBatched as s,isAnyOf as a,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,createListenerMiddleware as b,configureStore as _}from"@reduxjs/toolkit";import{useSelector as S,useStore as w,useDispatch as T,shallowEqual as E,batch as k,Provider as I}from"react-redux";import{useContext as F,createContext as A,useCallback as x,useState as P,useEffect as C,useMemo as O,useDebugValue as R,useRef as M,useLayoutEffect as N,Suspense as D,lazy as q}from"react";import{jsx as Q,Fragment as j}from"react/jsx-runtime";var B=Symbol.for("immer-nothing"),z=Symbol.for("immer-draftable"),$=Symbol.for("immer-state"),U="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 L(e,...t){if("production"!==process.env.NODE_ENV){const n=U[e],r=fe(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 K=Object,W=K.getPrototypeOf,V="constructor",H="prototype",G="configurable",J="enumerable",X="writable",Y="value",Z=e=>!!e&&!!e[$];function ee(e){return!!e&&(re(e)||ue(e)||!!e[z]||!!e[V]?.[z]||de(e)||le(e))}var te=K[H][V].toString(),ne=new WeakMap;function re(e){if(!e||!pe(e))return!1;const t=W(e);if(null===t||t===K[H])return!0;const n=K.hasOwnProperty.call(t,V)&&t[V];if(n===Object)return!0;if(!fe(n))return!1;let r=ne.get(n);return void 0===r&&(r=Function.toString.call(n),ne.set(n,r)),r===te}function oe(e,t,n=!0){0===ie(e)?(n?Reflect.ownKeys(e):K.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function ie(e){const t=e[$];return t?t.type_:ue(e)?1:de(e)?2:le(e)?3:0}var se=(e,t,n=ie(e))=>2===n?e.has(t):K[H].hasOwnProperty.call(e,t),ae=(e,t,n=ie(e))=>2===n?e.get(t):e[t],ce=(e,t,n,r=ie(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n},ue=Array.isArray,de=e=>e instanceof Map,le=e=>e instanceof Set,pe=e=>"object"==typeof e,fe=e=>"function"==typeof e,he=e=>"boolean"==typeof e,ge=e=>e.copy_||e.base_,me=e=>e.modified_?e.copy_:e.base_;function ye(e,t){if(de(e))return new Map(e);if(le(e))return new Set(e);if(ue(e))return Array[H].slice.call(e);const n=re(e);if(!0===t||"class_only"===t&&!n){const t=K.getOwnPropertyDescriptors(e);delete t[$];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const o=n[r],i=t[o];!1===i[X]&&(i[X]=!0,i[G]=!0),(i.get||i.set)&&(t[o]={[G]:!0,[X]:!0,[J]:i[J],[Y]:e[o]})}return K.create(W(e),t)}{const t=W(e);if(null!==t&&n)return{...e};const r=K.create(t);return K.assign(r,e)}}function ve(e,t=!1){return _e(e)||Z(e)||!ee(e)||(ie(e)>1&&K.defineProperties(e,{set:be,add:be,clear:be,delete:be}),K.freeze(e),t&&oe(e,(e,t)=>{ve(t,!0)},!1)),e}var be={[Y]:function(){L(2)}};function _e(e){return null===e||!pe(e)||K.isFrozen(e)}var Se="MapSet",we="Patches",Te="ArrayMethods",Ee={};function ke(e){const t=Ee[e];return t||L(0,e),t}var Ie,Fe=e=>!!Ee[e],Ae=()=>Ie;function xe(e,t){t&&(e.patchPlugin_=ke(we),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Pe(e){Ce(e),e.drafts_.forEach(Re),e.drafts_=null}function Ce(e){e===Ie&&(Ie=e.parent_)}var Oe=e=>Ie={drafts_:[],parent_:Ie,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:Fe(Se)?ke(Se):void 0,arrayMethodsPlugin_:Fe(Te)?ke(Te):void 0};function Re(e){const t=e[$];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function Me(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[$].modified_&&(Pe(t),L(4)),ee(e)&&(e=Ne(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[$].base_,e,t)}else e=Ne(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ve(t,n)}(t,e,!0),Pe(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==B?e:void 0}function Ne(e,t){if(_e(t))return t;const n=t[$];if(!n)return ze(t,e.handledSet_,e);if(!qe(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);Be(n,e)}return n.copy_}function De(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var qe=(e,t)=>e.scope_===t,Qe=[];function je(e,t,n,r){const o=ge(e),i=e.type_;if(void 0!==r&&ae(o,r,i)===t)return void ce(o,r,n,i);if(!e.draftLocations_){const t=e.draftLocations_=new Map;oe(o,(e,n)=>{if(Z(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const s=e.draftLocations_.get(t)??Qe;for(const e of s)ce(o,e,n,i)}function Be(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)}De(e)}}function ze(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Z(e)||t.has(e)||!ee(e)||_e(e)||(t.add(e),oe(e,(r,o)=>{if(Z(o)){const t=o[$];if(qe(t,n)){const n=me(t);ce(e,r,n,e.type_),De(t)}}else ee(o)&&ze(o,t,n)})),e}var $e={get(e,t){if(t===$)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 o=ge(e);if(!se(o,t,e.type_))return function(e,t,n){const r=Ke(t,n);return r?Y in r?r[Y]:r.get?.call(e.draft_):void 0}(e,o,t);const i=o[t];if(e.finalized_||!ee(i))return i;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return i;if(i===Le(e.base_,t)){Ve(e);const n=1===e.type_?+t:t,r=He(0,i,e,n);return e.copy_[n]=r}return i},has:(e,t)=>t in ge(e),ownKeys:e=>Reflect.ownKeys(ge(e)),set(e,t,n){const r=Ke(ge(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=Le(ge(e),t),s=r?.[$];if(s&&s.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((o=n)===(i=r)?0!==o||1/o==1/i:o!=o&&i!=i)&&(void 0!==n||se(e.base_,t,e.type_)))return!0;Ve(e),We(e)}var o,i;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(Z(n)){const o=n[$];qe(o,r)&&o.callbacks_.push(function(){Ve(e);const r=me(o);je(e,n,r,t)})}else ee(n)&&e.callbacks_.push(function(){const o=ge(e);3===e.type_?o.has(n)&&ze(n,r.handledSet_,r):ae(o,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&ze(ae(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(Ve(e),void 0!==Le(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),We(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=ge(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[X]:!0,[G]:1!==e.type_||"length"!==t,[J]:r[J],[Y]:n[t]}:r},defineProperty(){L(11)},getPrototypeOf:e=>W(e.base_),setPrototypeOf(){L(12)}},Ue={};for(let e in $e){let t=$e[e];Ue[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function Le(e,t){const n=e[$];return(n?ge(n):e)[t]}function Ke(e,t){if(!(t in e))return;let n=W(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=W(n)}}function We(e){e.modified_||(e.modified_=!0,e.parent_&&We(e.parent_))}function Ve(e){e.copy_||(e.assigned_=new Map,e.copy_=ye(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function He(e,t,n,r){const[o,i]=de(t)?ke(Se).proxyMap_(t,n):le(t)?ke(Se).proxySet_(t,n):function(e,t){const n=ue(e),r={type_:n?1:0,scope_:t?t.scope_:Ae(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let o=r,i=$e;n&&(o=[r],i=Ue);const{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,[a,r]}(t,n);return(n?.scope_??Ae()).drafts_.push(o),i.callbacks_=n?.callbacks_??[],i.key_=r,n&&void 0!==r?function(e,t,n){e.callbacks_.push(function(r){const o=t;if(!o||!qe(o,r))return;r.mapSetPlugin_?.fixSetContents(o);const i=me(o);je(e,o.draft_??o,i,n),Be(o,r)})}(n,i,r):i.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(i);const{patchPlugin_:t}=e;i.modified_&&t&&t.generatePatches_(i,[],e)}),o}function Ge(e){return Z(e)||L(10,e),Je(e)}function Je(e){if(!ee(e)||_e(e))return e;const t=e[$];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 oe(n,(e,t)=>{ce(n,e,Je(t))},r),t&&(t.finalized_=!1),n}Ue.deleteProperty=function(e,t){return"production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&L(13),Ue.set.call(this,e,t,void 0)},Ue.set=function(e,t,n){return"production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&L(14),$e.set.call(this,e[0],t,n,e[0])},new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(fe(e)&&!fe(t)){const n=t;t=e;const r=this;return function(e=n,...o){return r.produce(e,e=>t.call(this,e,...o))}}let r;if(fe(t)||L(6),void 0===n||fe(n)||L(7),ee(e)){const o=Oe(this),i=He(0,e,void 0);let s=!0;try{r=t(i),s=!1}finally{s?Pe(o):Ce(o)}return xe(o,n),Me(r,o)}if(!e||!pe(e)){if(r=t(e),void 0===r&&(r=e),r===B&&(r=void 0),this.autoFreeze_&&ve(r,!0),n){const t=[],o=[];ke(we).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:o}),n(t,o)}return r}L(1,e)},this.produceWithPatches=(e,t)=>{if(fe(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]},he(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),he(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),he(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){ee(e)||L(8),Z(e)&&(e=Ge(e));const t=Oe(this),n=He(0,e,void 0);return n[$].isManual_=!0,Ce(t),n}finishDraft(e,t){const n=e&&e[$];n&&n.isManual_||L(9);const{scope_:r}=n;return xe(r,t),Me(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=ke(we).applyPatches_;return Z(e)?r(e,t):this.produce(e,e=>r(e,t))}},Error;var Xe=(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})}}},Ye=(e,t,n)=>{const{memoize:r,memoizeOptions:o}=t,{inputSelectorResults:i,inputSelectorResultsCopy:s}=e,a=r(()=>({}),...o);if(a.apply(null,i)!==a.apply(null,s)){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:i,secondInputs:s,stack:e})}},Ze={inputStabilityCheck:"once",identityFunctionCheck:"once"},et=e=>Array.isArray(e)?e:[e];function tt(e,t){const n=[],{length:r}=e;for(let o=0;o<r;o++)n.push(e[o].apply(null,t));return n}var nt="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function rt(){return{s:0,v:void 0,o:null,p:null}}function ot(e,t={}){let n={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:r}=t;let o,i=0;function s(){let t=n;const{length:s}=arguments;for(let e=0,n=s;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=rt(),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=rt(),e.set(n,t)):t=r}}const a=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),i++,r){const e=o?.deref?.()??o;null!=e&&r(e,c)&&(c=e,0!==i&&i--),o="object"==typeof c&&null!==c||"function"==typeof c?new nt(c):c}return a.s=1,a.v=c,c}return s.clearCache=()=>{n={s:0,v:void 0,o:null,p:null},s.resetResultsCount()},s.resultsCount=()=>i,s.resetResultsCount=()=>{i=0},s}function it(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t,r=0,o=0,i={},s=e.pop();"object"==typeof s&&(i=s,s=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(s,`createSelector expects an output function after the inputs, but received: [${typeof s}]`);const a={...n,...i},{memoize:c,memoizeOptions:u=[],argsMemoize:d=ot,argsMemoizeOptions:l=[],devModeChecks:p={}}=a,f=et(u),h=et(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++,s.apply(null,arguments)},...f);let y=!0;const v=d(function(){o++;const e=tt(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}={...Ze,...t};return{identityFunctionCheck:{shouldRun:"always"===n||"once"===n&&e,run:Xe},inputStabilityCheck:{shouldRun:"always"===r||"once"===r&&e,run:Ye}}})(y,p);if(n.shouldRun&&n.run(s,e,t),r.shouldRun){const t=tt(g,arguments);r.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:f},arguments)}y&&(y=!1)}return t},...h);return Object.assign(v,{resultFunc:s,memoizedResultFunc:m,dependencies:g,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>t,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(r,{withTypes:()=>r}),r}var st=it(ot),at=Object.assign((e,t=st)=>{!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:()=>at}),ct="__rtkq/",ut="online",dt="offline",lt="focus",pt="focused",ft="visibilitychange",ht=e(`${ct}${pt}`),gt=e(`${ct}un${pt}`),mt=e(`${ct}${ut}`),yt=e(`${ct}${dt}`),vt=!1;WeakMap,new Error("Promise never resolved before cacheEntryRemoved.");const bt="DEBUG",_t="INFO",St="WARN",wt="ERROR";let Tt=null,Et=null;const kt=[];function It(e,t){const n=Et?function(e){try{return e()??{}}catch{return{}}}(Et):{},{message:r,...o}=t,i={...n,...o,level:e,message:r,timestamp:(new Date).toISOString()};Tt?Tt.emit(i):(kt.length>=200&&kt.shift(),kt.push(i))}const Ft={debug(e){It(bt,e)},info(e){It(_t,e)},warn(e){It(St,e)},error(e){It(wt,e)},flush:()=>Tt?.flush?.()},At={[bt]:0,[_t]:1,[St]:2,[wt]:3};function xt(e={}){const t=At[e.minLevel??bt];return{emit(e){At[e.level]<t||(e.level===wt?console.error:e.level===St?console.warn:e.level===bt?console.debug:console.info)(e)}}}const Pt={[bt]:5,[_t]:9,[St]:13,[wt]:17};function Ct(e){if(null===e)return"null";const t=typeof e;if("string"===t||"number"===t||"boolean"===t)return e;if(e instanceof Error)return JSON.stringify({name:e.name,message:e.message,stack:e.stack});try{return JSON.stringify(e)}catch{return String(e)}}function Ot(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=Ct(r));return t}let Rt=!1,Mt=null,Nt=!0;function Dt(e){Nt=e}Object.freeze(Object.defineProperty({__proto__:null,initLogger:function(e){Rt||(Rt=!0,function(e){Et=e}(function(e){const t={app_name:e.appName,app_version:e.appVersion,environment:e.environment};return()=>({...t,...e.getContext()})}(e)),function(e){if(Tt=e,kt.length>0){const t=kt.splice(0,kt.length);for(const n of t)e.emit(n)}}(function(e){const t=[xt({minLevel:e.consoleMinLevel??(e.isDev?bt:St)})];if(e.otlpEndpoint&&!e.isDev){const n="otel"===(e.logTransport??"otel")?function(e){let t=!1,n=null,r=null;const o=[];function i(){r||(r=async function(){const[t,r,i,s]=await Promise.all([import("./index-Bs9yNhX-.js"),import("./index-_NPuwCXg.js"),import("./index-AVWXcG-i.js"),import("./index-BQf9Yax1.js")]),a=s.resourceFromAttributes(e.resourceAttrs),c=new i.OTLPLogExporter({url:e.endpoint}),u=new r.LoggerProvider({resource:a,processors:[new r.BatchLogRecordProcessor(c)]});t.logs.setGlobalLoggerProvider(u);const d=t.logs.getLogger(e.resourceAttrs["service.name"]??"app");if(n={emit(e){const{level:t,message:n,timestamp:r,...o}=e;d.emit({severityNumber:Pt[t],severityText:t,body:JSON.stringify(e),attributes:Ot(o),timestamp:new Date(r)})},async flush(){await u.forceFlush()}},o.length>0){const e=o.splice(0,o.length);for(const t of e)n.emit(t)}}().catch(()=>{o.length=0,n=null,t=!0}))}return{emit(e){t||(n?n.emit(e):(i(),o.length>=200&&o.shift(),o.push(e)))},async flush(){(r||n)&&(i(),await r,n&&await n.flush())}}}({endpoint:e.otlpEndpoint,resourceAttrs:{"service.name":e.appName,"service.version":e.appVersion,"deployment.environment":e.environment}}):function(e){const t=e.maxBatchSize??50,n=e.scheduledDelayMs??5e3,r=e.maxQueueSize??2048,o=e.wrapBatch??(e=>e),i=[];let s=null;function a(){return null!==s&&(clearTimeout(s),s=null),0===i.length||0===(t=i.splice(0,i.length)).length?Promise.resolve():fetch(e.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o(t)),keepalive:!0}).then(()=>{}).catch(()=>{});var t}return{emit(e){i.length>=r&&i.shift(),i.push(e),i.length>=t?a():null===s&&(s=setTimeout(()=>{s=null,a()},n))},async flush(){await a()}}}({endpoint:e.otlpEndpoint});t.push({emit(e){Nt&&n.emit(e)},flush:n.flush.bind(n)})}return e.extraSinks?.length&&t.push(...e.extraSinks),1===t.length?t[0]:function(e){return{emit(t){for(const n of e)try{n.emit(t)}catch{}},async flush(){await Promise.all(e.map(e=>e.flush?Promise.resolve(e.flush()).catch(()=>{}):Promise.resolve()))}}}(t)}(e)),!1!==e.flushOnAppHide&&Mt?.())},registerPlatformFlushAttacher:function(e){Mt=e},resetInitLoggerStateForTests:function(){Rt=!1,Mt=null,Nt=!0},setNetworkLoggingEnabled:Dt},Symbol.toStringTag,{value:"Module"}));let qt,Qt="",jt={},Bt=null,zt=()=>null,$t=()=>null;const Ut=()=>Qt,Lt=()=>qt,Kt=()=>jt,Wt=()=>Bt,Vt=e=>{zt=e},Ht=e=>{$t=e},Gt=e=>{const t=e.startsWith("/")?e:`/${e}`;return`${Qt}/api${t}`},Jt={CONVERSATIONS:()=>Gt("/conversations"),CONVERSATION_STREAM:e=>Gt(`/conversations/${e}`),CONVERSATION_START:e=>Gt(`/conversations/${e}/start`),get TRANSCRIBE(){return Gt("/transcribe")},get BRANDING(){return Gt("/branding")},get CONFIG(){return Gt("/config")},get PROFILE(){return Gt("/profile")},get AUTH_ME(){return Gt("/auth/me")},get ORGANIZATIONS_EXISTS(){return Gt("/organizations/exists")},get DEBUG(){return Gt("/debug")},get TOOL_SERVERS(){return Gt("/tool-servers")},TOOL_SERVER_AUTH_START:e=>Gt(`/tool-servers/${e}/auth/start`),TOOL_SERVER_AUTH_CONNECTION:e=>Gt(`/tool-servers/${e}/auth/connection`),get TOOL_SERVERS_SIGN_IN_EXCHANGE(){return Gt("/tool-servers/auth/exchange")},get LOG(){return Gt("/log")}},Xt="accessToken",Yt="refreshToken",Zt="tokenExpiresAt",en="user",tn="1interface_appearance_mode",nn="1interface_location_enabled",rn="1interface_debug_mode",on="1interface_stt_auto_send",sn="1interface_stt_implementation",an="1interface_send_diagnostics",cn="online",un=e=>e?`${tn}:${e}`:tn,dn=(e="Please try again")=>function(e){"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("bridge-toast",{detail:e}))}({title:"Error",description:e,variant:"destructive"}),ln=e=>!!e&&Date.now()>=e-3e4,pn=e=>!e||Date.now()>=e-6e5,fn=e=>e?Math.max(0,e-Date.now()):0,hn=e=>{const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return t>0?`${t}m ${n}s`:`${n}s`},gn="light",mn="dark",yn="system",vn="pill",bn="sharp",_n={bgColor:"linear-gradient(281.8deg, #061522 6.7%, #101F2F 59.64%, #3C3B4F 76.85%, #5D4C63 88.46%, #755770 99.24%)",inputBgColor:"#222D34",sidebarBg:"#0F1419",sidebarBorderColor:"#8F8F8F",widgetBg:"#222D34",settingsGroupBg:"#272626",inputBorderStyle:"solid",inputBorderColor:"#FFFFFF80",inputBorderWidth:"1px",inputBorderOpacity:50,widgetBorderStyle:"solid",widgetBorderColor:"#FFFFFF1A",widgetBorderWidth:"1px",widgetBorderOpacity:10,placeholderColor:"#8F8F8F",primaryText:"#FFFFFF",secondaryText:"#AFAFAF",tertiaryText:"#8F8F8F",userMsgBg:"#90629F",userMsgText:"#FFFFFF",userMsgBorderStyle:"none",userMsgBorderColor:"#FFFFFFFF",userMsgBorderWidth:"1px",userMsgBorderOpacity:100,sideMenuHeadings:"#FFFFFF",sideMenuText:"#AFAFAF",sideMenuIcon:"#8F8F8F",sideMenuProfile:"#FFFFFF",statusPrimary:{solid:"#90629F",background:"#90629F",text:"#FFFFFF"},statusSecondary:{solid:"#5D5D5D",background:"#F3F3F3",text:"#0D0D0D"},statusSuccess:{solid:"#00A240",background:"#D9F4E4",text:"#FFFFFF"},statusDanger:{solid:"#E02E2A",background:"#FFD9D9",text:"#FFFFFF"},statusWarning:{solid:"#E25507",background:"#FFE7D9",text:"#FFFFFF"},statusInfo:{solid:"#0285FF",background:"#E5F3FF",text:"#FFFFFF"},statusDiscovery:{solid:"#924FF7",background:"#EFE5FE",text:"#FFFFFF"},switchCheckedColor:"#90629F",switchUncheckedColor:"#222D34",fontFamily:"'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif",fontFamilyMono:'"SF Mono", ui-monospace, monospace',fontSize:14,borderRadius:16,cornerRadiusMode:vn,chatInputPlaceholder:"Type anything..."},Sn={bgColor:"linear-gradient(281.8deg, #EEF2FF 6.7%, #E2E8FD 59.64%, #E8DFF4 76.85%, #F4DBE6 88.46%, #FFE1D0 99.24%)",inputBgColor:"#F4F4F5",sidebarBg:"#FFFFFF",sidebarBorderColor:"#9B9B9B",widgetBg:"#FFFFFF",settingsGroupBg:"#1A1A1A10",inputBorderStyle:"solid",inputBorderColor:"#0000001A",inputBorderWidth:"1px",inputBorderOpacity:10,widgetBorderStyle:"solid",widgetBorderColor:"#0000001A",widgetBorderWidth:"1px",widgetBorderOpacity:10,placeholderColor:"#9B9B9B",primaryText:"#1A1A1A",secondaryText:"#6B6B6B",tertiaryText:"#9B9B9B",userMsgBg:"#90629F",userMsgText:"#FFFFFF",userMsgBorderStyle:"none",userMsgBorderColor:"#000000FF",userMsgBorderWidth:"1px",userMsgBorderOpacity:100,sideMenuHeadings:"#1A1A1A",sideMenuText:"#6B6B6B",sideMenuIcon:"#9B9B9B",sideMenuProfile:"#1A1A1A",statusPrimary:{solid:"#90629F",background:"#90629F",text:"#FFFFFF"},statusSecondary:{solid:"#5D5D5D",background:"#F3F3F3",text:"#0D0D0D"},statusSuccess:{solid:"#00A240",background:"#D9F4E4",text:"#FFFFFF"},statusDanger:{solid:"#E02E2A",background:"#FFD9D9",text:"#FFFFFF"},statusWarning:{solid:"#E25507",background:"#FFE7D9",text:"#FFFFFF"},statusInfo:{solid:"#0285FF",background:"#E5F3FF",text:"#FFFFFF"},statusDiscovery:{solid:"#924FF7",background:"#EFE5FE",text:"#FFFFFF"},switchCheckedColor:"#90629F",switchUncheckedColor:"#F4F4F5",fontFamily:"'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif",fontFamilyMono:'"SF Mono", ui-monospace, monospace',fontSize:14,borderRadius:16,cornerRadiusMode:vn,chatInputPlaceholder:"Type anything..."};function wn(e,t){const n=e.replace("#","");let r;r=3===n.length?n.split("").map(e=>e+e).join(""):6===n.length?n:"000000";const o=Math.max(0,Math.min(100,t));return`#${r}${Math.round(o/100*255).toString(16).padStart(2,"0")}`.toUpperCase()}function Tn(e,t){if(!e)return t.fontFamily;switch(e){case"Inter":return"'Inter', sans-serif";case"System":return"system-ui, -apple-system, sans-serif";default:return"'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif"}}function En(e,t){return e?`"${e}", ui-monospace, monospace`:t.fontFamilyMono}function kn(e,t){if(!e)return t.borderRadius;switch(e){case"none":return 0;case"sm":return 8;case"md":return 12;case"pill":return 16;default:const n=parseInt(e,10);return isNaN(n)?t.borderRadius:n}}function In(e){switch(e){case"pill":return vn;case"none":return bn;default:return 0===parseInt(e??"",10)?bn:"rounded"}}const Fn=A(void 0);function An(){const e=F(Fn);if(!e)throw new Error("useBranding must be used within a BrandingProvider");return e}const xn=A(null),Pn=()=>{const e=F(xn);if(!e)throw new Error("useStorage must be called inside a <StorageProvider>. Wrap your app's root with <StorageProvider value={browserLocalStorageAdapter}> (or an RN equivalent).");return e};let Cn=null;const On=()=>Cn,Rn=A(null),Mn=i({name:"auth",initialState:{user:null,accessToken:null,refreshToken:null,tokenExpiresAt:null,selectedOrgId:null,isAuthenticated:!1,isLoading:!1},reducers:{setSession:(e,t)=>{const{user:n,accessToken:r,refreshToken:o,expiresIn:i}=t.payload;void 0!==n&&(e.user=n),void 0!==r&&(e.accessToken=r),void 0!==o&&(e.refreshToken=o),void 0!==i?e.tokenExpiresAt=null===i?null:1e3*i:r&&(e.tokenExpiresAt=Date.now()+36e5),e.isAuthenticated=Boolean(e.accessToken),e.isLoading=!1},updateUser:(e,t)=>{e.user={...e.user||{},...t.payload}},clearSession:e=>{e.user=null,e.accessToken=null,e.refreshToken=null,e.tokenExpiresAt=null,e.isAuthenticated=!1,e.isLoading=!1},sessionExpired:e=>{e.user=null,e.accessToken=null,e.refreshToken=null,e.tokenExpiresAt=null,e.isAuthenticated=!1,e.isLoading=!1},setSelectedOrgId:(e,t)=>{e.selectedOrgId=t.payload??null}}}),{setSession:Nn,updateUser:Dn,clearSession:qn,sessionExpired:Qn}=Mn.actions,jn=e=>async t=>{const[n,r,o,i]=await Promise.all([e.getItem(Xt),e.getItem(Yt),e.getItem(Zt),e.getItem(en)]),s=o?parseInt(o,10):null;if((!n||!s||ln(s))&&!r)return void(n&&await Promise.all([e.removeItem(Xt),e.removeItem(Yt),e.removeItem(Zt),e.removeItem(en)]));let a=null;if(i)try{a=JSON.parse(i)}catch(e){Ft.error({message:"Failed to parse stored user during session hydration",component:"sessionSlice",error_message:e instanceof Error?e.message:String(e)})}t(Nn({user:a,accessToken:n,refreshToken:r,expiresIn:null!=s?s/1e3:null}))},Bn=b();Bn.startListening({matcher:a(Nn,Dn,qn,Qn),effect:async(e,t)=>{const n=On();if(!n)return;const{auth:r}=t.getState(),o=[];o.push(r.accessToken?n.setItem(Xt,r.accessToken):n.removeItem(Xt)),o.push(r.refreshToken?n.setItem(Yt,r.refreshToken):n.removeItem(Yt)),o.push(null!=r.tokenExpiresAt?n.setItem(Zt,String(r.tokenExpiresAt)):n.removeItem(Zt)),o.push(r.user?n.setItem(en,JSON.stringify(r.user)):n.removeItem(en)),(qn.match(e)||Qn.match(e))&&o.push(n.removeItem("1interface_cached_location"),n.removeItem(rn),n.removeItem(tn),n.removeItem(nn),n.removeItem(on),n.removeItem(sn),n.removeItem(an),n.removeItem("1interface_active_conversation_id")),await Promise.all(o)}});const zn=Mn.reducer,$n={lastResponseTime:null},Un=i({name:"indicator",initialState:$n,reducers:{setLastResponseTime(e,t){e.lastResponseTime=t.payload},clearLastResponseTime(e){e.lastResponseTime=null}},extraReducers:e=>{e.addMatcher(a(qn,Qn),()=>$n)}}),Ln=Un.reducer,Kn="text/event-stream",Wn="last-event-id";function Vn(e,t){var{signal:n,headers:r,onopen:o,onmessage:i,onclose:s,onerror:a,openWhenHidden:c,fetch:u}=t,d=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((t,l)=>{const p=Object.assign({},r);let f;function h(){f.abort(),document.hidden||_()}p.accept||(p.accept=Kn),c||document.addEventListener("visibilitychange",h);let g=1e3,m=0;function y(){document.removeEventListener("visibilitychange",h),window.clearTimeout(m),f.abort()}null==n||n.addEventListener("abort",()=>{y(),t()});const v=null!=u?u:window.fetch,b=null!=o?o:Hn;async function _(){var n;f=new AbortController;try{const n=await v(e,Object.assign(Object.assign({},d),{headers:p,signal:f.signal}));await b(n),await async function(e,t){const n=e.getReader();let r;for(;!(r=await n.read()).done;)t(r.value)}(n.body,function(e){let t,n,r,o=!1;return function(i){void 0===t?(t=i,n=0,r=-1):t=function(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}(t,i);const s=t.length;let a=0;for(;n<s;){o&&(10===t[n]&&(a=++n),o=!1);let i=-1;for(;n<s&&-1===i;++n)switch(t[n]){case 58:-1===r&&(r=n-a);break;case 13:o=!0;case 10:i=n}if(-1===i)break;e(t.subarray(a,i),r),a=n,r=-1}a===s?t=void 0:0!==a&&(t=t.subarray(a),n-=a)}}(function(e,t,n){let r={data:"",event:"",id:"",retry:void 0};const o=new TextDecoder;return function(e,t){if(0===e.length)null==n||n(r),r={data:"",event:"",id:"",retry:void 0};else if(t>0){const n=o.decode(e.subarray(0,t)),s=o.decode(e.subarray(t+(32===e[t+1]?2:1)));switch(n){case"data":r.data=r.data?r.data+"\n"+s:s;break;case"event":r.event=s;break;case"id":(i=r.id=s)?p[Wn]=i:delete p[Wn];break;case"retry":const e=parseInt(s,10);isNaN(e)||(e=>{g=e})(r.retry=e)}}var i}}(0,0,i))),null==s||s(),y(),t()}catch(e){if(!f.signal.aborted)try{const t=null!==(n=null==a?void 0:a(e))&&void 0!==n?n:g;window.clearTimeout(m),m=window.setTimeout(_,t)}catch(e){y(),l(e)}}}_()})}function Hn(e){const t=e.headers.get("content-type");if(!(null==t?void 0:t.startsWith(Kn)))throw new Error(`Expected content-type to be ${Kn}, Actual: ${t}`)}var Gn=Symbol.for("immer-nothing"),Jn=Symbol.for("immer-draftable"),Xn=Symbol.for("immer-state"),Yn="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 Zn(e,...t){if("production"!==process.env.NODE_ENV){const n=Yn[e],r=wr(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 er=Object,tr=er.getPrototypeOf,nr="constructor",rr="prototype",or="configurable",ir="enumerable",sr="writable",ar="value",cr=e=>!!e&&!!e[Xn];function ur(e){return!!e&&(pr(e)||vr(e)||!!e[Jn]||!!e[nr]?.[Jn]||br(e)||_r(e))}var dr=er[rr][nr].toString(),lr=new WeakMap;function pr(e){if(!e||!Sr(e))return!1;const t=tr(e);if(null===t||t===er[rr])return!0;const n=er.hasOwnProperty.call(t,nr)&&t[nr];if(n===Object)return!0;if(!wr(n))return!1;let r=lr.get(n);return void 0===r&&(r=Function.toString.call(n),lr.set(n,r)),r===dr}function fr(e,t,n=!0){0===hr(e)?(n?Reflect.ownKeys(e):er.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function hr(e){const t=e[Xn];return t?t.type_:vr(e)?1:br(e)?2:_r(e)?3:0}var gr=(e,t,n=hr(e))=>2===n?e.has(t):er[rr].hasOwnProperty.call(e,t),mr=(e,t,n=hr(e))=>2===n?e.get(t):e[t],yr=(e,t,n,r=hr(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n},vr=Array.isArray,br=e=>e instanceof Map,_r=e=>e instanceof Set,Sr=e=>"object"==typeof e,wr=e=>"function"==typeof e,Tr=e=>"boolean"==typeof e,Er=e=>e.copy_||e.base_,kr=e=>e.modified_?e.copy_:e.base_;function Ir(e,t){if(br(e))return new Map(e);if(_r(e))return new Set(e);if(vr(e))return Array[rr].slice.call(e);const n=pr(e);if(!0===t||"class_only"===t&&!n){const t=er.getOwnPropertyDescriptors(e);delete t[Xn];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const o=n[r],i=t[o];!1===i[sr]&&(i[sr]=!0,i[or]=!0),(i.get||i.set)&&(t[o]={[or]:!0,[sr]:!0,[ir]:i[ir],[ar]:e[o]})}return er.create(tr(e),t)}{const t=tr(e);if(null!==t&&n)return{...e};const r=er.create(t);return er.assign(r,e)}}function Fr(e,t=!1){return xr(e)||cr(e)||!ur(e)||(hr(e)>1&&er.defineProperties(e,{set:Ar,add:Ar,clear:Ar,delete:Ar}),er.freeze(e),t&&fr(e,(e,t)=>{Fr(t,!0)},!1)),e}var Ar={[ar]:function(){Zn(2)}};function xr(e){return null===e||!Sr(e)||er.isFrozen(e)}var Pr="MapSet",Cr="Patches",Or="ArrayMethods",Rr={};function Mr(e){const t=Rr[e];return t||Zn(0,e),t}var Nr,Dr=e=>!!Rr[e],qr=()=>Nr;function Qr(e,t){t&&(e.patchPlugin_=Mr(Cr),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function jr(e){Br(e),e.drafts_.forEach($r),e.drafts_=null}function Br(e){e===Nr&&(Nr=e.parent_)}var zr=e=>Nr={drafts_:[],parent_:Nr,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:Dr(Pr)?Mr(Pr):void 0,arrayMethodsPlugin_:Dr(Or)?Mr(Or):void 0};function $r(e){const t=e[Xn];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function Ur(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[Xn].modified_&&(jr(t),Zn(4)),ur(e)&&(e=Lr(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[Xn].base_,e,t)}else e=Lr(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Fr(t,n)}(t,e,!0),jr(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Gn?e:void 0}function Lr(e,t){if(xr(t))return t;const n=t[Xn];if(!n)return Jr(t,e.handledSet_,e);if(!Wr(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);Gr(n,e)}return n.copy_}function Kr(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var Wr=(e,t)=>e.scope_===t,Vr=[];function Hr(e,t,n,r){const o=Er(e),i=e.type_;if(void 0!==r&&mr(o,r,i)===t)return void yr(o,r,n,i);if(!e.draftLocations_){const t=e.draftLocations_=new Map;fr(o,(e,n)=>{if(cr(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const s=e.draftLocations_.get(t)??Vr;for(const e of s)yr(o,e,n,i)}function Gr(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)}Kr(e)}}function Jr(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||cr(e)||t.has(e)||!ur(e)||xr(e)||(t.add(e),fr(e,(r,o)=>{if(cr(o)){const t=o[Xn];if(Wr(t,n)){const n=kr(t);yr(e,r,n,e.type_),Kr(t)}}else ur(o)&&Jr(o,t,n)})),e}var Xr={get(e,t){if(t===Xn)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 o=Er(e);if(!gr(o,t,e.type_))return function(e,t,n){const r=eo(t,n);return r?ar in r?r[ar]:r.get?.call(e.draft_):void 0}(e,o,t);const i=o[t];if(e.finalized_||!ur(i))return i;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return i;if(i===Zr(e.base_,t)){no(e);const n=1===e.type_?+t:t,r=ro(0,i,e,n);return e.copy_[n]=r}return i},has:(e,t)=>t in Er(e),ownKeys:e=>Reflect.ownKeys(Er(e)),set(e,t,n){const r=eo(Er(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=Zr(Er(e),t),s=r?.[Xn];if(s&&s.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((o=n)===(i=r)?0!==o||1/o==1/i:o!=o&&i!=i)&&(void 0!==n||gr(e.base_,t,e.type_)))return!0;no(e),to(e)}var o,i;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(cr(n)){const o=n[Xn];Wr(o,r)&&o.callbacks_.push(function(){no(e);const r=kr(o);Hr(e,n,r,t)})}else ur(n)&&e.callbacks_.push(function(){const o=Er(e);3===e.type_?o.has(n)&&Jr(n,r.handledSet_,r):mr(o,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&Jr(mr(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(no(e),void 0!==Zr(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),to(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Er(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[sr]:!0,[or]:1!==e.type_||"length"!==t,[ir]:r[ir],[ar]:n[t]}:r},defineProperty(){Zn(11)},getPrototypeOf:e=>tr(e.base_),setPrototypeOf(){Zn(12)}},Yr={};for(let e in Xr){let t=Xr[e];Yr[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function Zr(e,t){const n=e[Xn];return(n?Er(n):e)[t]}function eo(e,t){if(!(t in e))return;let n=tr(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=tr(n)}}function to(e){e.modified_||(e.modified_=!0,e.parent_&&to(e.parent_))}function no(e){e.copy_||(e.assigned_=new Map,e.copy_=Ir(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function ro(e,t,n,r){const[o,i]=br(t)?Mr(Pr).proxyMap_(t,n):_r(t)?Mr(Pr).proxySet_(t,n):function(e,t){const n=vr(e),r={type_:n?1:0,scope_:t?t.scope_:qr(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let o=r,i=Xr;n&&(o=[r],i=Yr);const{revoke:s,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=s,[a,r]}(t,n);return(n?.scope_??qr()).drafts_.push(o),i.callbacks_=n?.callbacks_??[],i.key_=r,n&&void 0!==r?(a=i,c=r,(s=n).callbacks_.push(function(e){const t=a;if(!t||!Wr(t,e))return;e.mapSetPlugin_?.fixSetContents(t);const n=kr(t);Hr(s,t.draft_??t,n,c),Gr(t,e)})):i.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(i);const{patchPlugin_:t}=e;i.modified_&&t&&t.generatePatches_(i,[],e)}),o;var s,a,c}function oo(e){return cr(e)||Zn(10,e),io(e)}function io(e){if(!ur(e)||xr(e))return e;const t=e[Xn];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Ir(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=Ir(e,!0);return fr(n,(e,t)=>{yr(n,e,io(t))},r),t&&(t.finalized_=!1),n}Yr.deleteProperty=function(e,t){return"production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&Zn(13),Yr.set.call(this,e,t,void 0)},Yr.set=function(e,t,n){return"production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&Zn(14),Xr.set.call(this,e[0],t,n,e[0])};var so=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(wr(e)&&!wr(t)){const n=t;t=e;const r=this;return function(e=n,...o){return r.produce(e,e=>t.call(this,e,...o))}}let r;if(wr(t)||Zn(6),void 0===n||wr(n)||Zn(7),ur(e)){const o=zr(this),i=ro(0,e,void 0);let s=!0;try{r=t(i),s=!1}finally{s?jr(o):Br(o)}return Qr(o,n),Ur(r,o)}if(!e||!Sr(e)){if(r=t(e),void 0===r&&(r=e),r===Gn&&(r=void 0),this.autoFreeze_&&Fr(r,!0),n){const t=[],o=[];Mr(Cr).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:o}),n(t,o)}return r}Zn(1,e)},this.produceWithPatches=(e,t)=>{if(wr(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]},Tr(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),Tr(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),Tr(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){ur(e)||Zn(8),cr(e)&&(e=oo(e));const t=zr(this),n=ro(0,e,void 0);return n[Xn].isManual_=!0,Br(t),n}finishDraft(e,t){const n=e&&e[Xn];n&&n.isManual_||Zn(9);const{scope_:r}=n;return Qr(r,t),Ur(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=Mr(Cr).applyPatches_;return cr(e)?r(e,t):this.produce(e,e=>r(e,t))}},ao=so.produceWithPatches.bind(so),co=so.applyPatches.bind(so),uo=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}},lo=(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})}}},po=(e,t,n)=>{const{memoize:r,memoizeOptions:o}=t,{inputSelectorResults:i,inputSelectorResultsCopy:s}=e,a=r(()=>({}),...o);if(a.apply(null,i)!==a.apply(null,s)){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:i,secondInputs:s,stack:e})}},fo={inputStabilityCheck:"once",identityFunctionCheck:"once"},ho=e=>Array.isArray(e)?e:[e];function go(e,t){const n=[],{length:r}=e;for(let o=0;o<r;o++)n.push(e[o].apply(null,t));return n}var mo="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function yo(){return{s:0,v:void 0,o:null,p:null}}function vo(e,t={}){let n={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:r}=t;let o,i=0;function s(){let t=n;const{length:s}=arguments;for(let e=0,n=s;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=yo(),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=yo(),e.set(n,t)):t=r}}const a=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),i++,r){const e=o?.deref?.()??o;null!=e&&r(e,c)&&(c=e,0!==i&&i--),o="object"==typeof c&&null!==c||"function"==typeof c?new mo(c):c}return a.s=1,a.v=c,c}return s.clearCache=()=>{n={s:0,v:void 0,o:null,p:null},s.resetResultsCount()},s.resultsCount=()=>i,s.resetResultsCount=()=>{i=0},s}var bo,_o=function(){const e="function"==typeof vo?{memoize:vo,memoizeOptions:[]}:vo,t=(...t)=>{let n,r=0,o=0,i={},s=t.pop();"object"==typeof s&&(i=s,s=t.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(s,`createSelector expects an output function after the inputs, but received: [${typeof s}]`);const a={...e,...i},{memoize:c,memoizeOptions:u=[],argsMemoize:d=vo,argsMemoizeOptions:l=[],devModeChecks:p={}}=a,f=ho(u),h=ho(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}(t),m=c(function(){return r++,s.apply(null,arguments)},...f);let y=!0;const v=d(function(){o++;const e=go(g,arguments);if(n=m.apply(null,e),"production"!==process.env.NODE_ENV){const{identityFunctionCheck:t,inputStabilityCheck:r}=((e,t)=>{const{identityFunctionCheck:n,inputStabilityCheck:r}={...fo,...t};return{identityFunctionCheck:{shouldRun:"always"===n||"once"===n&&e,run:lo},inputStabilityCheck:{shouldRun:"always"===r||"once"===r&&e,run:po}}})(y,p);if(t.shouldRun&&t.run(s,e,n),r.shouldRun){const t=go(g,arguments);r.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:f},arguments)}y&&(y=!1)}return n},...h);return Object.assign(v,{resultFunc:s,memoizedResultFunc:m,dependencies:g,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>n,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(t,{withTypes:()=>t}),t}(),So=Object.assign((e,t=_o)=>{!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:()=>So}),wo=((bo=wo||{}).uninitialized="uninitialized",bo.pending="pending",bo.fulfilled="fulfilled",bo.rejected="rejected",bo),To="uninitialized",Eo="pending",ko="fulfilled",Io="rejected";function Fo(e){return{status:e,isUninitialized:e===To,isLoading:e===Eo,isSuccess:e===ko,isError:e===Io}}var Ao=l;function xo(e,t){if(e===t||!(Ao(e)&&Ao(t)||Array.isArray(e)&&Array.isArray(t)))return t;const n=Object.keys(t),r=Object.keys(e);let o=n.length===r.length;const i=Array.isArray(t)?[]:{};for(const r of n)i[r]=xo(e[r],t[r]),o&&(o=e[r]===i[r]);return o?e:i}function Po(e,t,n){return e.reduce((e,r,o)=>(t(r,o)&&e.push(n(r,o)),e),[]).flat()}function Co(e){return null!=e}function Oo(e){return[...e?.values()??[]].filter(Co)}function Ro(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var Mo=()=>new Map,No=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},Do=(...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},qo=(...e)=>fetch(...e),Qo=e=>e.status>=200&&e.status<=299,jo=e=>/ion\/(vnd\.api\+)?json/.test(e.get("content-type")||"");function Bo(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 zo=class{constructor(e,t=void 0){this.value=e,this.meta=t}},$o="__rtkq/",Uo="online",Lo="offline",Ko="focus",Wo="focused",Vo="visibilitychange",Ho=e(`${$o}${Wo}`),Go=e(`${$o}un${Wo}`),Jo=e(`${$o}${Uo}`),Xo=e(`${$o}${Lo}`),Yo=!1,Zo="query",ei="mutation",ti="infinitequery";function ni(e){return e.type===Zo}function ri(e){return e.type===ti}function oi(e){return ni(e)||ri(e)}function ii(e,t,n,r,o,i){const s="function"==typeof e?e(t,n,r,o):e;return s?Po(s,Co,e=>i(si(e))):[]}function si(e){return"string"==typeof e?{type:e}:e}var ai=(e,t)=>e.endpointDefinitions[t],ci=Symbol("forceQueryFn"),ui=e=>"function"==typeof e[ci],di=class extends uo{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}},li=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function pi(e,t,n,r){const o=await e["~standard"].validate(t);if(o.issues)throw new di(o.issues,t,n,r);return o.value}function fi(e){return e}var hi=(e={})=>({...e,[p]:!0});function gi(e,{pages:t,pageParams:n},r){const o=t.length-1;return e.getNextPageParam(t[o],t,n[o],n,r)}function mi(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function yi(e,t,n,r){return ii(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 vi(e){return cr(e)?oo(e):e}function bi(e,t,n){const r=e[t];r&&n(r)}function _i(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function Si(e,t,n){const r=e[_i(t)];r&&n(r)}var wi={},Ti=Symbol.for("RTKQ/skipToken"),Ei={status:To},ki=y(Ei,()=>{}),Ii=y(Ei,()=>{}),Fi=WeakMap?new WeakMap:void 0,Ai=({endpointName:e,queryArgs:t})=>{let n="";const r=Fi?.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)&&Fi?.set(t,e),n=e}return`${e}(${n})`};function xi(e,...t){return Object.assign(e,...t)}var Pi=({api:e,queryThunk:t,context:n,internalState:r,selectors:{selectQueryEntry:o,selectConfig:i},getRunningQueryThunk:s})=>{const{removeQueryResult:c,unsubscribeQueryResult:u,cacheEntriesUpserted:d}=e.internalActions,l=a(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 i of e){const e=o(r,i);e?.endpointName&&m(i,e.endpointName,t,n)}}function m(e,t,r,i){const a=ai(n,t),u=a?.keepUnusedDataFor??i.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=o(r.getState(),e);if(t?.endpointName){const e=r.dispatch(s(t.endpointName,t.originalArgs));e?.abort()}r.dispatch(c({queryCacheKey:e}))}delete f[e]},1e3*d)}}return(t,o)=>{const s=o.getState(),a=i(s);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,o,a)}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),o,a)}}},Ci=new Error("Promise never resolved before cacheEntryRemoved."),Oi=({api:e,reducerPath:t,context:n,queryThunk:r,mutationThunk:o,selectors:{selectQueryEntry:i}})=>{const s=v(r),a=v(o),u=c(r,o),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:o}=t;return[r,o,n]}function y(t,r,o,i,s){const a=ai(n,t),c=a?.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 Ci})]);p.catch(()=>{}),d[o]=u;const f=e.endpoints[t].select(oi(a)?r:o),h=i.dispatch((e,t,n)=>n),g={...i,getCacheEntry:()=>f(i.getState()),requestId:s,extra:h,updateCachedData:oi(a)?n=>i.dispatch(e.util.updateQueryData(t,r,n)):void 0,cacheDataLoaded:p,cacheEntryRemoved:l},m=c(r,g);Promise.resolve(m).catch(e=>{if(e!==Ci)throw e})}return(n,c,v)=>{const b=s(_=n)?_.meta.arg.queryCacheKey:a(_)?_.meta.arg.fixedCacheKey??_.meta.requestId:l.match(_)?_.payload.queryCacheKey:p.match(_)?_i(_.payload):"";var _;function S(e,t,n,r){const o=i(v,t),s=i(c.getState(),t);!o&&s&&y(e,r,t,c,n)}if(r.pending.match(n)){const[e,t,r]=m(n);S(e,b,r,t)}else if(f.match(n))for(const{queryDescription:e,value:t}of n.payload){const{endpointName:r,originalArgs:o,queryCacheKey:i}=e;S(r,i,n.meta.requestId,o),h(i,t,{})}else if(o.pending.match(n)){if(c.getState()[t].mutations[b]){const[e,t,r]=m(n);y(e,t,b,c,r)}}else if(u(n))h(b,n.payload,n.meta.baseQueryMeta);else if(l.match(n)||p.match(n))g(b);else if(e.util.resetApiState.match(n))for(const e of Object.keys(d))g(e)}},Ri=({api:e,context:{apiUid:t},reducerPath:n})=>(r,o)=>{e.util.resetApiState.match(r)&&o.dispatch(e.internalActions.middlewareRegistered(t)),"undefined"!=typeof process&&"development"===process.env.NODE_ENV&&e.internalActions.middlewareRegistered.match(r)&&r.payload===t&&"conflict"===o.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!":""}`)},Mi=({reducerPath:e,context:t,context:{endpointDefinitions:n},mutationThunk:r,queryThunk:o,api:i,assertTagType:s,refetchQuery:d,internalState:l})=>{const{removeQueryResult:p}=i.internalActions,f=a(c(r),u(r)),g=a(c(o,r),h(o,r));let m=[],y=0;function v(n,r){const o=r.getState(),s=o[e];if(m.push(...n),"delayed"===s.config.invalidationBehavior&&y>0)return;const a=m;if(m=[],0===a.length)return;const c=i.util.selectInvalidatedBy(o,a);t.batch(()=>{const e=Array.from(c.values());for(const{queryCacheKey:t}of e){const e=s.queries[t],n=Ro(l.currentSubscriptions,t,Mo);e&&(0===n.size?r.dispatch(p({queryCacheKey:t})):e.status!==To&&r.dispatch(d(e)))}})}return(e,t)=>{(o.pending.match(e)||r.pending.match(e))&&y++,g(e)&&(y=Math.max(0,y-1)),f(e)?v(yi(e,"invalidatesTags",n,s),t):g(e)?v([],t):i.util.invalidateTags.match(e)&&v(ii(e.payload,void 0,void 0,void 0,void 0,s),t)}},Ni=({reducerPath:e,queryThunk:t,api:n,refetchQuery:r,internalState:o})=>{const{currentPolls:i,currentSubscriptions:s}=o,a=new Set;let c=null;function u(e,t){a.add(e),c||(c=setTimeout(()=>{for(const e of a)l({queryCacheKey:e},t);a.clear(),c=null},0))}function d({queryCacheKey:t},n){const o=n.getState()[e],a=o.queries[t],c=s.get(t);if(!a||a.status===To)return;const{lowestPollingInterval:u,skipPollingIfUnfocused:l}=f(c);if(!Number.isFinite(u))return;const p=i.get(t);p?.timeout&&(clearTimeout(p.timeout),p.timeout=void 0);const h=Date.now()+u;i.set(t,{nextPollTimestamp:h,pollingInterval:u,timeout:setTimeout(()=>{!o.config.focused&&l||n.dispatch(r(a)),d({queryCacheKey:t},n)},u)})}function l({queryCacheKey:t},n){const r=n.getState()[e].queries[t],o=s.get(t);if(!r||r.status===To)return;const{lowestPollingInterval:a}=f(o);if("test"===process.env.NODE_ENV){const e=i.pollUpdateCounters??={};e[t]??=0,e[t]++}if(!Number.isFinite(a))return void p(t);const c=i.get(t),u=Date.now()+a;(!c||u<c.nextPollTimestamp)&&d({queryCacheKey:t},n)}function p(e){const t=i.get(e);t?.timeout&&clearTimeout(t.timeout),i.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 i.keys())p(e)}(),c&&(clearTimeout(c),c=null),a.clear())}},Di=({api:e,context:t,queryThunk:n,mutationThunk:r})=>{const o=g(n,r),i=h(n,r),s=c(n,r),a={};return(n,r)=>{if(o(n)){const{requestId:o,arg:{endpointName:i,originalArgs:s}}=n.meta,c=ai(t,i),u=c?.onQueryStarted;if(u){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),a[o]=t;const d=e.endpoints[i].select(oi(c)?s:o),l=r.dispatch((e,t,n)=>n),p={...r,getCacheEntry:()=>d(r.getState()),requestId:o,extra:l,updateCachedData:oi(c)?t=>r.dispatch(e.util.updateQueryData(i,s,t)):void 0,queryFulfilled:n};u(s,p)}}else if(s(n)){const{requestId:e,baseQueryMeta:t}=n.meta;a[e]?.resolve({data:n.payload,meta:t}),delete a[e]}else if(i(n)){const{requestId:e,rejectedWithValue:t,baseQueryMeta:r}=n.meta;a[e]?.reject({error:n.payload??n.error,isUnhandledError:!t,meta:r}),delete a[e]}}},qi=Symbol(),Qi=({createSelector:l=r}={})=>({name:qi,init(r,{baseQuery:v,tagTypes:b,reducerPath:_,serializeQueryArgs:S,keepUnusedDataFor:w,refetchOnMountOrArgChange:T,refetchOnFocus:E,refetchOnReconnect:k,invalidationBehavior:I,onSchemaFailure:F,catchSchemaFailure:A,skipSchemaValidation:x},P){!function(){"production"!==process.env.NODE_ENV&&Yn.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(!ur(e))return e;if(vr(e))return e.map(r);if(br(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(_r(e))return new Set(Array.from(e).map(r));const t=Object.create(tr(e));for(const n in e)t[n]=r(e[n]);return gr(e,Jn)&&(t[Jn]=e[Jn]),t}function o(e){return cr(e)?r(e):e}var i;Rr[i=Cr]||(Rr[i]={applyPatches_:function(o,i){return i.forEach(i=>{const{path:s,op:a}=i;let c=o;for(let e=0;e<s.length-1;e++){const t=hr(c);let n=s[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==nr||Zn(19),wr(c)&&n===rr&&Zn(19),c=mr(c,n),Sr(c)||Zn(18,s.join("/"))}const u=hr(c),d=r(i.value),l=s[s.length-1];switch(a){case e:switch(u){case 2:return c.set(l,d);case 3:Zn(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(i.value);default:return delete c[l]}default:Zn(17,a)}}),o},generatePatches_:function(r,i,s){if(r.scope_.processedForPatches_.has(r))return;r.scope_.processedForPatches_.add(r);const{patches_:a,inversePatches_:c}=s;switch(r.type_){case 0:case 2:return function(r,i,s,a){const{base_:c,copy_:u,type_:d}=r;fr(r.assigned_,(r,l)=>{const p=mr(c,r,d),f=mr(u,r,d),h=l?gr(c,r)?e:t:n;if(p===f&&h===e)return;const g=i.concat(r);s.push(h===n?{op:h,path:g}:{op:h,path:g,value:o(f)}),a.push(h===t?{op:n,path:g}:h===n?{op:t,path:g,value:o(p)}:{op:e,path:g,value:o(p)})})}(r,i,a,c);case 1:return function(r,i,s,a){let{base_:c,assigned_:u}=r,d=r.copy_;d.length<c.length&&([c,d]=[d,c],[s,a]=[a,s]);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?.[Xn];if(c&&c.modified_)continue;const u=i.concat([t]);s.push({op:e,path:u,value:o(n)}),a.push({op:e,path:u,value:o(r)})}}for(let e=c.length;e<d.length;e++){const n=i.concat([e]);s.push({op:t,path:n,value:o(d[e])})}for(let e=d.length-1;c.length<=e;--e){const t=i.concat([e]);a.push({op:n,path:t})}}(r,i,a,c);case 3:return function(e,r,o,i){let{base_:s,copy_:a}=e,c=0;s.forEach(e=>{if(!a.has(e)){const s=r.concat([c]);o.push({op:n,path:s,value:e}),i.unshift({op:t,path:s,value:e})}c++}),c=0,a.forEach(e=>{if(!s.has(e)){const s=r.concat([c]);o.push({op:t,path:s,value:e}),i.unshift({op:n,path:s,value:e})}c++})}(r,i,a,c)}},generateReplacementPatches_:function(t,n,r){const{patches_:o,inversePatches_:i}=r;o.push({op:e,path:[],value:n===Gn?void 0:n}),i.push({op:e,path:[],value:t})},getPath:function e(t,n=[]){if(void 0!==t.key_){const e=t.parent_.copy_??t.parent_.base_,o=(r=mr(e,t.key_),Sr(r)?r?.[Xn]:null),i=mr(e,t.key_);if(void 0===i)return null;if(i!==t.draft_&&i!==t.base_&&i!==t.copy_)return null;if(null!=o&&o.base_!==t.base_)return null;const s=3===t.parent_.type_;let a;if(a=s?Array.from(t.parent_.drafts_.keys()).indexOf(t.key_):t.key_,!(s&&e.size>a||gr(e,a)))return null;n.push(a)}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=mr(n,t[e]),!Sr(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}(t.copy_,n)}catch(e){return null}return n}})}();const C=e=>("undefined"!=typeof process&&"development"===process.env.NODE_ENV&&(b.includes(e.type)||console.error(`Tag type '${e.type}' was used, but not specified in \`tagTypes\`!`)),e);Object.assign(r,{reducerPath:_,endpoints:{},internalActions:{onOnline:Jo,onOffline:Xo,onFocus:Ho,onFocusLost:Go},util:{}});const O=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>ki,o=e=>Ii;return{buildQuerySelector:function(e,t){return u(e,t,i)},buildInfiniteQuerySelector:function(e,t){const{infiniteQueryOptions:n}=t;return u(e,t,function(e){const t={...e,...Fo(e.status)},{isLoading:r,isError:o,direction:i}=t,s="forward"===i,a="backward"===i;return{...t,hasNextPage:(c=n,u=t.data,l=t.originalArgs,!!u&&null!=gi(c,u,l)),hasPreviousPage:d(n,t.data,t.originalArgs),isFetchingNextPage:r&&s,isFetchingPreviousPage:r&&a,isFetchNextPageError:o&&s,isFetchPreviousPageError:o&&a};var c,u,l})},buildMutationSelector:function(){return e=>{let t;return t="object"==typeof e?_i(e)??Ti:e,n(t===Ti?o:e=>s(e)?.mutations?.[t]??Ii,i)}},selectInvalidatedBy:function(e,n){const r=e[t],o=new Set,i=Po(n,Co,si);for(const e of i){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)o.add(e)}return Array.from(o.values()).flatMap(e=>{const t=r.queries[e];return t?{queryCacheKey:e,endpointName:t.endpointName,originalArgs:t.originalArgs}:[]})},selectCachedArgsForQuery:function(e,t){return Po(Object.values(a(e)),e=>e?.endpointName===t&&e.status!==To,e=>e.originalArgs)},selectApiState:s,selectQueries:a,selectMutations:function(e){return s(e)?.mutations},selectQueryEntry:c,selectConfig:function(e){return s(e)?.config}};function i(e){return{...e,...Fo(e.status)}}function s(e){const n=e[t];if("production"!==process.env.NODE_ENV&&!n){if(s.triggered)return n;s.triggered=!0,console.error(`Error: No data found at \`state.${t}\`. Did you forget to add the reducer to the store?`)}return n}function a(e){return s(e)?.queries}function c(e,t){return a(e)?.[t]}function u(t,o,i){return s=>{if(s===Ti)return n(r,i);const a=e({queryArgs:s,endpointDefinition:o,endpointName:t});return n(e=>c(e,a)??ki,i)}}function d(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=mi(e,t,n)}}({serializeQueryArgs:S,reducerPath:_,createSelector:l}),{selectInvalidatedBy:R,selectCachedArgsForQuery:M,buildQuerySelector:N,buildInfiniteQuerySelector:D,buildMutationSelector:q}=O;xi(r.util,{selectInvalidatedBy:R,selectCachedArgsForQuery:M});const{queryThunk:Q,infiniteQueryThunk:j,mutationThunk:B,patchQueryData:z,updateQueryData:$,upsertQueryData:U,prefetch:L,buildMatchThunkActions:K}=function({reducerPath:e,baseQuery:t,context:{endpointDefinitions:n},serializeQueryArgs:r,api:i,assertTagType:s,selectors:a,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]:fi,v=async(e,{signal:r,abort:o,rejectWithValue:i,fulfillWithValue:s,dispatch:c,getState:f,extra:h})=>{const g=n[e.endpointName],{metaSchema:v,skipSchemaValidation:_=l}=g,S=e.type===Zo;try{let w=fi;const T={signal:r,abort:o,dispatch:c,getState:f,extra:h,endpoint:e.endpointName,type:e.type,forced:S?b(e,f()):void 0,queryCacheKey:S?e.queryCacheKey:void 0},E=S?e[ci]:void 0;let k;const I=async(t,n,r,o)=>{if(null==n&&t.pages.length)return Promise.resolve({data:t});const i={queryArg:e.originalArgs,pageParam:n},s=await F(i),a=o?p:m;return{data:{pages:a(t.pages,s.data,r),pageParams:a(t.pageParams,n,r)},meta:s.meta}};async function F(n){let r;const{extraOptions:o,argSchema:i,rawResponseSchema:s,responseSchema:a}=g;if(i&&!li(_,"arg")&&(n=await pi(i,n,"argSchema",{})),E?r=E():g.query?(w=y(g,"transformResponse"),r=await t(g.query(n),T,o)):r=await g.queryFn(n,T,o,e=>t(e,T,o)),"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 zo(r.error,r.meta);let{data:c}=r;s&&!li(_,"rawResponse")&&(c=await pi(s,r.data,"rawResponseSchema",r.meta));let u=await w(c,r.meta,n);return a&&!li(_,"response")&&(u=await pi(a,u,"responseSchema",r.meta)),{...r,data:u}}if(S&&"infiniteQueryOptions"in g){const{infiniteQueryOptions:A}=g,{maxPages:x=1/0}=A,P=e.refetchCachedPages??A.refetchCachedPages??!0;let C;const O={pages:[],pageParams:[]},R=a.selectQueryEntry(f(),e.queryCacheKey)?.data,M=b(e,f())&&!e.direction||!R?O:R;if("direction"in e&&e.direction&&M.pages.length){const N="backward"===e.direction,D=(N?mi:gi)(A,M,e.originalArgs);C=await I(M,D,x,N)}else{const{initialPageParam:q=A.initialPageParam}=e,Q=R?.pageParams??[],j=Q[0]??q,B=Q.length;if(C=await I(M,j,x),E&&(C={data:C.data.pages[0]}),P)for(let z=1;z<B;z++){const $=gi(A,C.data,e.originalArgs);C=await I(C.data,$,x)}}k=C}else k=await F(e.originalArgs);return v&&!li(_,"meta")&&k.meta&&(k.meta=await pi(v,k.meta,"metaSchema",k.meta)),s(k.data,hi({fulfilledTimeStamp:Date.now(),baseQueryMeta:k.meta}))}catch(U){let L=U;if(L instanceof zo){let K=y(g,"transformErrorResponse");const{rawErrorResponseSchema:W,errorResponseSchema:V}=g;let{value:H,meta:G}=L;try{W&&!li(_,"rawErrorResponse")&&(H=await pi(W,H,"rawErrorResponseSchema",G)),v&&!li(_,"meta")&&(G=await pi(v,G,"metaSchema",G));let J=await K(H,G,e.originalArgs);return V&&!li(_,"errorResponse")&&(J=await pi(V,J,"errorResponseSchema",G)),i(J,hi({baseQueryMeta:G}))}catch(X){L=X}}try{if(L instanceof di){const Y={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:S?e.queryCacheKey:void 0};g.onSchemaFailure?.(L,Y),u?.(L,Y);const{catchSchemaFailure:Z=d}=g;if(Z)return i(Z(L,Y),hi({baseQueryMeta:L._bqMeta}))}}catch(ee){L=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".`,L):console.error(L),L}};function b(e,t){const n=a.selectQueryEntry(t,e.queryCacheKey),r=a.selectConfig(t).refetchOnMountOrArgChange,o=n?.fulfilledTimeStamp,i=e.forceRefetch??(e.subscribe&&r);return!!i&&(!0===i||(Number(new Date)-Number(o))/1e3>=i)}const _=()=>o(`${e}/executeQuery`,v,{getPendingMeta({arg:e}){const t=n[e.endpointName];return hi({startedTimeStamp:Date.now(),...ri(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const r=t(),o=a.selectQueryEntry(r,e.queryCacheKey),i=o?.fulfilledTimeStamp,s=e.originalArgs,c=o?.originalArgs,u=n[e.endpointName],d=e.direction;return!(!ui(e)&&("pending"===o?.status||!b(e,r)&&(!ni(u)||!u?.forceRefetch?.({currentArg:s,previousArg:c,endpointState:o,state:r}))&&i&&!d))},dispatchConditionRejection:!0}),S=_(),w=_();function T(e){return t=>t?.meta?.arg?.endpointName===e}return{queryThunk:S,mutationThunk:o(`${e}/executeMutation`,v,{getPendingMeta:()=>hi({startedTimeStamp:Date.now()})}),infiniteQueryThunk:w,prefetch:(e,t,n={})=>(r,o)=>{const s="force"in n&&n.force,a="ifOlderThan"in n&&n.ifOlderThan,c=(n=!0)=>i.endpoints[e].initiate(t,{forceRefetch:n,subscribe:!1}),u=i.endpoints[e].select(t)(o());if(s)r(c());else if(a){const e=u?.fulfilledTimeStamp;if(!e)return void r(c());(Number(new Date)-Number(new Date(e)))/1e3>=a&&r(c())}else r(c(!1))},updateQueryData:(e,t,n,r=!0)=>(o,s)=>{const a=i.endpoints[e].select(t)(s()),c={patches:[],inversePatches:[],undo:()=>o(i.util.patchQueryData(e,t,c.inversePatches,r))};if(a.status===To)return c;let u;if("data"in a)if(ur(a.data)){const[e,t,r]=ao(a.data,n);c.patches.push(...t),c.inversePatches.push(...r),u=e}else u=n(a.data),c.patches.push({op:"replace",path:[],value:u}),c.inversePatches.push({op:"replace",path:[],value:a.data});return 0===c.patches.length||o(i.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(i.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[ci]:()=>({data:n})})),patchQueryData:(e,t,o,a)=>(c,u)=>{const d=n[e],l=r({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(i.internalActions.queryResultPatched({queryCacheKey:l,patches:o})),!a)return;const p=i.endpoints[e].select(t)(u()),f=ii(d.providesTags,p.data,void 0,t,{},s);c(i.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:_,context:P,api:r,serializeQueryArgs:S,assertTagType:C,selectors:O,onSchemaFailure:F,catchSchemaFailure:A,skipSchemaValidation:x}),{reducer:W,actions:V}=function({reducerPath:n,queryThunk:r,mutationThunk:o,serializeQueryArgs:l,context:{endpointDefinitions:f,apiUid:h,extractRehydrationInfo:g,hasRehydrationInfo:m},assertTagType:v,config:b}){const _=e(`${n}/resetApiState`);function S(e,t,n,r){e[t.queryCacheKey]??={status:To,endpointName:t.endpointName},bi(e,t.queryCacheKey,e=>{e.status=Eo,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp,ri(f[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function w(e,t,n,r){bi(e,t.arg.queryCacheKey,e=>{if(e.requestId!==t.requestId&&!r)return;const{merge:o}=f[t.arg.endpointName];if(e.status=ko,o)if(void 0!==e.data){const{fulfilledTimeStamp:r,arg:i,baseQueryMeta:s,requestId:a}=t;let c=y(e.data,e=>o(e,n,{arg:i.originalArgs,baseQueryMeta:s,fulfilledTimeStamp:r,requestId:a}));e.data=c}else e.data=n;else e.data=f[t.arg.endpointName].structuralSharing??1?xo(cr(e.data)?(cr(i=e.data)||Zn(15,i),i[Xn].base_):e.data,n):n;var i;delete e.error,e.fulfilledTimeStamp=t.fulfilledTimeStamp})}const T=i({name:`${n}/queries`,initialState:wi,reducers:{removeQueryResult:{reducer(e,{payload:{queryCacheKey:t}}){delete e[t]},prepare:s()},cacheEntriesUpserted:{reducer(e,t){for(const n of t.payload){const{queryDescription:r,value:o}=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:{}},o,!0)}},prepare:e=>({payload:e.map(e=>{const{endpointName:t,arg:n,value:r}=e;return{queryDescription:{type:Zo,endpointName:t,originalArgs:e.arg,queryCacheKey:l({queryArgs:n,endpointDefinition:f[t],endpointName:t})},value:r}}),meta:{[p]:!0,requestId:t(),timestamp:Date.now()}})},queryResultPatched:{reducer(e,{payload:{queryCacheKey:t,patches:n}}){bi(e,t,e=>{e.data=co(e.data,n.concat())})},prepare:s()}},extraReducers(e){e.addCase(r.pending,(e,{meta:t,meta:{arg:n}})=>{S(e,n,ui(n),t)}).addCase(r.fulfilled,(e,{meta:t,payload:n})=>{w(e,t,n,ui(t.arg))}).addCase(r.rejected,(e,{meta:{condition:t,arg:n,requestId:r},error:o,payload:i})=>{bi(e,n.queryCacheKey,e=>{if(t);else{if(e.requestId!==r)return;e.status=Io,e.error=i??o}})}).addMatcher(m,(e,t)=>{const{queries:n}=g(t);for(const[t,r]of Object.entries(n))r?.status!==ko&&r?.status!==Io||(e[t]=r)})}}),E=i({name:`${n}/mutations`,initialState:wi,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=_i(t);n in e&&delete e[n]},prepare:s()}},extraReducers(e){e.addCase(o.pending,(e,{meta:t,meta:{requestId:n,arg:r,startedTimeStamp:o}})=>{r.track&&(e[_i(t)]={requestId:n,status:Eo,endpointName:r.endpointName,startedTimeStamp:o})}).addCase(o.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&Si(e,n,e=>{e.requestId===n.requestId&&(e.status=ko,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(o.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&Si(e,r,e=>{e.requestId===r.requestId&&(e.status=Io,e.error=t??n)})}).addMatcher(m,(e,t)=>{const{mutations:n}=g(t);for(const[t,r]of Object.entries(n))r?.status!==ko&&r?.status!==Io||t===r?.requestId||(e[t]=r)})}}),k=i({name:`${n}/invalidation`,initialState:{tags:{},keys:{}},reducers:{updateProvidedBy:{reducer(e,t){for(const{queryCacheKey:n,providedTags:r}of t.payload){I(e,n);for(const{type:t,id:o}of r){const r=(e.tags[t]??={})[o||"__internal_without_id"]??=[];r.includes(n)||r.push(n)}e.keys[n]=r}},prepare:s()}},extraReducers(e){e.addCase(T.actions.removeQueryResult,(e,{payload:{queryCacheKey:t}})=>{I(e,t)}).addMatcher(m,(e,t)=>{const{provided:n}=g(t);for(const[t,r]of Object.entries(n.tags??{}))for(const[o,i]of Object.entries(r)){const r=(e.tags[t]??={})[o||"__internal_without_id"]??=[];for(const t of i)r.includes(t)||r.push(t),e.keys[t]=n.keys[t]}}).addMatcher(a(c(r),u(r)),(e,t)=>{F(e,[t])}).addMatcher(T.actions.cacheEntriesUpserted.match,(e,t)=>{F(e,t.payload.map(({queryDescription:e,value:t})=>({type:"UNKNOWN",payload:t,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:e}})))})}});function I(e,t){const n=vi(e.keys[t]??[]);for(const r of n){const n=r.type,o=r.id??"__internal_without_id",i=e.tags[n]?.[o];i&&(e.tags[n][o]=vi(i).filter(e=>e!==t))}delete e.keys[t]}function F(e,t){const n=t.map(e=>{const t=yi(e,"providesTags",f,v),{queryCacheKey:n}=e.meta.arg;return{queryCacheKey:n,providedTags:t}});k.caseReducers.updateProvidedBy(e,k.actions.updateProvidedBy(n))}const A=i({name:`${n}/subscriptions`,initialState:wi,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),x=i({name:`${n}/internalSubscriptions`,initialState:wi,reducers:{subscriptionsUpdated:{reducer:(e,t)=>co(e,t.payload),prepare:s()}}}),P=i({name:`${n}/config`,initialState:{online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine,focused:"undefined"==typeof document||"hidden"!==document.visibilityState,middlewareRegistered:!1,...b},reducers:{middlewareRegistered(e,{payload:t}){e.middlewareRegistered="conflict"!==e.middlewareRegistered&&h===t||"conflict"}},extraReducers:e=>{e.addCase(Jo,e=>{e.online=!0}).addCase(Xo,e=>{e.online=!1}).addCase(Ho,e=>{e.focused=!0}).addCase(Go,e=>{e.focused=!1}).addMatcher(m,e=>({...e}))}}),C=d({queries:T.reducer,mutations:E.reducer,provided:k.reducer,subscriptions:x.reducer,config:P.reducer});return{reducer:(e,t)=>C(_.match(t)?void 0:e,t),actions:{...P.actions,...T.actions,...A.actions,...x.actions,...E.actions,...k.actions,resetApiState:_}}}({context:P,queryThunk:Q,mutationThunk:B,serializeQueryArgs:S,reducerPath:_,assertTagType:C,config:{refetchOnFocus:E,refetchOnReconnect:k,refetchOnMountOrArgChange:T,keepUnusedDataFor:w,reducerPath:_,invalidationBehavior:I}});xi(r.util,{patchQueryData:z,updateQueryData:$,upsertQueryData:U,prefetch:L,resetApiState:V.resetApiState,upsertQueryEntries:V.cacheEntriesUpserted}),xi(r.internalActions,V);const H=new WeakMap,G=e=>Ro(H,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:J,buildInitiateInfiniteQuery:X,buildInitiateMutation:Y,getRunningMutationThunk:Z,getRunningMutationsThunk:ee,getRunningQueriesThunk:te,getRunningQueryThunk:ne}=function({serializeQueryArgs:e,queryThunk:t,infiniteQueryThunk:r,mutationThunk:o,api:i,context:s,getInternalState:a}){const c=e=>a(e)?.runningQueries,u=e=>a(e)?.runningMutations,{unsubscribeQueryResult:d,removeMutationResult:l,updateSubscriptionOptions:p}=i.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}={})=>(i,s)=>{const a=o({type:"mutation",endpointName:e,originalArgs:t,track:n,fixedCacheKey:r}),c=i(a);f(i);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:()=>{i(l({requestId:d,fixedCacheKey:r}))}}),y=u(i);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 o=ai(s,t),i=e({queryArgs:n,endpointDefinition:o,endpointName:t});return c(r)?.get(i)}},getRunningMutationThunk:function(e,t){return e=>u(e)?.get(t)},getRunningQueriesThunk:function(){return e=>Oo(c(e))},getRunningMutationsThunk:function(){return e=>Oo(u(e))}};function f(e){if("production"!==process.env.NODE_ENV){if(f.triggered)return;const t=e(i.internalActions.internal_getRTKQSubscriptions());if(f.triggered=!0,"object"!=typeof t||"string"==typeof t?.type)throw new Error("production"===process.env.NODE_ENV?n(34):`Warning: Middleware for RTK-Query API at reducerPath "${i.reducerPath}" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`)}}function h(n,o){const s=(a,{subscribe:u=!0,forceRefetch:l,subscriptionOptions:h,[ci]:g,...m}={})=>(y,v)=>{const b=e({queryArgs:a,endpointDefinition:o,endpointName:n});let _;const S={...m,type:Zo,subscribe:u,forceRefetch:l,subscriptionOptions:h,endpointName:n,originalArgs:a,queryCacheKey:b,[ci]:g};if(ni(o))_=t(S);else{const{direction:e,initialPageParam:t,refetchCachedPages:n}=m;_=r({...S,direction:e,initialPageParam:t,refetchCachedPages:n})}const w=i.endpoints[n].select(a),T=y(_),E=w(v());f(y);const{requestId:k,abort:I}=T,F=E.requestId!==k,A=c(y)?.get(b),x=()=>w(v()),P=Object.assign(g?T.then(x):F&&!A?Promise.resolve(E):Promise.all([A,T]).then(x),{arg:a,requestId:k,subscriptionOptions:h,queryCacheKey:b,abort:I,async unwrap(){const e=await P;if(e.isError)throw e.error;return e.data},refetch:e=>y(s(a,{subscribe:!1,forceRefetch:!0,...e})),unsubscribe(){u&&y(d({queryCacheKey:b,requestId:k}))},updateSubscriptionOptions(e){P.subscriptionOptions=e,y(p({endpointName:n,requestId:k,queryCacheKey:b,options:e}))}});if(!A&&!F&&!g){const e=c(y);e.set(b,P),P.then(()=>{e.delete(b)})}return P};return s}}({queryThunk:Q,mutationThunk:B,infiniteQueryThunk:j,api:r,serializeQueryArgs:S,context:P,getInternalState:G});xi(r.util,{getRunningMutationThunk:Z,getRunningMutationsThunk:ee,getRunningQueryThunk:ne,getRunningQueriesThunk:te});const{middleware:re,actions:oe}=function(t){const{reducerPath:n,api:r,context:o,getInternalState:i}=t,{apiUid:s}=o,a={invalidateTags:e(`${n}/invalidateTags`)},c=e=>e.type.startsWith(`${n}/`),u=[Ri,Pi,Mi,Ni,Oi,Di];return{middleware:e=>{let a=!1;const l=i(e.dispatch),p={...t,internalState:l,refetchQuery:d,isThisApiSliceAction:c,mwApi:e},f=u.map(e=>e(p)),h=(({api:e,queryThunk:t,internalState:n})=>{const r=`${e.reducerPath}/subscriptions`;let o=null,i=null;const{updateSubscriptionOptions:s,unsubscribeQueryResult:a}=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(o||(o=d(n.currentSubscriptions)),e.util.resetApiState.match(c))return o={},n.currentSubscriptions.clear(),i=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(c))return[!1,u];const p=((n,r)=>{if(s.match(r)){const{queryCacheKey:e,requestId:t,options:o}=r.payload,i=n.get(e);return i?.has(t)&&i.set(t,o),!0}if(a.match(r)){const{queryCacheKey:e,requestId:t}=r.payload,o=n.get(e);return o&&o.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,o=Ro(n,e.queryCacheKey,Mo);return e.subscribe&&o.set(t,e.subscriptionOptions??o.get(t)??{}),!0}let o=!1;if(t.rejected.match(r)){const{meta:{condition:e,arg:t,requestId:i}}=r;if(e&&t.subscribe){const e=Ro(n,t.queryCacheKey,Mo);e.set(i,t.subscriptionOptions??e.get(i)??{}),o=!0}}return o})(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){i||(i=setTimeout(()=>{const t=d(n.currentSubscriptions),[,r]=ao(o,()=>t);l.next(e.internalActions.subscriptionsUpdated(r)),o=t,i=null},500));const s="string"==typeof c.type&&!!c.type.startsWith(r),a=t.rejected.match(c)&&c.meta.condition&&!!c.meta.arg.subscribe;f=!s&&!a}return[f,!1]}})(p),g=(({reducerPath:e,context:t,api:n,refetchQuery:r,internalState:o})=>{const{removeQueryResult:i}=n.internalActions;function s(n,s){const a=n.getState()[e],c=a.queries,u=o.currentSubscriptions;t.batch(()=>{for(const e of u.keys()){const t=c[e],o=u.get(e);if(!o||!t)continue;const d=[...o.values()];(d.some(e=>!0===e[s])||d.every(e=>void 0===e[s])&&a.config[s])&&(0===o.size?n.dispatch(i({queryCacheKey:e})):t.status!==To&&n.dispatch(r(t)))}})}return(e,t)=>{Ho.match(e)&&s(t,"refetchOnFocus"),Jo.match(e)&&s(t,"refetchOnReconnect")}})(p);return t=>i=>{if(!m(i))return t(i);a||(a=!0,e.dispatch(r.internalActions.middlewareRegistered(s)));const u={...e,next:t},d=e.getState(),[l,p]=h(i,u,d);let y;if(y=l?t(i):p,e.getState()[n]&&(g(i,u,d),c(i)||o.hasRehydrationInfo(i)))for(const e of f)e(i,u,d);return y}},actions:a};function d(e){return t.api.endpoints[e.endpointName].initiate(e.originalArgs,{subscribe:!1,forceRefetch:!0})}}({reducerPath:_,context:P,queryThunk:Q,mutationThunk:B,infiniteQueryThunk:j,api:r,assertTagType:C,selectors:O,getRunningQueryThunk:ne,getInternalState:G});return xi(r.util,oe),xi(r,{reducer:W,middleware:re}),{name:qi,injectEndpoint(e,t){const n=r,o=n.endpoints[e]??={};ni(t)&&xi(o,{name:e,select:N(e,t),initiate:J(e,t)},K(Q,e)),t.type===ei&&xi(o,{name:e,select:q(),initiate:Y(e)},K(B,e)),ri(t)&&xi(o,{name:e,select:D(e,t),initiate:X(e,t)},K(Q,e))}}}});function ji(e){return e.replace(e[0],e[0].toUpperCase())}function Bi(e){let t=0;for(const n in e)t++;return t}function zi(e){return"infinitequery"===e.type}function $i(e,...t){return Object.assign(e,...t)}Qi();var Ui=Symbol();function Li(e){const t=M(e),n=O(()=>xo(t.current,e),[e]);return C(()=>{t.current!==n&&(t.current=n)},[n]),n}function Ki(e){const t=M(e);return C(()=>{E(t.current,e)||(t.current=e)},[e]),E(t.current,e)?t.current:e}var Wi=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),Vi="undefined"!=typeof navigator&&"ReactNative"===navigator.product,Hi=(()=>Wi||Vi?N:C)(),Gi=e=>e.isUninitialized?{...e,isUninitialized:!1,isFetching:!0,isLoading:void 0===e.data,status:wo.pending}:e;function Ji(e,...t){const n={};return t.forEach(t=>{n[t]=e[t]}),n}var Xi=["data","status","isLoading","isSuccess","isError","error"],Yi=Symbol(),Zi=function(...e){return function(r){const o=vo(e=>r.extractRehydrationInfo?.(e,{reducerPath:r.reducerPath??"api"})),i={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...r,extractRehydrationInfo:o,serializeQueryArgs(e){let t=Ai;if("serializeQueryArgs"in e.endpointDefinition){const n=e.endpointDefinition.serializeQueryArgs;t=e=>{const t=n(e);return"string"==typeof t?t:Ai({...e,queryArgs:t})}}else r.serializeQueryArgs&&(t=r.serializeQueryArgs);return t(e)},tagTypes:[...r.tagTypes||[]]},s={endpointDefinitions:{},batch(e){e()},apiUid:t(),extractRehydrationInfo:o,hasRehydrationInfo:vo(e=>null!=o(e))},a={injectEndpoints:function(e){const t=e.endpoints({query:e=>({...e,type:Zo}),mutation:e=>({...e,type:ei}),infiniteQuery:e=>({...e,type:ti})});for(const[r,o]of Object.entries(t))if(!0!==e.overrideExisting&&r in s.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error("production"===process.env.NODE_ENV?n(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&&ri(o)){const{infiniteQueryOptions:e}=o,{maxPages:t,getPreviousPageParam:i}=e;if("number"==typeof t){if(t<1)throw new Error("production"===process.env.NODE_ENV?n(40):`maxPages for endpoint '${r}' must be a number greater than 0`);if("function"!=typeof i)throw new Error("production"===process.env.NODE_ENV?n(41):`getPreviousPageParam for endpoint '${r}' must be a function if maxPages is used`)}}s.endpointDefinitions[r]=o;for(const e of c)e.injectEndpoint(r,o)}return a},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)i.tagTypes.includes(t)||i.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(ai(s,e)):Object.assign(ai(s,e)||{},n);return a}},c=e.map(e=>e.init(a,i,s));return a.injectEndpoints({endpoints:r.endpoints})}}(Qi(),(({batch:e=k,hooks:t={useDispatch:T,useSelector:S,useStore:w},createSelector:r=_o,unstable__sideEffectsInRender:o=!1,...i}={})=>{if("production"!==process.env.NODE_ENV){const e=["useDispatch","useSelector","useStore"];let r=!1;for(const o of e)if(Bi(i)>0&&(i[o]&&(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)),t[o]=i[o]),"function"!=typeof t[o])throw new Error("production"===process.env.NODE_ENV?n(36):`When using custom hooks for context, all ${e.length} hooks need to be provided: ${e.join(", ")}.\nHook ${o} was either not provided or not a function.`)}return{name:Yi,init(i,{serializeQueryArgs:s},a){const c=i,{buildQueryHooks:u,buildInfiniteQueryHooks:d,buildMutationHook:l,usePrefetch:p}=function({api:e,moduleOptions:{batch:t,hooks:{useDispatch:r,useSelector:o,useStore:i},unstable__sideEffectsInRender:s,createSelector:a},serializeQueryArgs:c,context:u}){const d=s?e=>e():C,l=e=>e.current?.unsubscribe?.(),p=u.endpointDefinitions;return{buildQueryHooks:function(o){const i=(e,t={})=>{const[r]=g(o,e,t);return y(r),O(()=>({refetch:()=>function(e){if(!e.current)throw new Error("production"===process.env.NODE_ENV?n(38):"Cannot refetch a query that has not been started yet.");return e.current.refetch()}(r)}),[r])},s=({refetchOnReconnect:n,refetchOnFocus:i,pollingInterval:s=0,skipPollingIfUnfocused:a=!1}={})=>{const{initiate:c}=e.endpoints[o],u=r(),[p,f]=P(Ui),h=M(void 0),g=Ki({refetchOnReconnect:n,refetchOnFocus:i,pollingInterval:s,skipPollingIfUnfocused:a});d(()=>{const e=h.current?.subscriptionOptions;g!==e&&h.current?.updateSubscriptionOptions(g)},[g]);const m=M(g);d(()=>{m.current=g},[g]);const y=x(function(e,n=!1){let r;return t(()=>{l(h),h.current=r=u(c(e,{subscriptionOptions:m.current,forceRefetch:!n})),f(e)}),r},[u,c]),v=x(()=>{h.current?.queryCacheKey&&u(e.internalActions.removeQueryResult({queryCacheKey:h.current?.queryCacheKey}))},[u]);return C(()=>()=>{l(h)},[]),C(()=>{p===Ui||h.current||y(p,!0)},[p,y]),O(()=>[y,p,{reset:v}],[y,p,v])},a=m(o,f);return{useQueryState:a,useQuerySubscription:i,useLazyQuerySubscription:s,useLazyQuery(e){const[t,n,{reset:r}]=s(e),o=a(n,{...e,skip:n===Ui}),i=O(()=>({lastArg:n}),[n]);return O(()=>[t,{...o,reset:r},i],[t,o,r,i])},useQuery(e,t){const n=i(e,t),r=a(e,{selectFromResult:e===Ti||t?.skip?void 0:Gi,...t}),o=Ji(r,...Xi);return R(o),O(()=>({...r,...n}),[r,n])}}},buildInfiniteQueryHooks:function(e){const r=(r,o={})=>{const[i,s,a,c]=g(e,r,o),u=M(c);d(()=>{u.current=c},[c]);const p=Ki(o.refetchCachedPages),f=x(function(e,n){let r;return t(()=>{l(i),i.current=r=s(a(e,{subscriptionOptions:u.current,direction:n}))}),r},[i,s,a]);y(i);const h=Li(o.skip?Ti:r),m=x(e=>{if(!i.current)throw new Error("production"===process.env.NODE_ENV?n(38):"Cannot refetch a query that has not been started yet.");return i.current.refetch({refetchCachedPages:e?.refetchCachedPages??p})},[i,p]);return O(()=>({trigger:f,refetch:m,fetchNextPage:()=>f(h,"forward"),fetchPreviousPage:()=>f(h,"backward")}),[m,f,h])},o=m(e,h);return{useInfiniteQueryState:o,useInfiniteQuerySubscription:r,useInfiniteQuery(e,t){const{refetch:n,fetchNextPage:i,fetchPreviousPage:s}=r(e,t),a=o(e,{selectFromResult:e===Ti||t?.skip?void 0:Gi,...t}),c=Ji(a,...Xi,"hasNextPage","hasPreviousPage");return R(c),O(()=>({...a,fetchNextPage:i,fetchPreviousPage:s,refetch:n}),[a,i,s,n])}}},buildMutationHook:function(n){return({selectFromResult:i,fixedCacheKey:s}={})=>{const{select:c,initiate:u}=e.endpoints[n],d=r(),[l,p]=P();C(()=>()=>{l?.arg.fixedCacheKey||l?.reset()},[l]);const f=x(function(e){const t=d(u(e,{fixedCacheKey:s}));return p(t),t},[d,u,s]),{requestId:h}=l||{},g=O(()=>c({fixedCacheKey:s,requestId:l?.requestId}),[s,l,c]),m=O(()=>i?a([g],i):g,[i,g]),y=o(m,E),v=null==s?l?.arg.originalArgs:void 0,b=x(()=>{t(()=>{l&&p(void 0),s&&d(e.internalActions.removeMutationResult({requestId:h,fixedCacheKey:s}))})},[d,s,l,h]),_=Ji(y,...Xi,"endpointName");R(_);const S=O(()=>({...y,originalArgs:v,reset:b}),[y,v,b]);return O(()=>[f,S],[f,S])}},usePrefetch:function(t,n){const o=r(),i=Ki(n);return x((n,r)=>o(e.util.prefetch(t,n,{...i,...r})),[t,o,i])}};function f(e,t,n){if(t?.endpointName&&e.isUninitialized){const{endpointName:e}=t,r=p[e];n!==Ti&&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 o=void 0!==r,i=e.isLoading,s=(!t||t.isLoading||t.isUninitialized)&&!o&&i,a=e.isSuccess||o&&(i&&!t?.isError||e.isUninitialized);return{...e,data:r,currentData:e.data,isFetching:i,isLoading:s,isSuccess:a}}function h(e,t,n){if(t?.endpointName&&e.isUninitialized){const{endpointName:e}=t,r=p[e];n!==Ti&&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 o=void 0!==r,i=e.isLoading,s=(!t||t.isLoading||t.isUninitialized)&&!o&&i,a=e.isSuccess||i&&o;return{...e,data:r,currentData:e.data,isFetching:i,isLoading:s,isSuccess:a}}function g(t,o,{refetchOnReconnect:i,refetchOnFocus:s,refetchOnMountOrArgChange:a,skip:c=!1,pollingInterval:u=0,skipPollingIfUnfocused:l=!1,...f}={}){const{initiate:h}=e.endpoints[t],g=r(),m=M(void 0);if(!m.current){const t=g(e.internalActions.internal_getRTKQSubscriptions());if("production"!==process.env.NODE_ENV&&("object"!=typeof t||"string"==typeof t?.type))throw new Error("production"===process.env.NODE_ENV?n(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=t}const y=Li(c?Ti:o),v=Ki({refetchOnReconnect:i,refetchOnFocus:s,pollingInterval:u,skipPollingIfUnfocused:l}),b=Ki(f.initialPageParam),_=Ki(f.refetchCachedPages),S=M(void 0);let{queryCacheKey:w,requestId:T}=S.current||{},E=!1;w&&T&&(E=m.current.isRequestSubscribed(w,T));const k=!E&&void 0!==S.current;return d(()=>{k&&(S.current=void 0)},[k]),d(()=>{const e=S.current;if("undefined"!=typeof process&&process,y===Ti)return e?.unsubscribe(),void(S.current=void 0);const n=S.current?.subscriptionOptions;if(e&&e.arg===y)v!==n&&e.updateSubscriptionOptions(v);else{e?.unsubscribe();const n=g(h(y,{subscriptionOptions:v,forceRefetch:a,...zi(p[t])?{initialPageParam:b,refetchCachedPages:_}:{}}));S.current=n}},[g,h,a,y,v,k,b,_,t]),[S,g,h,v]}function m(t,n){return(r,{skip:s=!1,selectFromResult:c}={})=>{const{select:u}=e.endpoints[t],d=Li(s?Ti:r),l=M(void 0),p=O(()=>a([u(d),(e,t)=>t,e=>d],n,{memoizeOptions:{resultEqualityCheck:E}}),[u,d]),f=O(()=>c?a([p],c,{devModeChecks:{identityFunctionCheck:"never"}}):p,[p,c]),h=o(e=>f(e,l.current),E),g=i(),m=p(g.getState(),l.current);return Hi(()=>{l.current=m},[m]),h}}function y(e){C(()=>()=>{l(e),e.current=void 0},[e])}}({api:i,moduleOptions:{batch:e,hooks:t,unstable__sideEffectsInRender:o,createSelector:r},serializeQueryArgs:s,context:a});return $i(c,{usePrefetch:p}),$i(a,{batch:e}),{injectEndpoint(e,t){if("query"===t.type){const{useQuery:t,useLazyQuery:n,useLazyQuerySubscription:r,useQueryState:o,useQuerySubscription:s}=u(e);$i(c.endpoints[e],{useQuery:t,useLazyQuery:n,useLazyQuerySubscription:r,useQueryState:o,useQuerySubscription:s}),i[`use${ji(e)}Query`]=t,i[`useLazy${ji(e)}Query`]=n}if("mutation"===t.type){const t=l(e);$i(c.endpoints[e],{useMutation:t}),i[`use${ji(e)}Mutation`]=t}else if(zi(t)){const{useInfiniteQuery:t,useInfiniteQuerySubscription:n,useInfiniteQueryState:r}=d(e);$i(c.endpoints[e],{useInfiniteQuery:t,useInfiniteQuerySubscription:n,useInfiniteQueryState:r}),i[`use${ji(e)}InfiniteQuery`]=t}}}}}})());let es=0;const ts="Something went wrong. Please try again.",ns="UNKNOWN";let rs=null;const os=function(e){const{name:t,innerBaseQuery:n,requestInterceptors:r,responseInterceptors:o,defaultOptions:i}=e;return async(e,s,a)=>{let c,u;if("string"==typeof e)c={url:e};else{const{_bridge:t,...n}=e;c=n,u=t}const d={...a,bridge:{...i,...a?.bridge,...u}},l={bridgeName:t,requestId:(p=t,es+=1,`${p}-${es}`),startTime:Date.now(),api:s,extraOptions:d};var p;const f=async e=>{let t=e;for(const e of r)t=await e(t,l);return n(t,s,d)};let h=await f(c);for(const e of o)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=qo,paramsSerializer:r,isJsonContentType:o=jo,jsonContentType:i="application/json",jsonReplacer:s,timeout:a,responseHandler:c,validateStatus:u,...d}={}){return"undefined"==typeof fetch&&n===qo&&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:b,type:_}=h;let S,{url:w,headers:T=new Headers(d.headers),params:E,responseHandler:k=c??"json",validateStatus:I=u??Qo,timeout:F=a,...A}="string"==typeof f?{url:f}:f,x={...d,signal:F?Do(h.signal,No(F)):h.signal,...A};T=new Headers(Bo(T)),x.headers=await t(T,{getState:m,arg:f,extra:y,endpoint:v,forced:b,type:_,extraOptions:g})||T;const P="object"==typeof(C=x.body)&&(l(C)||Array.isArray(C)||"function"==typeof C.toJSON);var C;if(null==x.body||P||"string"==typeof x.body||x.headers.delete("content-type"),!x.headers.has("content-type")&&P&&x.headers.set("content-type",i),P&&o(x.headers)&&(x.body=JSON.stringify(x.body,s)),x.headers.has("accept")||("json"===k?x.headers.set("accept","application/json"):"text"===k&&x.headers.set("accept","text/plain, text/html, */*")),E){const e=~w.indexOf("?")?"&":"?";w+=e+(r?r(E):new URLSearchParams(Bo(E)))}w=function(e,t){if(!e)return t;if(!t)return e;if(n=t,new RegExp("(^|:)//").test(n))return t;var n;const r=e.endsWith("/")||!t.startsWith("?")?"/":"";return e=(e=>e.replace(/\/$/,""))(e),`${e}${r}${t=(e=>e.replace(/^\//,""))(t)}`}(e,w);const O=new Request(w,x);let R;S={request:new Request(w,x)};try{R=await n(O)}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 M=R.clone();let N;S.response=M;let D="";try{let e;if(await Promise.all([p(R,k).then(e=>N=e,t=>e=t),M.text().then(e=>D=e,()=>{})]),e)throw e}catch(e){return{error:{status:"PARSING_ERROR",originalStatus:R.status,data:D,error:String(e)},meta:S}}return I(R,N)?{data:N,meta:S}:{error:{status:R.status,data:N},meta:S}};async function p(e,t){if("function"==typeof t)return t(e);if("content-type"===t&&(t=o(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=Kt(),r=t.extraOptions.bridge?.customHeaders,o=Object.keys(n).length>0,i=!!r&&Object.keys(r).length>0;return o||i?{...e,headers:{...e.headers,...n,...r??{}}}:e},(e,t)=>e],responseInterceptors:[async(e,t,n,r)=>{if(n.extraOptions.bridge?.skipTokenRefresh)return e;if(401!==e.error?.status)return e;const o=n.api.getState();if(!o.auth?.accessToken||!o.auth?.isAuthenticated)return e;if(!Wt())return n.api.dispatch(qn()),e;try{const e=await async function(){return rs||(rs=async function(){const e=Wt();if(!e)return null;try{return await e()}catch{return null}}().finally(()=>{rs=null}),rs)}();if(e){const o=n.api.getState().auth?.accessToken;return o!==e.accessToken&&n.api.dispatch(Nn({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresIn:e.expiresIn})),r(t)}Ft.error({message:"Session cleared: token refresh failed after 401",api_name:"auth-refresh"}),n.api.dispatch(qn())}catch{Ft.error({message:"Session cleared: token refresh threw after 401",api_name:"auth-refresh"}),n.api.dispatch(qn())}return e},async(e,t,n)=>{if(!e.error)return e;const r=(o=e.error,i={url:t.url,method:t.method||"GET",timestamp:n.startTime,duration:Date.now()-n.startTime,requestId:n.requestId,bridgeName:n.bridgeName},o&&"object"==typeof o&&"status"in o?function(e,t){const n="PARSING_ERROR"===e.status,r=n?e.originalStatus:void 0,o="number"==typeof r&&r>=400?r:e.status;let i,s="Request failed",a=ns;if("data"in e)if(i=e.data,"string"==typeof e.data)s=e.data;else if(e.data&&"object"==typeof e.data){const t=e.data;s=t.message||t.error||t.detail||s}return!n&&"error"in e&&"string"==typeof e.error&&(s=e.error),401===o?a="UNAUTHORIZED":403===o?a="FORBIDDEN":404===o?a="NOT_FOUND":422===o?a="VALIDATION_ERROR":"FETCH_ERROR"===o?a="NETWORK_ERROR":"TIMEOUT_ERROR"===o?a="TIMEOUT":"PARSING_ERROR"===o?a="PARSE_ERROR":"number"==typeof o&&o>=500&&(a="SERVER_ERROR"),"number"==typeof o&&o>=500&&(s=ts),{status:o,message:s,data:i,code:a,meta:{timestamp:Date.now(),...t}}}(o,i):o instanceof Error?{status:"FETCH_ERROR",message:o.message||"An unexpected error occurred",code:ns,meta:{timestamp:Date.now(),...i}}:"string"==typeof o?{status:"CUSTOM_ERROR",message:o,code:ns,meta:{timestamp:Date.now(),...i}}:{status:"CUSTOM_ERROR",message:"An unknown error occurred",data:o,code:ns,meta:{timestamp:Date.now(),...i}});var o,i;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?(dn("Network error. Please check your connection."),e):"TIMEOUT_ERROR"===r?(dn("Request timed out. Please try again."),e):"number"==typeof r&&r>=500?(dn(ts),e):e},async(e,t,n,r)=>{if(!e.error)return e;const{status:o}=e.error;if("FETCH_ERROR"!==o&&"TIMEOUT_ERROR"!==o)return e;const i=n.extraOptions.bridge?.retry,s=i?.maxRetries??1,a=i?.backoffMs??1e3,c=parseInt(t.headers?.["X-Bridge-Retry-Count"]||"0",10);if(c>=s)return e;const u=a*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=Date.now()-n.startTime,o=(t.method||"GET").toUpperCase(),i=t.url||"",s=e.meta?.response,a=e.error?e.error.status:s?.status??"OK",c=s?.headers?.get?.("x-request-id")??void 0;return!!e.error&&Ft.error({message:`${n.bridgeName} ${o} ${i} failed (${a})`,api_name:n.api.endpoint,request_id:c??n.requestId,method:o,url:i,status:a,duration:r,error_data:e.error.data}),e}]});function is(){return zt()}let ss=0;const as=Zi({reducerPath:"chatApi",baseQuery:os,keepUnusedDataFor:0,tagTypes:["chat","toolServers"],endpoints:e=>({getConversationHistory:e.query({query:({skip:e=0,limit:t=20})=>({url:`${Jt.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:`${Jt.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:`${Jt.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 async function(e){const{url:t,method:n="GET",body:r,headers:o={},skipAuth:i=!1,skipLogging:s=!1,skipContentType:a=!1,responseHandler:c="json",signal:u,keepalive:d}=e;ss+=1;const l=`fetch-${ss}`,p=Date.now(),f=n.toUpperCase(),h={...o};if(Object.assign(h,Kt()),!i){const e=is();e&&(h.Authorization=`Bearer ${e}`)}let g;a||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);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 o=e.headers.get("x-request-id")??void 0;return s||Ft.error({message:`bridgedFetch ${f} ${t} failed (${e.status})`,api_name:"bridgedFetch",request_id:o??l,method:f,url:t,status:e.status,duration:r,error_data:n}),{error:{status:e.status,data:n},response:e}}let o;if("blob"===c)o=await e.blob();else if("text"===c)o=await e.text();else{const t=await e.text();o=t?JSON.parse(t):void 0}return{data:o,response:e}}catch(e){const n=Date.now()-p;return s||Ft.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"}}}}({url:Jt.TRANSCRIBE,method:"POST",body:t,skipContentType:!0});return r?{error:r}:{data:n}}}),getToolServers:e.query({query:()=>({url:Jt.TOOL_SERVERS,method:"GET"}),transformResponse:e=>e?.data??{tool_servers:[]},providesTags:["toolServers"]}),startToolServerOAuth:e.mutation({query:e=>({url:Jt.TOOL_SERVER_AUTH_START(e),method:"POST"}),transformResponse:e=>e?.data??{authorize_url:""}}),deleteToolServerConnection:e.mutation({query:e=>({url:Jt.TOOL_SERVER_AUTH_CONNECTION(e),method:"DELETE"}),invalidatesTags:["toolServers"]}),exchangeOAuthCode:e.mutation({query:({code:e,state:t})=>({url:Jt.TOOL_SERVERS_SIGN_IN_EXCHANGE,method:"POST",body:{code:e,state:t}}),invalidatesTags:["toolServers"]}),deleteConversation:e.mutation({query:({conversationId:e})=>({url:`${Jt.CONVERSATIONS()}/${e}`,method:"DELETE"}),extraOptions:{bridge:{skipErrorToast:!0}}})})}),cs={bridge:{skipErrorToast:!0,skipTokenRefresh:!0}},us=Zi({reducerPath:"brandingApi",baseQuery:os,keepUnusedDataFor:0,endpoints:e=>({getBranding:e.query({query:e=>({url:Jt.BRANDING,method:"GET",_bridge:{skipAuth:!e}}),extraOptions:cs})})}),{useGetBrandingQuery:ds}=us,ls={bridge:{skipErrorToast:!0,skipTokenRefresh:!0,retry:{maxRetries:0}}},ps=Zi({reducerPath:"configApi",baseQuery:os,keepUnusedDataFor:1/0,endpoints:e=>({getConfig:e.query({query:()=>({url:Jt.CONFIG,method:"GET",_bridge:{skipAuth:!0},timeout:5e3}),extraOptions:ls})})}),{useGetConfigQuery:fs}=ps,hs=Zi({reducerPath:"profileApi",baseQuery:os,keepUnusedDataFor:0,tagTypes:["profile"],endpoints:e=>({getProfile:e.query({query:()=>({url:Jt.PROFILE,method:"GET"}),extraOptions:{bridge:{skipErrorToast:!0}},transformResponse:e=>e?.data??null,providesTags:["profile"]}),updateProfile:e.mutation({query:e=>({url:Jt.PROFILE,method:"PUT",body:e}),async onQueryStarted(e,{dispatch:t,queryFulfilled:n}){try{await n,t(hs.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:Jt.AUTH_ME,method:"DELETE"})})})}),gs={[as.reducerPath]:as.reducer,[us.reducerPath]:us.reducer,[ps.reducerPath]:ps.reducer,[hs.reducerPath]:hs.reducer},ms=[as.middleware,us.middleware,ps.middleware,hs.middleware],ys={isAgentWorking:!0,statusText:null,responseStartTime:null,messageQueue:[]},vs=i({name:"chat",initialState:ys,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:()=>ys},extraReducers:e=>{e.addMatcher(a(qn,Qn),()=>ys)}}),bs=vs.reducer,_s={activeConversationId:null,titles:{}},Ss=i({name:"conversations",initialState:_s,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(a(qn,Qn),()=>_s)}}),ws=Ss.reducer,Ts=d({...gs,auth:zn,chat:bs,conversations:ws,indicator:Ln}),Es={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"]},ks=_({reducer:Ts,middleware:e=>e({serializableCheck:Es}).prepend(Bn.middleware).concat(ms)});var Is;Is=ks.dispatch,function(){const[e,t,n,r]=[Ho,Go,Jo,Xo].map(e=>()=>Is(e())),o=()=>{"visible"===window.document.visibilityState?e():t()};if(!Yo&&"undefined"!=typeof window&&window.addEventListener){let t=function(e){Object.entries(i).forEach(([e,t])=>{window.addEventListener(e,t,!1)})};const i={[Ko]:e,[Vo]:o,[Uo]:n,[Lo]:r};t(),Yo=!0}}(),Vt(()=>ks.getState().auth.accessToken),Ht(()=>ks.getState().auth.tokenExpiresAt);const Fs=A(void 0);var As=(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))(As||{});let xs=class extends Error{constructor(e){super(),this.reopen=e}};class Ps{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})}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:o}=e;if(r)return{type:"stream_end",data:{isEnd:!0},timestamp:Date.now(),requestId:o};const i=(n||"").toLowerCase(),{type:s,data:a}=this.mapSSEEvent(i,t);return{type:s,data:a,timestamp:Date.now(),requestId:o}}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,o="",i=!1;const s=[];let a=null,c=!1,u=null;const d=e=>{a?a.onEvent(e):s.push(e)},l=e=>{a?a.onError(e):u=e},p=()=>{c=!0,a&&a.onComplete()},f=async()=>{try{await(this.config.ensureFreshToken?.()),await Vn(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&&!i){i=!0,Ft.warn({message:"MTX SSE rejected with 401 — refreshing token",api_name:"mtx-sse"});const e=await(this.config.forceRefreshToken?.());throw e||(Ft.error({message:"MTX SSE 401 refresh failed — clearing session",api_name:"mtx-sse"}),this.config.onAuthExpired?.()),new xs(Boolean(e))}const t=e.headers.get("x-request-id");t&&(o=t)},onmessage:e=>{if("[DONE]"===e.data)return;const t=(e.event||"").toLowerCase(),n=new Set(Object.values(As));if("status_update"!==t&&"clear_status"!==t||Ft.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===As.END;let r;try{r=JSON.parse(e.data)}catch{return}if(!n&&t!==As.CLEAR_STATUS&&r&&"object"==typeof r&&0===Object.keys(r).length)return;const i=this.normalizeEvent({parsed:r,eventType:e.event,isStreamEnd:n,requestId:r.request_id||o||""});d(i),n&&"stream_end"!==i.type&&d({type:"stream_end",data:{isEnd:!0},timestamp:Date.now(),requestId:o})}catch(e){Ft.error({message:"Failed to parse MTX SSE message",api_name:"mtx-sse",error_message:e instanceof Error?e.message:String(e)})}else Ft.debug({message:"Ignoring unrecognized MTX SSE event type",api_name:"mtx-sse",sse_event:e.event})},onerror:e=>{if(e instanceof xs)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 xs)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){a=e;for(const t of s)e.onEvent(t);return s.length=0,u&&(e.onError(u),u=null),c&&e.onComplete(),()=>{a=null}},abort(){n.abort()}}}}class Cs extends Error{constructor(e){super(),this.reopen=e}}class Os{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})}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&&function(e){if(e)return"moyasar"===e.provider?e.config?.given_id:e.payment_id}(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 Ft.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,o="",i=!1;const s=[];let a=null,c=!1,u=null;const d=e=>{a?a.onEvent(e):s.push(e)},l=e=>{a?a.onError(e):u=e},p=()=>{c=!0,a&&a.onComplete()},f=async()=>{try{await(this.config.ensureFreshToken?.()),await Vn(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&&!i){i=!0,Ft.warn({message:"AG-UI SSE rejected with 401 — refreshing token",api_name:"agui-sse"});const e=await(this.config.forceRefreshToken?.());throw e||(Ft.error({message:"AG-UI SSE 401 refresh failed — clearing session",api_name:"agui-sse"}),this.config.onAuthExpired?.()),new Cs(Boolean(e))}const t=e.headers.get("x-request-id");t&&(o=t)},onmessage:e=>{Ft.debug({message:"AG-UI SSE event",api_name:"agui-sse",sse_event:e.event});const t=(e.event||"").toLowerCase(),n=new Set(Object.values(As));if(!t||n.has(t))if(t!==As.END){if("[DONE]"!==e.data)try{let n;try{n=JSON.parse(e.data)}catch(t){return void Ft.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&&(o=n.runId);const r=t===As.CONVERSATION_TITLE?{...n,type:"CONVERSATION_TITLE",payload:n,runId:n.runId||o}:{...n,runId:n.runId||o},i=this.normalizeEvent(r);d(i)}catch(e){Ft.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:o}));else Ft.debug({message:"AG-UI ignoring unknown SSE event type",api_name:"agui-sse",sse_event:e.event})},onerror:e=>{if(e instanceof Cs)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 Cs)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){a=e;for(const t of s)e.onEvent(t);return s.length=0,u&&(e.onError(u),u=null),c&&e.onComplete(),()=>{a=null}},abort(){n.abort()}}}}const Rs=()=>{const{user:e,accessToken:t,tokenExpiresAt:n,isAuthenticated:r,isLoading:o}=S(e=>e.auth);return{user:e,accessToken:t,isAuthenticated:r,isLoading:o,tokenInfo:{isExpired:!!n&&ln(n),isAboutToExpire:!!n&&pn(n),expiresAt:n,timeUntilExpiry:n?fn(n):0,timeUntilExpiryFormatted:n?hn(fn(n)):"0s"}}};function Ms(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)}`}}const Ns=A(null),Ds={conversations:{disable_old_widgets:!1,allow_conversation_deletion:!0},voice_agent:{enabled:!1,show_customization_modal:!1,assistant_starts_conversation:!1},features:[]},qs=A(void 0),Qs=()=>{const{data:e,isLoading:t,error:n}=(()=>{const e=fs(),{isError:t,isFetching:n,refetch:r}=e,o=M(!1);return C(()=>{!t||n||o.current||(o.current=!0,r())},[t,n,r]),e})(),r=e?.success?e.data:null,o=O(()=>{return(e=r)?{conversations:{...Ds.conversations,...e.conversations},voice_agent:{...Ds.voice_agent,...e.voice_agent},features:e.features??Ds.features}:Ds;var e},[r]);return O(()=>({clientConfig:o,isLoading:t,error:n?new Error("Failed to fetch client configuration"):null}),[o,t,n])},js=A({}),Bs="moyasar_cb";function zs(e){const t=new URL(window.location.href),n=new URL(`${t.origin}${Ut()}/moyasar-callback.html`);return n.searchParams.set(Bs,"1"),e&&n.searchParams.set("given_id",e),n.toString()}const $s=new Set(["paid","authorized","failed","captured"]);function Us(e){if(!e)return null;const t=new URLSearchParams(e);if("1"!==t.get(Bs))return null;const n=t.get("status"),r=t.get("id");if(!n||!r)return null;if(!$s.has(n))return null;const o=t.get("conversation_id")||null,i=(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:i,amount:Number.isFinite(n)?n:void 0,currency:t.get("currency")??void 0},conversationId:o}}return{result:{status:"failure",provider:"moyasar",code:n,message:Ls(t.get("message")??`Payment ${n}`),paymentId:i},conversationId:o}}function Ls(e){try{const t=decodeURIComponent(e);return t===e?e:t}catch{return e}}function Ks(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 Ws="stripe",Vs=24e3,Hs="/sounds/thinking-sound.mp3",Gs="reset",Js="voice_selectedMicId",Xs="voice_selectedSpeakerId",Ys=i({name:"voice",initialState:{connectionStatus:"disconnected",pipelineStatus:"idle",listeningEnabled:!1,muted:!1,firstAssistantMessageComplete:!1,statusText:null,isAgentWorking:!1,responseStartTime:null,error:null,interimTranscript:null,selectedMicId:"",selectedSpeakerId:""},reducers:{setConnectionStatus(e,t){e.connectionStatus=t.payload},setPipelineStatus(e,t){e.pipelineStatus=t.payload},setListeningEnabled(e,t){e.listeningEnabled=t.payload},setStatusText(e,t){e.statusText=t.payload},setIsAgentWorking(e,t){e.isAgentWorking=t.payload},setResponseStartTime(e,t){e.responseStartTime=t.payload},setError(e,t){e.error=t.payload},setInterimTranscript(e,t){e.interimTranscript=t.payload},setMuted(e,t){e.muted=t.payload},setFirstAssistantMessageComplete(e,t){e.firstAssistantMessageComplete=t.payload},setSelectedMicId(e,t){e.selectedMicId=t.payload},setSelectedSpeakerId(e,t){e.selectedSpeakerId=t.payload},resetVoiceState:()=>({connectionStatus:"disconnected",pipelineStatus:"idle",listeningEnabled:!1,muted:!1,firstAssistantMessageComplete:!1,statusText:null,isAgentWorking:!1,responseStartTime:null,error:null,interimTranscript:null,selectedMicId:"",selectedSpeakerId:""}),resetIndicatorState(e){e.statusText=null,e.isAgentWorking=!1,e.responseStartTime=null}}}),{setSelectedMicId:Zs,setSelectedSpeakerId:ea,resetVoiceState:ta}=Ys.actions,na=Ys.reducer,ra=new Map,oa=new Map;class ia{ctx=null;masterGain=null;currentSpeakerId=void 0;nextPlayTime=0;doneTimer=null;isFirstChunk=!0;prerollProvider=null;activeSources=new Set;setPrerollProvider(e){this.prerollProvider=e}play(e,t){this.ctx&&t!==this.currentSpeakerId&&(this.ctx.close(),this.ctx=null,this.masterGain=null),this.ctx||(this.ctx=new AudioContext({sampleRate:Vs,...t?{sinkId:t}:{}}),this.masterGain=this.ctx.createGain(),this.masterGain.connect(this.ctx.destination),this.currentSpeakerId=t);const n=this.ctx,r=new Int16Array(e),o=new Float32Array(r.length);for(let e=0;e<r.length;e++)o[e]=r[e]/32768;const i=n.createBuffer(1,o.length,Vs);i.getChannelData(0).set(o);const s=n.createBufferSource();s.buffer=i,s.connect(this.masterGain),this.activeSources.add(s),s.onended=()=>this.activeSources.delete(s);const a=n.currentTime;let c=Math.max(a,this.nextPlayTime);if(this.isFirstChunk){this.isFirstChunk=!1;const e=this.prerollProvider?this.prerollProvider():.2;c=Math.max(c,a+e)}s.start(c),this.nextPlayTime=c+i.duration}get remainingSeconds(){return this.ctx?Math.max(0,this.nextPlayTime-this.ctx.currentTime):0}onDrained(e){this.doneTimer&&clearTimeout(this.doneTimer);const t=this.remainingSeconds;t<=0?e():this.doneTimer=setTimeout(()=>{this.doneTimer=null,e()},1e3*t)}resetForNewSegment(){this.isFirstChunk=!0}stop(){this.doneTimer&&(clearTimeout(this.doneTimer),this.doneTimer=null);for(const e of this.activeSources)try{e.stop()}catch(e){}this.activeSources.clear(),this.nextPlayTime=0,this.isFirstChunk=!0}destroy(){this.stop(),this.ctx&&(this.ctx.close(),this.ctx=null,this.masterGain=null)}}const sa=A(null);A(null),A({strategyActive:!1,voiceSlot:null,onEnterVoice:null,onFloatingOrbClick:null,voiceInputHidden:!1,headerCenterSlot:null,floatOrbPositionRef:null});const aa=b();aa.startListening({actionCreator:Zs,effect:async e=>{const t=On();t&&await t.setItem(Js,e.payload)}}),aa.startListening({actionCreator:ea,effect:async e=>{const t=On();t&&await t.setItem(Xs,e.payload)}}),aa.startListening({actionCreator:ta,effect:()=>{ra.clear(),oa.clear()}}),aa.startListening({matcher:a(qn,Qn),effect:async(e,t)=>{const n=On();n&&await Promise.all([n.removeItem(Js),n.removeItem(Xs)]),t.dispatch(ta())}});class ca{ctx=null;stream=null;source=null;gain=null;worklet=null;worker=null;visibilityHandler=null;opening=!1;cancelled=!1;opts=null;open(e){this.opening||this.ctx||(this.cancelled=!1,this.opening=!0,this.opts=e,e.onLoadingChange?.(!0),(async()=>{let t=null,n=null,r=null,o=null,i=null,s=null;try{try{t=new AudioContext({sampleRate:Vs})}catch{t=new AudioContext}if(this.cancelled)return void await t.close().catch(()=>{});if(await t.audioWorklet.addModule(`${Ut()}/audio-recorder.worklet.js`),this.cancelled)return void await t.close().catch(()=>{});if(n=await navigator.mediaDevices.getUserMedia({audio:{...e.micDeviceId?{deviceId:{exact:e.micDeviceId}}:{},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,sampleRate:Vs,echoCancellationType:{ideal:"system"}}}),this.cancelled)return n.getTracks().forEach(e=>e.stop()),void await t.close().catch(()=>{});r=t.createMediaStreamSource(n),o=t.createGain(),o.gain.setValueAtTime(e.initialMuted?0:1,t.currentTime),i=new AudioWorkletNode(t,"audio-recorder"),s=new Worker(`${Ut()}/audio-processor.worker.js`);const a=s;if(i.port.onmessage=e=>{if(this.cancelled)return;const t=e.data;t&&0!==t.length&&a.postMessage({type:"frame",frame:t},[t.buffer])},s.onmessage=e=>{const t=e.data;t&&"chunk"===t.type&&t.buffer instanceof ArrayBuffer&&this.opts?.onChunk(t.buffer)},r.connect(o).connect(i).connect(t.destination),"suspended"===t.state&&await t.resume().catch(()=>{}),this.cancelled)return s.terminate(),i.disconnect(),o.disconnect(),r.disconnect(),n.getTracks().forEach(e=>e.stop()),void await t.close().catch(()=>{});this.ctx=t,this.stream=n,this.source=r,this.gain=o,this.worklet=i,this.worker=s;const c=()=>{"visible"===document.visibilityState&&"suspended"===t.state&&t.resume().catch(()=>{})};document.addEventListener("visibilitychange",c),this.visibilityHandler=c,this.opts?.onLoadingChange?.(!1)}catch(e){Ft.error({message:"Mic capture failed",api_name:"voice-mic",error_message:e instanceof Error?e.message:String(e)}),t?.close().catch(()=>{}),n?.getTracks().forEach(e=>e.stop()),s?.terminate(),i?.disconnect(),o?.disconnect(),r?.disconnect(),this.cancelled||(this.opts?.onError?.(e),this.opts?.onLoadingChange?.(!1))}finally{this.opening=!1}})())}setMuted(e){const t=this.ctx,n=this.gain;t&&n&&(n.gain.setValueAtTime(e?0:1,t.currentTime),e&&this.worker?.postMessage({type:Gs}))}close(){this.cancelled=!0;const e=this.worker,t=this.worklet,n=this.gain,r=this.source,o=this.stream,i=this.ctx;e&&(e.postMessage({type:Gs}),e.terminate()),t?.disconnect(),n?.disconnect(),r?.disconnect(),o?.getTracks().forEach(e=>e.stop()),this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),i?.close().catch(()=>{}),this.ctx=null,this.stream=null,this.source=null,this.gain=null,this.worklet=null,this.worker=null,this.opts=null}}class ua{audio=null;timer=null;pendingPlay=null;pendingAction=null;unlock(){this.audio||(this.audio=new Audio(`${Ut()}${Hs}`),this.audio.loop=!0,this.audio.volume=.5,this.audio.preload="auto",this.audio.load());const e=this.audio.volume;this.audio.volume=0;const t=this.audio.play();t&&"function"==typeof t.then?t.then(()=>{this.pendingPlay?this.audio&&(this.audio.volume=e):(this.audio?.pause(),this.audio&&(this.audio.currentTime=0,this.audio.volume=e))}).catch(()=>{this.audio&&(this.audio.volume=e)}):(this.pendingPlay||(this.audio.pause(),this.audio.currentTime=0),this.audio.volume=e)}start(e){if(this.timer||this.audio&&!this.audio.paused)return;this.stop(),this.audio||(this.audio=new Audio(`${Ut()}${Hs}`),this.audio.loop=!0,this.audio.volume=.5);const t=Math.round(1e3*e)+300;this.timer=setTimeout(()=>{this.timer=null,this._doPlay()},t)}pause(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingPlay?this.pendingAction="pause":this.audio&&!this.audio.paused&&this.audio.pause()}resume(e=0){if(!this.audio)return;const t=Math.round(1e3*e)+300;this.timer=setTimeout(()=>{this.timer=null,this._doPlay()},t)}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.pendingPlay?this.pendingAction="stop":this.audio&&(this.audio.pause(),this.audio.currentTime=0)}destroy(){this.stop(),this.pendingAction=null,this.audio&&(this.audio.removeAttribute("src"),this.audio=null)}_doPlay(){this.pendingAction=null;const e=this.audio?.play();e instanceof Promise?(this.pendingPlay=e,e.then(()=>{this.pendingPlay=null;const e=this.pendingAction;this.pendingAction=null,"pause"===e?this.audio?.pause():"stop"===e&&this.audio&&(this.audio.pause(),this.audio.currentTime=0)}).catch(()=>{this.pendingPlay=null,this.pendingAction=null})):this.pendingPlay=null}}const da={createCapture:()=>new ca,createPlayer:()=>new ia,createThinkingSound:()=>new ua,devices:new class{async enumerate(){const e={microphones:[],speakers:[]};if(!navigator.mediaDevices?.enumerateDevices)return e;try{const e=await navigator.mediaDevices.enumerateDevices();let t=0,n=0;return{microphones:e.filter(e=>"audioinput"===e.kind).map(e=>({deviceId:e.deviceId,label:e.label||"Microphone "+ ++t})),speakers:e.filter(e=>"audiooutput"===e.kind).map(e=>({deviceId:e.deviceId,label:e.label||"Speaker "+ ++n}))}}catch{return e}}onChange(e){const t=navigator.mediaDevices;return t?.addEventListener?(t.addEventListener("devicechange",e),()=>t.removeEventListener("devicechange",e)):()=>{}}},requestMicPermission:async function(){try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),{granted:!0}}catch(e){return{granted:!1,error:e}}},requiresSoftwareAecMute:!1},la=d({...gs,auth:zn,chat:bs,conversations:ws,voice:na,indicator:Ln}),pa=_({reducer:la,middleware:e=>e({serializableCheck:Es}).prepend(Bn.middleware,aa.middleware).concat(ms)});var fa;fa=pa.dispatch,function(){const[e,t,n,r]=[ht,gt,mt,yt].map(e=>()=>fa(e())),o=()=>{"visible"===window.document.visibilityState?e():t()};if(!vt&&"undefined"!=typeof window&&window.addEventListener){let t=function(e){Object.entries(i).forEach(([t,n])=>{e?window.addEventListener(t,n,!1):window.removeEventListener(t,n)})};const i={[lt]:e,[ft]:o,[ut]:n,[dt]:r};t(!0),vt=!0}}(),Vt(()=>pa.getState().auth.accessToken),Ht(()=>pa.getState().auth.tokenExpiresAt);const ha=!1,ga=!0,ma=!0,ya=cn,va=!0,ba=(e,t)=>null===e?t:"true"===e,_a=({children:e,defaultSttImplementation:t=ya})=>{const{user:n}=Rs(),r=n?.id,o=Pn(),[i,s]=P(!1),[a,c]=P(ha),[u,d]=P(ga),[l,p]=P(ma),[f,h]=P(t),[g,m]=P(va);return C(()=>{let e=!1;return Promise.all([o.getItem(rn),o.getItem(nn),o.getItem(on),o.getItem(sn),o.getItem(an)]).then(([n,r,o,i,s])=>{if(e)return;var a;c(ba(n,ha)),d(ba(r,ga)),p(ba(o,ma)),h((a=i)===cn||"device"===a?a:t);const u=ba(s,va);m(u),Dt(u)}),()=>{e=!0}},[t,r,o]),Q(Ns.Provider,{value:{enableTts:i,setEnableTts:s,debugMode:a,setDebugMode:e=>{c(e),o.setItem(rn,String(e))},locationEnabled:u,setLocationEnabled:e=>{d(e),o.setItem(nn,String(e))},autoSendVoice:l,setAutoSendVoice:e=>{p(e),o.setItem(on,String(e))},sttImplementation:f,setSttImplementation:e=>{h(e),o.setItem(sn,e)},sendDiagnostics:g,setSendDiagnostics:e=>{m(e),Dt(e),o.setItem(an,String(e))}},children:e})},Sa=()=>{const e=F(Ns);if(!e)throw new Error("useChatSettings must be used within a <SettingsProvider>");return e},wa=A(void 0),Ta=A({}),Ea=({children:e,messageId:t,isDisabled:n=!1})=>{const[r,o]=P({});return Q(wa.Provider,{value:{messageContext:r,setMessageContext:o,updateMessageContext:(e,t)=>{o(n=>({...n,[e]:t}))},messageId:t},children:Q(Ta.Provider,{value:{messageId:t,isDisabled:n},children:e})})},ka=()=>{const e=F(wa);if(!e)throw new Error("useMessageContext must be used within MessageContextProvider");return e},Ia=()=>{const e=F(Ta);return e?.messageId},Fa=()=>{const e=F(Ta);return e?.isDisabled??!1};function Aa(){return"undefined"!=typeof window&&window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)").matches?mn:gn:mn}const xa=({children:e,orgId:t,fallbackThemeStyles:n,initialAppearanceMode:r=yn})=>{const{user:o}=Rs(),i=o?.id,s=Pn(),[a,c]=P(r),[u,d]=P(()=>r===yn?Aa():r);C(()=>{let e=!1;const t=un(i),n=tn;return(async()=>{const o=await s.getItem(t);if(i&&await s.removeItem(n),e)return;const a=((e,t)=>e===gn||e===mn||e===yn?e:t)(o,r);c(a),d(a===yn?Aa():a)})(),()=>{e=!0}},[i,s,r]),C(()=>{if(a!==yn)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),t=e=>{d(e.matches?mn:gn)};return d(e.matches?mn:gn),e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[a]);const l=t||void 0,{data:p,isLoading:f,error:h}=ds(l),g=p?.success?p.data??null:null,m=g?.themes?(u===gn?g.themes.light:g.themes.dark)??null:null,y=O(()=>!g&&n?n:function(e,t,n=mn){const r=function(e){return e===gn?Sn:_n}(n);if(!e||!t)return r;const o=t.surface?.chatInput?.border||t.surface?.input?.border,i=t.surface?.userMessage?.border,s=t.surface?.widget?.border;return{bgColor:t.surface?.chat?.background||r.bgColor,inputBgColor:t.surface?.chatInput?.background||t.surface?.input?.background||r.inputBgColor,sidebarBg:t.surface?.sideMenu?.background||r.sidebarBg,sidebarBorderColor:t.surface?.sideMenu?.iconColor||t.surface?.sideMenu?.icons||r.sidebarBorderColor,widgetBg:t.surface?.widget?.background||r.widgetBg,settingsGroupBg:t.surface?.settings?.groupBackground||r.settingsGroupBg,inputBorderStyle:o?.style||r.inputBorderStyle,inputBorderColor:o?.color?wn(o.color,o.opacity||100):r.inputBorderColor,inputBorderWidth:o?.width||r.inputBorderWidth,inputBorderOpacity:o?.opacity||100,widgetBorderStyle:s?.style||r.widgetBorderStyle,widgetBorderColor:s?.color?wn(s.color,s.opacity||100):r.widgetBorderColor,widgetBorderWidth:s?.width||r.widgetBorderWidth,widgetBorderOpacity:s?.opacity??r.widgetBorderOpacity,placeholderColor:t.surface?.chatInput?.placeholderColor||t.surface?.input?.placeholderColor||r.placeholderColor,primaryText:t.text?.primary||r.primaryText,secondaryText:t.text?.secondary||r.secondaryText,tertiaryText:t.text?.tertiary||r.tertiaryText,userMsgBg:t.surface?.userMessage?.background||r.userMsgBg,userMsgText:t.surface?.userMessage?.textColor||r.userMsgText,userMsgBorderStyle:i?.style||r.userMsgBorderStyle,userMsgBorderColor:i?.color?wn(i.color,i.opacity||100):r.userMsgBorderColor,userMsgBorderWidth:i?.width||r.userMsgBorderWidth,userMsgBorderOpacity:i?.opacity||0,sideMenuHeadings:t.surface?.sideMenu?.headingsColor||t.surface?.sideMenu?.headings||r.sideMenuHeadings,sideMenuText:t.surface?.sideMenu?.textContentColor||t.surface?.sideMenu?.textContent||r.sideMenuText,sideMenuIcon:t.surface?.sideMenu?.iconColor||t.surface?.sideMenu?.icons||r.sideMenuIcon,sideMenuProfile:t.surface?.sideMenu?.profileTextColor||t.surface?.sideMenu?.textProfile||r.sideMenuProfile,statusPrimary:{solid:t.status?.primary?.solid||r.statusPrimary.solid,background:t.status?.primary?.background||r.statusPrimary.background,text:t.status?.primary?.text||r.statusPrimary.text},statusSecondary:{solid:t.status?.secondary?.solid||r.statusSecondary.solid,background:t.status?.secondary?.background||r.statusSecondary.background,text:t.status?.secondary?.text||r.statusSecondary.text},statusSuccess:{solid:t.status?.success?.solid||r.statusSuccess.solid,background:t.status?.success?.background||r.statusSuccess.background,text:t.status?.success?.text||r.statusSuccess.text},statusDanger:{solid:t.status?.danger?.solid||r.statusDanger.solid,background:t.status?.danger?.background||r.statusDanger.background,text:t.status?.danger?.text||r.statusDanger.text},statusWarning:{solid:t.status?.warning?.solid||r.statusWarning.solid,background:t.status?.warning?.background||r.statusWarning.background,text:t.status?.warning?.text||r.statusWarning.text},statusInfo:{solid:t.status?.info?.solid||r.statusInfo.solid,background:t.status?.info?.background||r.statusInfo.background,text:t.status?.info?.text||r.statusInfo.text},statusDiscovery:{solid:t.status?.discovery?.solid||r.statusDiscovery.solid,background:t.status?.discovery?.background||r.statusDiscovery.background,text:t.status?.discovery?.text||r.statusDiscovery.text},switchCheckedColor:t.status?.primary?.solid||r.switchCheckedColor,switchUncheckedColor:t.surface?.chatInput?.background||r.switchUncheckedColor,fontFamily:Tn(e.typography?.fontFamily,r),fontFamilyMono:En(e.typography?.fontFamilyMono,r),fontSize:14,borderRadius:kn(e.cornerRadius,r),cornerRadiusMode:In(e.cornerRadius),chatInputPlaceholder:e.startScreen.inputPlaceholder}}(g,m,u),[g,m,u,n]),v=g?.orbPosition??"foreground",b=x(e=>{c(e);const t=un(i);s.setItem(t,e),i&&s.removeItem(tn),d(e===yn?Aa():e)},[s,i]),_={theme:u,setTheme:b,appearanceMode:a,isLoading:f,error:h?new Error("Failed to fetch branding"):null,currentThemeColors:m,themeStyles:y,orbPosition:v};return Q(Fn.Provider,{value:_,children:e})},Pa=({value:e,children:t})=>Q(sa.Provider,{value:e??da,children:t}),Ca=({children:e,protocolType:t})=>{const n=t||"mtx",r=O(()=>function(e,t){switch(e){case"mtx":return new Ps(t);case"agui":return new Os(t);default:throw new Error(`Unknown protocol type: "${e}". Supported types: mtx, agui`)}}(n,function(e={}){return{getAuthToken:()=>is(),getCustomHeaders:()=>Kt(),onAuthExpired:e.onAuthExpired,getStreamUrl:e=>Jt.CONVERSATION_STREAM(e),getInitialStreamUrl:e=>Jt.CONVERSATION_START(e),getDebugUrl:()=>Jt.DEBUG,ensureFreshToken:async()=>{pn($t())&&await(Wt()?.())},forceRefreshToken:async()=>Boolean(await(Wt()?.()))}}({onAuthExpired:()=>pa.dispatch(qn())})),[n]),o=O(()=>({adapter:r,protocolType:n}),[r,n]);return Q(Fs.Provider,{value:o,children:e})},Oa=({value:e,children:t,fallback:n,extraHydrations:r})=>{!function(e){Cn=e}(e);const o=T(),i=void 0!==n,[s,a]=P(!i);return C(()=>{let t=!1;const n=[o(jn(e))];if(r)for(const t of r)n.push(Promise.resolve(t(e,o)).catch(e=>{Ft.error({message:"StorageProvider hydration step failed",component:"StorageProvider",error_message:e instanceof Error?e.message:String(e)})}));return Promise.all(n).finally(()=>{t||i&&a(!0)}),()=>{t=!0}},[]),Q(xn.Provider,{value:e,children:i&&!s?Q(j,{children:n}):t})},Ra=({token:e,user:t,children:n})=>{const r=M(null);return e&&e!==r.current&&(r.current=e,pa.dispatch(Nn({accessToken:e,expiresIn:Math.floor(Date.now()/1e3)+3600,...t&&{user:{id:"",email:t.email||"",name:t.name}}}))),Q(j,{children:n})},Ma=({children:e})=>Q(qs.Provider,{value:Qs(),children:e}),Na=({children:e,callbacks:t})=>Q(js.Provider,{value:t,children:e}),Da=({baseUrl:e,customHeaders:t,token:n,user:r,protocol:o="mtx",paymentProvider:i,onConversationChange:s,onConversationTitleChange:a,onMessagesChange:c,onLogoutRequested:u,onSessionExpired:d,storage:l,storageFallback:p,extraHydrations:f,orgId:h,initialThemeStyles:g,initialAppearanceMode:m,audioPlatform:y,networkMonitor:v,children:b})=>{(e=>{Qt=e.baseUrl,jt=e.customHeaders||{},qt=e.paymentProvider})({baseUrl:e,customHeaders:t,paymentProvider:i}),(e=>{Bt=e})(d??null);let _=Q(Ra,{token:n,user:r,children:Q(Ca,{protocolType:o,children:Q(Ma,{children:Q(Na,{callbacks:{onConversationChange:s,onConversationTitleChange:a,onMessagesChange:c,onLogoutRequested:u},children:Q(xa,{orgId:h,fallbackThemeStyles:g,initialAppearanceMode:m,children:Q(Pa,{value:y,children:b})})})})})});return v&&(_=Q(Rn.Provider,{value:v,children:_})),Q(I,{store:pa,children:l?Q(Oa,{value:l,fallback:p,extraHydrations:f,children:_}):_})},qa=q(()=>import("./PaymentProviderHost-BeHcCUZx.js")),Qa=e=>Q(D,{fallback:null,children:Q(qa,{...e})}),ja=()=>import("./PaymentProviderHost-BeHcCUZx.js").catch(()=>{});export{xa as B,Da as C,dn as D,Ea as M,Qa as P,_a as S,Lt as Z,Oa as a,Ms as b,ja as c,An as d,Fa as e,Ia as f,Sa as g,Us as h,Ks as m,zs as p,la as r,pa as s,ka as u,Ws as y};
@@ -1 +0,0 @@
1
- import{r as e,D as t,g as r,u as s,d as i}from"./diag-api-BepQpXrk.js";import{t as o,h as n,E as a}from"./ExportResult-vKWGlZZX.js";import{A as c,a as h,b as u,d as l}from"./ResourceImpl-DPkc_ob9.js";import{S as d,a as _}from"./NoopLogger-aeNt0r6v.js";function g(e){return Symbol.for(e)}class p{constructor(e){const t=this;t._currentContext=e?new Map(e):new Map,t.getValue=e=>t._currentContext.get(e),t.setValue=(e,r)=>{const s=new p(t._currentContext);return s._currentContext.set(e,r),s},t.deleteValue=e=>{const r=new p(t._currentContext);return r._currentContext.delete(e),r}}}const m=new p;class f{}class x{addCallback(e){}removeCallback(e){}}const b=new class{constructor(){}createGauge(e,t){return y}createHistogram(e,t){return w}createCounter(e,t){return v}createUpDownCounter(e,t){return S}createObservableGauge(e,t){return L}createObservableCounter(e,t){return C}createObservableUpDownCounter(e,t){return T}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}},v=new class extends f{add(e,t){}},y=new class extends f{record(e,t){}},w=new class extends f{record(e,t){}},S=new class extends f{add(e,t){}},C=new class extends x{},L=new class extends x{},T=new class extends x{},E="context",R=new class{active(){return m}with(e,t,r,...s){return t.call(r,...s)}bind(e,t){return t}enable(){return this}disable(){return this}};class O{constructor(){}static getInstance(){return this._instance||(this._instance=new O),this._instance}setGlobalContextManager(r){return e(E,r,t.instance())}active(){return this._getContextManager().active()}with(e,t,r,...s){return this._getContextManager().with(e,t,r,...s)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return r(E)||R}disable(){this._getContextManager().disable(),s(E,t.instance())}}var P,A;(A=P||(P={}))[A.NONE=0]="NONE",A[A.SAMPLED=1]="SAMPLED";const N="0000000000000000",F="00000000000000000000000000000000",M={traceId:F,spanId:N,traceFlags:P.NONE};class I{constructor(e=M){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}const B=g("OpenTelemetry Context Key SPAN");function j(e){return e.getValue(B)||void 0}function D(){return j(O.getInstance().active())}function z(e,t){return e.setValue(B,t)}function k(e){return e.deleteValue(B)}function U(e,t){return z(e,new I(t))}function $(e){var t;return null===(t=j(e))||void 0===t?void 0:t.spanContext()}const V=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function Q(e,t){if("string"!=typeof e||e.length!==t)return!1;let r=0;for(let t=0;t<e.length;t+=4)r+=(0|V[e.charCodeAt(t)])+(0|V[e.charCodeAt(t+1)])+(0|V[e.charCodeAt(t+2)])+(0|V[e.charCodeAt(t+3)]);return r===t}function H(e){return Q(r=e.traceId,32)&&r!==F&&Q(t=e.spanId,16)&&t!==N;var t,r}function G(e){return new I(e)}const K=O.getInstance();class W{startSpan(e,t,r=K.active()){if(Boolean(null==t?void 0:t.root))return new I;const s=r&&$(r);return null!==(i=s)&&"object"==typeof i&&"spanId"in i&&"string"==typeof i.spanId&&"traceId"in i&&"string"==typeof i.traceId&&"traceFlags"in i&&"number"==typeof i.traceFlags&&H(s)?new I(s):new I;var i}startActiveSpan(e,t,r,s){let i,o,n;if(arguments.length<2)return;2===arguments.length?n=t:3===arguments.length?(i=t,n=r):(i=t,o=r,n=s);const a=null!=o?o:K.active(),c=this.startSpan(e,i,a),h=z(a,c);return K.with(h,n,void 0,c)}}const q=new W;class J{constructor(e,t,r,s){this._provider=e,this.name=t,this.version=r,this.options=s}startSpan(e,t,r){return this._getTracer().startSpan(e,t,r)}startActiveSpan(e,t,r,s){const i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):q}}const X=new class{getTracer(e,t,r){return new W}};class Y{getTracer(e,t,r){var s;return null!==(s=this.getDelegateTracer(e,t,r))&&void 0!==s?s:new J(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:X}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,r){var s;return null===(s=this._delegate)||void 0===s?void 0:s.getTracer(e,t,r)}}const Z=O.getInstance(),ee="trace";class te{constructor(){this._proxyTracerProvider=new Y,this.wrapSpanContext=G,this.isSpanContextValid=H,this.deleteSpan=k,this.getSpan=j,this.getActiveSpan=D,this.getSpanContext=$,this.setSpan=z,this.setSpanContext=U}static getInstance(){return this._instance||(this._instance=new te),this._instance}setGlobalTracerProvider(r){const s=e(ee,this._proxyTracerProvider,t.instance());return s&&this._proxyTracerProvider.setDelegate(r),s}getTracerProvider(){return r(ee)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){s(ee,t.instance()),this._proxyTracerProvider=new Y}}const re=te.getInstance(),se=g("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function ie(e){return e.setValue(se,!0)}function oe(e){try{(e=>{i.error(function(e){return"string"==typeof e?e:JSON.stringify(function(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const s=r[e];s&&(t[e]=String(s))}),r=Object.getPrototypeOf(r);return t}(e))}(e))})(e)}catch{}}class ne extends Error{constructor(e){super(e),Object.setPrototypeOf(this,ne.prototype)}}class ae{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}class ce{_isCalled=!1;_deferred=new ae;_callback;_that;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}function he(e){return ue(e,new WeakSet)}function ue(e,t){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e||e instanceof Uint8Array||"object"==typeof e&&!t.has(e)&&(t.add(e),Array.isArray(e)?e.every(e=>ue(e,t)):(e.constructor===Object||void 0===e.constructor)&&Object.values(e).every(e=>ue(e,t)))}class le{hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;_eventName;_attributesCount=0;_droppedAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get eventName(){return this._eventName}set eventName(e){this._isLogRecordReadonly()||(this._eventName=e)}get droppedAttributesCount(){return this._droppedAttributesCount}constructor(e,t,r){const{timestamp:s,observedTimestamp:i,eventName:n,severityNumber:a,severityText:c,body:h,attributes:u={},exception:l,context:d}=r,_=Date.now();if(this.hrTime=o(s??_),this.hrTimeObserved=o(i??_),d){const e=re.getSpanContext(d);e&&H(e)&&(this.spanContext=e)}this.severityNumber=a,this.severityText=c,this.body=h,this.resource=e.resource,this.instrumentationScope=t,this._logRecordLimits=e.logRecordLimits,this._eventName=n,this.setAttributes(u),null!=l&&this._setException(l)}setAttribute(e,t){if(this._isLogRecordReadonly())return this;if(0===e.length)return i.warn(`Invalid attribute key: ${e}`),this;if(!he(t))return i.warn(`Invalid attribute value set for key: ${e}`),this;const r=!Object.prototype.hasOwnProperty.call(this.attributes,e);return r&&this._attributesCount>=this._logRecordLimits.attributeCountLimit?(this._droppedAttributesCount++,1===this._droppedAttributesCount&&i.warn("Dropping extra attributes."),this):(this.attributes[e]=this._truncateToSize(t),r&&this._attributesCount++,this)}setAttributes(e){for(const[t,r]of Object.entries(e))this.setAttribute(t,r);return this}setBody(e){return this.body=e,this}setEventName(e){return this.eventName=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){const t=this._logRecordLimits.attributeValueLengthLimit;if(t<=0)return i.warn(`Attribute value limit must be positive, got ${t}`),e;if(null==e)return e;if("string"==typeof e)return this._truncateToLimitUtil(e,t);if(e instanceof Uint8Array)return e;if(Array.isArray(e))return e.map(e=>this._truncateToSize(e));if("object"==typeof e){const t={};for(const[r,s]of Object.entries(e))t[r]=this._truncateToSize(s);return t}return e}_setException(e){let t=!1;if("string"==typeof e||"number"==typeof e)Object.hasOwn(this.attributes,c)||this.setAttribute(c,String(e)),t=!0;else if(e&&"object"==typeof e){const r=e;r.code?(Object.hasOwn(this.attributes,h)||this.setAttribute(h,r.code.toString()),t=!0):r.name&&(Object.hasOwn(this.attributes,h)||this.setAttribute(h,r.name),t=!0),r.message&&(Object.hasOwn(this.attributes,c)||this.setAttribute(c,r.message),t=!0),r.stack&&(Object.hasOwn(this.attributes,u)||this.setAttribute(u,r.stack),t=!0)}t||i.warn(`Failed to record an exception ${e}`)}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_isLogRecordReadonly(){return this._isReadonly&&i.warn("Can not execute the operation on emitted log record"),this._isReadonly}}class de{instrumentationScope;_sharedState;_loggerConfig;constructor(e,t){this.instrumentationScope=e,this._sharedState=t,this._loggerConfig=this._sharedState.getLoggerConfig(this.instrumentationScope)}emit(e){const t=e.context||Z.active();if(!this.enabled(e))return;const r=new le(this._sharedState,this.instrumentationScope,{context:t,...e});this._sharedState.loggerMetrics.emitLog(),this._sharedState.activeProcessor.onEmit(r,t),r._makeReadonly()}enabled(e){const t=this._loggerConfig;if(t.disabled)return!1;const r=e?.severityNumber;if("number"==typeof r&&r!==d.UNSPECIFIED&&r<t.minimumSeverity)return!1;const s=e?.context||Z.active();if(t.traceBased){const e=re.getSpanContext(s);if(e&&H(e)&&(e.traceFlags&P.SAMPLED)!==P.SAMPLED)return!1}const i={context:s,instrumentationScope:this.instrumentationScope,severityNumber:e?.severityNumber,eventName:e?.eventName};for(const e of this._sharedState.processors)if(!e.enabled||e.enabled(i))return!0;return!1}}class _e{forceFlush(){return Promise.resolve()}onEmit(e,t){}shutdown(){return Promise.resolve()}enabled(e){return!1}}class ge{processors;forceFlushTimeoutMillis;constructor(e,t){this.processors=e,this.forceFlushTimeoutMillis=t}async forceFlush(){const e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(t=>function(e,t){let r;const s=new Promise(function(e,s){r=setTimeout(function(){s(new ne("Operation timed out."))},t)});return Promise.race([e,s]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}(t.forceFlush(),e)))}onEmit(e,t){this.processors.forEach(r=>r.onEmit(e,t))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}enabled(e){for(const t of this.processors)if(!t.enabled||t.enabled(e))return!0;return!1}}class pe{createdLogs;constructor(e){this.createdLogs=e.createCounter("otel.sdk.log.created",{unit:"{log_record}",description:"The number of logs submitted to enabled SDK Loggers."})}emitLog(){this.createdLogs.add(1)}}const me={disabled:!1,minimumSeverity:d.UNSPECIFIED,traceBased:!1},fe=()=>({...me});class xe{loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggerMetrics;_loggerConfigurator;_loggerConfigs=new Map;constructor(e,t,r,s,i,o){this.resource=e,this.forceFlushTimeoutMillis=t,this.logRecordLimits=r,this.processors=s,s.length>0?(this.registeredLogRecordProcessors=s,this.activeProcessor=new ge(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new _e,this._loggerConfigurator=i??fe;const n=o?o.getMeter("@opentelemetry/sdk-logs","0.218.0"):b;this.loggerMetrics=new pe(n)}getLoggerConfig(e){const t=`${(r=e).name}@${r.version||""}:${r.schemaUrl||""}`;var r;let s=this._loggerConfigs.get(t);return s||(s=this._loggerConfigurator(e),this._loggerConfigs.set(t,s),s)}}class be{_shutdownOnce;_sharedState;constructor(e={}){const t={resource:e.resource??l(),forceFlushTimeoutMillis:e.forceFlushTimeoutMillis??3e4,logRecordLimits:{attributeCountLimit:e.logRecordLimits?.attributeCountLimit??128,attributeValueLengthLimit:e.logRecordLimits?.attributeValueLengthLimit??1/0},loggerConfigurator:e.loggerConfigurator??fe,processors:e.processors??[],meterProvider:e.meterProvider};this._sharedState=new xe(t.resource,t.forceFlushTimeoutMillis,t.logRecordLimits,t.processors,t.loggerConfigurator,t.meterProvider),this._shutdownOnce=new ce(this._shutdown,this)}getLogger(e,t,r){if(this._shutdownOnce.isCalled)return i.warn("A shutdown LoggerProvider cannot provide a Logger"),_;e||i.warn("Logger requested without instrumentation scope name.");const s=e||"unknown",o=`${s}@${t||""}:${r?.schemaUrl||""}`;return this._sharedState.loggers.has(o)||this._sharedState.loggers.set(o,new de({name:s,version:t,schemaUrl:r?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(o)}forceFlush(){return this._shutdownOnce.isCalled?(i.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(i.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}}class ve{export(e,t){this._sendLogRecords(e,t)}async forceFlush(){}async shutdown(){}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,timestamp:n(e.hrTime),traceId:e.spanContext?.traceId,spanId:e.spanContext?.spanId,traceFlags:e.spanContext?.traceFlags,severityText:e.severityText,severityNumber:e.severityNumber,eventName:e.eventName,body:e.body,attributes:e.attributes}}_sendLogRecords(e,t){for(const t of e)console.dir(this._exportInfo(t),{depth:3});t?.({code:a.SUCCESS})}}class ye{_exporter;_shutdownOnce;_unresolvedExports;constructor(e){this._exporter=e,this._shutdownOnce=new ce(this._shutdown,this),this._unresolvedExports=new Set}onEmit(e,t){if(this._shutdownOnce.isCalled)return;const r=()=>{return(t=this._exporter,r=[e],new Promise(e=>{Z.with(ie(Z.active()),()=>{t.export(r,e)})})).then(e=>{e.code!==a.SUCCESS&&oe(e.error??new Error(`SimpleLogRecordProcessor: log record export failed (status ${e})`))}).catch(oe);var t,r};if(e.resource.asyncAttributesPending){const t=e.resource.waitForAsyncAttributes?.().then(()=>(this._unresolvedExports.delete(t),r()),oe);null!=t&&this._unresolvedExports.add(t)}else r()}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports))}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}class we{_finishedLogRecords=[];_stopped=!1;export(e,t){if(this._stopped)return t({code:a.FAILED,error:new Error("Exporter has been stopped")});this._finishedLogRecords.push(...e),t({code:a.SUCCESS})}async shutdown(){this._stopped=!0,this.reset()}async forceFlush(){}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}}class Se{_exportCompleted;_exportScheduledPromise;_exportScheduledResolve;constructor(e,t,r){this._exportScheduledPromise=new Promise(e=>{this._exportScheduledResolve=e}),this._exportCompleted=this._executeExport(e,t,r)}get exportCompleted(){return this._exportCompleted}get exportScheduled(){return this._exportScheduledPromise}async _executeExport(e,t,r){try{await async function(e){const t=[];for(let r=0,s=e.length;r<s;r++){const s=e[r];s.resource.asyncAttributesPending&&s.resource.waitForAsyncAttributes&&t.push(s.resource.waitForAsyncAttributes())}null!=t&&t.length>0&&await Promise.all(t)}(t),await Z.with(ie(Z.active()),async()=>this._exportWithTimeout(e,t,r))}catch(e){oe(e),this._exportScheduledResolve()}}async _exportWithTimeout(e,t,r){return new Promise((s,i)=>{const o=setTimeout(()=>{i(new Error("Timeout"))},r);e.export(t,e=>{clearTimeout(o),e.code===a.SUCCESS?s():i(e.error??new Error("BatchLogRecordProcessor: log record export failed"))}),this._exportScheduledResolve()})}}class Ce{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_currentExport=null;_finishedLogRecords=[];_timer;_shutdownOnce;_flushing=!1;constructor(e,t){this._exporter=e,this._maxExportBatchSize=t?.maxExportBatchSize??512,this._maxQueueSize=t?.maxQueueSize??2048,this._scheduledDelayMillis=t?.scheduledDelayMillis??5e3,this._exportTimeoutMillis=t?.exportTimeoutMillis??3e4,this._shutdownOnce=new ce(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(i.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}onEmit(e){this._shutdownOnce.isCalled||this._addToBuffer(e)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}_addToBuffer(e){this._finishedLogRecords.length>=this._maxQueueSize||(this._finishedLogRecords.push(e),this._maybeStartTimer())}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}async _flushAll(){if(this._flushing)return;this._flushing=!0;let e=this._finishedLogRecords;for(this._finishedLogRecords=[],this._clearTimer(),null!==this._currentExport&&(await this._exporter.forceFlush(),await this._currentExport.exportCompleted,this._currentExport=null);e.length>0;){let t;e.length<=this._maxExportBatchSize?(t=e,e=[]):t=e.splice(0,this._maxExportBatchSize);const r=new Se(this._exporter,t,this._exportTimeoutMillis);this._currentExport=r;try{await r.exportScheduled,await this._exporter.forceFlush(),await r.exportCompleted}catch(e){oe(e)}finally{this._currentExport=null}}this._flushing=!1,this._maybeStartTimer()}_extractBatch(){if(0===this._finishedLogRecords.length)return null;if(this._finishedLogRecords.length<=this._maxExportBatchSize){const e=this._finishedLogRecords;return this._finishedLogRecords=[],e}return this._finishedLogRecords.splice(0,this._maxExportBatchSize)}_exportOneBatch(){this._clearTimer();const e=this._extractBatch();if(null===e)return;const t=new Se(this._exporter,e,this._exportTimeoutMillis);this._currentExport=t,t.exportCompleted.then(()=>{this._currentExport=null,this._maybeStartTimer()}).catch(e=>{this._currentExport=null,oe(e),this._maybeStartTimer()})}_maybeStartTimer(){this._shutdownOnce.isCalled||this._flushing||0!==this._finishedLogRecords.length&&null===this._currentExport&&(this._finishedLogRecords.length>=this._maxExportBatchSize?this._exportOneBatch():void 0===this._timer&&(this._timer=setTimeout(()=>{this._timer=void 0,this._exportOneBatch()},this._scheduledDelayMillis),"number"!=typeof this._timer&&this._timer.unref()))}_clearTimer(){void 0!==this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}class Le extends Ce{_visibilityChangeListener;_pageHideListener;constructor(e,t){super(e,t),this._onInit(t)}onShutdown(){"undefined"!=typeof document&&(this._visibilityChangeListener&&document.removeEventListener("visibilitychange",this._visibilityChangeListener),this._pageHideListener&&document.removeEventListener("pagehide",this._pageHideListener))}_onInit(e){!0!==e?.disableAutoFlushOnDocumentHide&&"undefined"!=typeof document&&(this._visibilityChangeListener=()=>{"hidden"===document.visibilityState&&this.forceFlush()},this._pageHideListener=()=>{this.forceFlush()},document.addEventListener("visibilitychange",this._visibilityChangeListener),document.addEventListener("pagehide",this._pageHideListener))}}const Te={disabled:!1,minimumSeverity:d.UNSPECIFIED,traceBased:!1};function Ee(e){return t=>{const r=t.name;for(const{pattern:t,config:s}of e)if(Re(r,t))return{disabled:s.disabled??Te.disabled,minimumSeverity:s.minimumSeverity??Te.minimumSeverity,traceBased:s.traceBased??Te.traceBased};return{...Te}}}function Re(e,t){if(t===e)return!0;if(t.includes("*")){const r=t.split("*").map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${r}$`).test(e)}return!1}export{Le as BatchLogRecordProcessor,ve as ConsoleLogRecordExporter,we as InMemoryLogRecordExporter,be as LoggerProvider,ye as SimpleLogRecordProcessor,Ee as createLoggerConfigurator};
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./diag-api-DsVI4ljU.cjs"),t=require("./ExportResult-eb4TcH7k.cjs");class r{_delegate;constructor(e){this._delegate=e}export(e,t){this._delegate.export(e,t)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class n extends Error{code;name="OTLPExporterError";data;constructor(e,t,r){super(e),this.data=r,this.code=t}}function s(e){if(Number.isFinite(e)&&e>0)return e;throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${e}')`)}function o(e,t,r){return{timeoutMillis:s(e.timeoutMillis??t.timeoutMillis??r.timeoutMillis),concurrencyLimit:e.concurrencyLimit??t.concurrencyLimit??r.concurrencyLimit,compression:e.compression??t.compression??r.compression}}class i{_concurrencyLimit;_sendingPromises=[];constructor(e){this._concurrencyLimit=e}pushPromise(e){if(this.hasReachedLimit())throw new Error("Concurrency Limit reached");this._sendingPromises.push(e);const t=()=>{const t=this._sendingPromises.indexOf(e);this._sendingPromises.splice(t,1)};e.then(t,t)}hasReachedLimit(){return this._sendingPromises.length>=this._concurrencyLimit}async awaitAll(){await Promise.all(this._sendingPromises)}}function a(e){return new i(e.concurrencyLimit)}class u{_diagLogger;_transport;_serializer;_responseHandler;_promiseQueue;_timeout;constructor(t,r,n,s,o){this._transport=t,this._serializer=r,this._responseHandler=n,this._promiseQueue=s,this._timeout=o,this._diagLogger=e.diag.createComponentLogger({namespace:"OTLPExportDelegate"})}export(e,r){if(this._diagLogger.debug("items to be sent",e),this._promiseQueue.hasReachedLimit())return void r({code:t.ExportResultCode.FAILED,error:new Error("Concurrent export limit reached")});const s=this._serializer.serializeRequest(e);null!=s?this._promiseQueue.pushPromise(this._transport.send(s,this._timeout).then(e=>{if("success"!==e.status)r("failure"===e.status&&e.error?{code:t.ExportResultCode.FAILED,error:e.error}:"retryable"===e.status?{code:t.ExportResultCode.FAILED,error:e.error??new n("Export failed with retryable status")}:{code:t.ExportResultCode.FAILED,error:new n("Export failed with unknown error")});else{if(null!=e.data)try{this._responseHandler.handleResponse(this._serializer.deserializeResponse(e.data))}catch(t){this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?",t,e.data)}r({code:t.ExportResultCode.SUCCESS})}},e=>r({code:t.ExportResultCode.FAILED,error:e}))):r({code:t.ExportResultCode.FAILED,error:new Error("Nothing to send")})}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started"),await this.forceFlush(),this._transport.shutdown()}}function c(e,t){return Object.keys(e).map(r=>l(r,e[r],t))}function l(e,t,r){return{key:e,value:d(t,r)}}function d(e,t){const r=typeof e;if("string"===r)return{stringValue:e};if("number"===r)return Number.isInteger(e)?{intValue:e}:{doubleValue:e};if("boolean"===r)return{boolValue:e};if(e instanceof Uint8Array)return{bytesValue:t.encodeUint8Array(e)};if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=d(e[n],t);return{arrayValue:{values:r}}}if("object"===r&&null!=e){const r=Object.keys(e),n=new Array(r.length);for(let s=0;s<r.length;s++)n[s]={key:r[s],value:d(e[r[s]],t)};return{kvlistValue:{values:n}}}return{}}function p(e,t){const r=function(e){const t=new Map;for(const r of e){const{resource:e,instrumentationScope:{name:n,version:s="",schemaUrl:o=""}}=r;let i=t.get(e);i||(i=new Map,t.set(e,i));const a=`${n}@${s}:${o}`;let u=i.get(a);u||(u=[],i.set(a,u)),u.push(r)}return t}(e);return Array.from(r,([e,r])=>{const n=function(e,t){const r={attributes:c(e.attributes,t),droppedAttributesCount:0},n=e.schemaUrl;return n&&""!==n&&(r.schemaUrl=n),r}(e,t);return{resource:n,scopeLogs:Array.from(r,([,e])=>{return{scope:(r=e[0].instrumentationScope,{name:r.name,version:r.version}),logRecords:e.map(e=>function(e,t){return{timeUnixNano:t.encodeHrTime(e.hrTime),observedTimeUnixNano:t.encodeHrTime(e.hrTimeObserved),severityNumber:e.severityNumber,severityText:e.severityText,body:d(e.body,t),eventName:e.eventName,attributes:h(e.attributes,t),droppedAttributesCount:e.droppedAttributesCount,flags:e.spanContext?.traceFlags,traceId:t.encodeOptionalSpanContext(e.spanContext?.traceId),spanId:t.encodeOptionalSpanContext(e.spanContext?.spanId)}}(e,t)),schemaUrl:e[0].instrumentationScope.schemaUrl};var r}),schemaUrl:n.schemaUrl}})}function h(e,t){return Object.keys(e).map(r=>l(r,e[r],t))}function m(e){return e}const g={encodeHrTime:"undefined"!=typeof BigInt?function(e){return function(e){const t=BigInt(1e9);return BigInt(Math.trunc(e[0]))*t+BigInt(Math.trunc(e[1]))}(e).toString()}:t.hrTimeToNanoseconds,encodeSpanContext:m,encodeOptionalSpanContext:m,encodeUint8Array:e=>{if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");const t=new Array(e.length);for(let r=0;r<e.length;r++)t[r]=String.fromCharCode(e[r]);return btoa(t.join(""))}},f={serializeRequest:e=>{const t={resourceLogs:p(e,g)};return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:t=>{if(0===t.length)return{};const r=new TextDecoder;try{return JSON.parse(r.decode(t))}catch(t){return e.diag.warn(`Failed to parse logs export response: ${t.message}. Returning empty response`),{}}}};function y(){return.4*Math.random()-.2}class w{_transport;constructor(e){this._transport=e}retry(e,t,r){return new Promise((n,s)=>{setTimeout(()=>{this._transport.send(e,t).then(n,s)},r)})}async send(t,r){let n=5,s=1e3;const o=Date.now()+r;let i=await this._transport.send(t,r);for(;"retryable"===i.status&&n>0;){n--;const r=Math.max(Math.min(s*(1+y()),5e3),0);s*=1.5;const a=i.retryInMillis??r,u=o-Date.now();if(a>u)return e.diag.info(`Export retry time ${Math.round(a)}ms exceeds remaining timeout ${Math.round(u)}ms, not retrying further.`),i;e.diag.verbose(`Scheduling export retry in ${Math.round(a)}ms`),i=await this.retry(t,u,a)}return"success"===i.status?e.diag.verbose(`Export succeeded after ${5-n} retry attempts.`):e.diag.info("retryable"===i.status?"Export failed after maximum retry attempts (5).":`Export failed with non-retryable error: ${i.error}`),i}shutdown(){return this._transport.shutdown()}}let b=0,x=0;class _{_parameters;constructor(e){this._parameters=e}async send(t,r){const n=new AbortController,s=setTimeout(()=>n.abort(),r);let o=globalThis.fetch;"function"==typeof o.__original&&(o=o.__original);const i=t.byteLength,a=b+i>61440,u=!(a||x>=9);if(u)b+=i,x++;else{const t=a?"size limit":"count limit";e.diag.debug(`keepalive disabled: ${(i/1024).toFixed(1)}KB payload, ${x} pending (${t})`)}try{const r=new URL(this._parameters.url),s=await o(r.href,{method:"POST",headers:await this._parameters.headers(),body:t,signal:n.signal,keepalive:u,mode:globalThis.location?globalThis.location.origin===r.origin?"same-origin":"cors":"no-cors"});return s.status>=200&&s.status<=299?(e.diag.debug(`export response success (status: ${s.status})`),{status:"success"}):429===(c=s.status)||502===c||503===c||504===c?(e.diag.warn(`export response retryable (status: ${s.status})`),{status:"retryable",retryInMillis:function(e){if(null==e)return;const t=Number.parseInt(e,10);if(Number.isInteger(t))return t>0?1e3*t:-1;const r=new Date(e).getTime()-Date.now();return r>=0?r:0}(s.headers.get("Retry-After"))}):(e.diag.error(`export response failure (status: ${s.status})`),{status:"failure",error:new Error(`Fetch request failed with non-retryable status ${s.status}`)})}catch(t){return function(e){return e instanceof TypeError&&!e.cause}(t)?(e.diag.warn(`export request retryable (network error: ${t})`),{status:"retryable",error:new Error("Fetch request encountered a network error",{cause:t})}):(e.diag.error(`export request failure (error: ${t})`),{status:"failure",error:new Error("Fetch request errored",{cause:t})})}finally{clearTimeout(s),u&&(b-=i,x--)}var c}shutdown(){}}function E(e){if(null!=e)try{const t=globalThis.location?.href;return new URL(e,t).href}catch{throw new Error(`Configuration: Could not parse user-provided export URL: '${e}'`)}}function L(e){return"function"==typeof e.headers?e.headers:function(e){if(null!=e)return async()=>e}(e.headers)}exports.OTLPLogExporter=class extends r{constructor(t={}){super(function(t,r){return function(t,r){return function(t,r,n){return s={transport:n,serializer:r,promiseHandler:a(t)},o={timeout:t.timeoutMillis},new u(s.transport,s.serializer,{handleResponse(t){null!=t&&function(e){return Object.prototype.hasOwnProperty.call(e,"partialSuccess")}(t)&&null!=t.partialSuccess&&0!==Object.keys(t.partialSuccess).length&&e.diag.warn("Received Partial Success response:",JSON.stringify(t.partialSuccess))}},s.promiseHandler,o.timeout);var s,o}(t,r,function(e){return new w(e.transport)}({transport:(n=t,new _(n))}));var n}(function(t){return i={url:t.url,timeoutMillis:t.timeoutMillis,headers:L(t),concurrencyLimit:t.concurrencyLimit},a={},u=function(e,t){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none",headers:async()=>e,url:"http://localhost:4318/"+t}}({"Content-Type":"application/json"},"v1/logs"),{...o(i,a,u),headers:(r=i.headers,n=a.headers,s=u.headers,async()=>{const t={...await s()},o={};return null!=n&&Object.assign(o,await n()),null!=r&&Object.assign(o,function(t){const r={};return Object.entries(t??{}).forEach(([t,n])=>{void 0!==n?r[t]=String(n):e.diag.warn(`Header "${t}" has invalid value (${n}) and will be ignored`)}),r}(await r())),Object.assign(o,t)}),url:E(i.url)??a.url??u.url};var r,n,s,i,a,u}(t),r)}(t,f))}};