db-studio 1.9.4 → 1.9.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/index.js +20 -20
- package/dist/index.js.map +1 -1
- package/dist/web-dist/assets/_pathlessLayout-BByrt-IV.js +2 -0
- package/dist/web-dist/assets/{_pathlessLayout-DhK1pVQZ.js.map → _pathlessLayout-BByrt-IV.js.map} +1 -1
- package/dist/web-dist/assets/{_queryId-PHL0xcKj.js → _queryId-cyxa5wMS.js} +1 -1
- package/dist/web-dist/assets/{_queryId-PHL0xcKj.js.map → _queryId-cyxa5wMS.js.map} +1 -1
- package/dist/web-dist/assets/{_table-Ud147_vw.js → _table-B0yPxctF.js} +1 -1
- package/dist/web-dist/assets/{_table-Ud147_vw.js.map → _table-B0yPxctF.js.map} +1 -1
- package/dist/web-dist/assets/{_table-CThT7wMT.js → _table-DwIZYs3U.js} +1 -1
- package/dist/web-dist/assets/{_table-CThT7wMT.js.map → _table-DwIZYs3U.js.map} +1 -1
- package/dist/web-dist/assets/{format-cell-value-DG6WpZw_.js → format-cell-value-BDLw73u3.js} +6 -6
- package/dist/web-dist/assets/format-cell-value-BDLw73u3.js.map +1 -0
- package/dist/web-dist/assets/index-DRNEODC_.js +86 -0
- package/dist/web-dist/assets/index-DRNEODC_.js.map +1 -0
- package/dist/web-dist/assets/{queries.store-DruKauzK.js → queries.store-DvaENLe7.js} +1 -1
- package/dist/web-dist/assets/{queries.store-DruKauzK.js.map → queries.store-DvaENLe7.js.map} +1 -1
- package/dist/web-dist/assets/{query-runner-Db56mYGQ.js → query-runner-D4jp77L6.js} +2 -2
- package/dist/web-dist/assets/{query-runner-Db56mYGQ.js.map → query-runner-D4jp77L6.js.map} +1 -1
- package/dist/web-dist/assets/{runner-DAA3MnAn.js → runner-EqOuNKQH.js} +1 -1
- package/dist/web-dist/assets/{runner-DAA3MnAn.js.map → runner-EqOuNKQH.js.map} +1 -1
- package/dist/web-dist/assets/{tanstack-C38qytx8.js → tanstack-BfO3BbGk.js} +5 -5
- package/dist/web-dist/assets/tanstack-BfO3BbGk.js.map +1 -0
- package/dist/web-dist/index.html +3 -3
- package/package.json +1 -1
- package/dist/web-dist/assets/_pathlessLayout-DhK1pVQZ.js +0 -2
- package/dist/web-dist/assets/format-cell-value-DG6WpZw_.js.map +0 -1
- package/dist/web-dist/assets/index-GnOMl7Md.js +0 -86
- package/dist/web-dist/assets/index-GnOMl7Md.js.map +0 -1
- package/dist/web-dist/assets/tanstack-C38qytx8.js.map +0 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{r as pr,t as je}from"./rolldown-runtime-b3L32Ng1.js";import{nt as Ds}from"./icons-B5bSDd0r.js";import{Dt as Mi,Ot as Ei}from"./radix-ui-DS4zDRqg.js";var ze=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},xi=class extends ze{#t;#e;#s;constructor(){super(),this.#s=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#s=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},ks=new xi,Pi={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ti=class{#t=Pi;#e=!1;setTimeoutProvider(e){this.#t=e}setTimeout(e,t){return this.#t.setTimeout(e,t)}clearTimeout(e){this.#t.clearTimeout(e)}setInterval(e,t){return this.#t.setInterval(e,t)}clearInterval(e){this.#t.clearInterval(e)}},Ee=new Ti;function Ai(e){setTimeout(e,0)}var Oi=typeof window>"u"||"Deno"in globalThis;function K(){}function Li(e,t){return typeof e=="function"?e(t):e}function fs(e){return typeof e=="number"&&e>=0&&e!==1/0}function mr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ye(e,t){return typeof e=="function"?e(t):e}function ee(e,t){return typeof e=="function"?e(t):e}function an(e,t){const{type:s="all",exact:n,fetchStatus:r,predicate:i,queryKey:o,stale:a}=e;if(o){if(n){if(t.queryHash!==$s(o,t.options))return!1}else if(!nt(t.queryKey,o))return!1}if(s!=="all"){const l=t.isActive();if(s==="active"&&!l||s==="inactive"&&l)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||r&&r!==t.state.fetchStatus||i&&!i(t))}function ln(e,t){const{exact:s,status:n,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(s){if(Ae(t.options.mutationKey)!==Ae(i))return!1}else if(!nt(t.options.mutationKey,i))return!1}return!(n&&t.state.status!==n||r&&!r(t))}function $s(e,t){return(t?.queryKeyHashFn||Ae)(e)}function Ae(e){return JSON.stringify(e,(t,s)=>gs(s)?Object.keys(s).sort().reduce((n,r)=>(n[r]=s[r],n),{}):s)}function nt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>nt(e[s],t[s])):!1}var Fi=Object.prototype.hasOwnProperty;function vr(e,t,s=0){if(e===t)return e;if(s>500)return t;const n=un(e)&&un(t);if(!n&&!(gs(e)&&gs(t)))return t;const r=(n?e:Object.keys(e)).length,i=n?t:Object.keys(t),o=i.length,a=n?new Array(o):{};let l=0;for(let u=0;u<o;u++){const d=n?u:i[u],c=e[d],h=t[d];if(c===h){a[d]=c,(n?u<r:Fi.call(e,d))&&l++;continue}if(c===null||h===null||typeof c!="object"||typeof h!="object"){a[d]=h;continue}const f=vr(c,h,s+1);a[d]=f,f===c&&l++}return r===o&&l===r?e:a}function xt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function un(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function gs(e){if(!cn(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!cn(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function cn(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ni(e){return new Promise(t=>{Ee.setTimeout(t,e)})}function ps(e,t,s){return typeof s.structuralSharing=="function"?s.structuralSharing(e,t):s.structuralSharing!==!1?vr(e,t):t}function Di(e,t,s=0){const n=[...e,t];return s&&n.length>s?n.slice(1):n}function ki(e,t,s=0){const n=[t,...e];return s&&n.length>s?n.slice(0,-1):n}var Bs=Symbol();function Sr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Bs?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Us(e,t){return typeof e=="function"?e(...t):!!e}function $i(e,t,s){let n=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),n||(n=!0,r.aborted?s():r.addEventListener("abort",s,{once:!0})),r)}),e}var rt=(()=>{let e=()=>Oi;return{isServer(){return e()},setIsServer(t){e=t}}})();function ms(){let e,t;const s=new Promise((r,i)=>{e=r,t=i});s.status="pending",s.catch(()=>{});function n(r){Object.assign(s,r),delete s.resolve,delete s.reject}return s.resolve=r=>{n({status:"fulfilled",value:r}),e(r)},s.reject=r=>{n({status:"rejected",reason:r}),t(r)},s}function hc(e){return e.state.status==="success"}var Bi=Ai;function Ui(){let e=[],t=0,s=a=>{a()},n=a=>{a()},r=Bi;const i=a=>{t?e.push(a):r(()=>{s(a)})},o=()=>{const a=e;e=[],a.length&&r(()=>{n(()=>{a.forEach(l=>{s(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||o()}return l},batchCalls:a=>(...l)=>{i(()=>{a(...l)})},schedule:i,setNotifyFunction:a=>{s=a},setBatchNotifyFunction:a=>{n=a},setScheduler:a=>{r=a}}}var U=Ui(),Vi=class extends ze{#t=!0;#e;#s;constructor(){super(),this.#s=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#s=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#t}},Pt=new Vi;function Gi(e){return Math.min(1e3*2**e,3e4)}function yr(e){return(e??"online")==="online"?Pt.isOnline():!0}var vs=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Cr(e){let t=!1,s=0,n;const r=ms(),i=()=>r.status!=="pending",o=p=>{if(!i()){const v=new vs(p);h(v),e.onCancel?.(v)}},a=()=>{t=!0},l=()=>{t=!1},u=()=>ks.isFocused()&&(e.networkMode==="always"||Pt.isOnline())&&e.canRun(),d=()=>yr(e.networkMode)&&e.canRun(),c=p=>{i()||(n?.(),r.resolve(p))},h=p=>{i()||(n?.(),r.reject(p))},f=()=>new Promise(p=>{n=v=>{(i()||u())&&p(v)},e.onPause?.()}).then(()=>{n=void 0,i()||e.onContinue?.()}),g=()=>{if(i())return;let p;const v=s===0?e.initialPromise:void 0;try{p=v??e.fn()}catch(m){p=Promise.reject(m)}Promise.resolve(p).then(c).catch(m=>{if(i())return;const S=e.retry??(rt.isServer()?0:3),C=e.retryDelay??Gi,I=typeof C=="function"?C(s,m):C,y=S===!0||typeof S=="number"&&s<S||typeof S=="function"&&S(s,m);if(t||!y){h(m);return}s++,e.onFail?.(s,m),Ni(I).then(()=>u()?void 0:f()).then(()=>{t?h(m):g()})})};return{promise:r,status:()=>r.status,cancel:o,continue:()=>(n?.(),r),cancelRetry:a,continueRetry:l,canStart:d,start:()=>(d()?g():f().then(g),r)}}var Rr=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),fs(this.gcTime)&&(this.#t=Ee.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(rt.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#t!==void 0&&(Ee.clearTimeout(this.#t),this.#t=void 0)}};function Hi(e){return{onFetch:(t,s)=>{const n=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let d=!1;const c=g=>{$i(g,()=>t.signal,()=>d=!0)},h=Sr(t.options,t.fetchOptions),f=async(g,p,v)=>{if(d)return Promise.reject(t.signal.reason);if(p==null&&g.pages.length)return Promise.resolve(g);const S=(()=>{const R={client:t.client,queryKey:t.queryKey,pageParam:p,direction:v?"backward":"forward",meta:t.options.meta};return c(R),R})(),C=await h(S),{maxPages:I}=t.options,y=v?ki:Di;return{pages:y(g.pages,C,I),pageParams:y(g.pageParams,p,I)}};if(r&&i.length){const g=r==="backward",p=g?ji:dn,v={pages:i,pageParams:o};a=await f(v,p(n,v),g)}else{const g=e??i.length;do{const p=l===0?o[0]??n.initialPageParam:dn(n,a);if(l>0&&p==null)break;a=await f(a,p),l++}while(l<g)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=u}}}function dn(e,{pages:t,pageParams:s}){const n=t.length-1;return t.length>0?e.getNextPageParam(t[n],t,s[n],s):void 0}function ji(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var zi=class extends Rr{#t;#e;#s;#n;#i;#r;#o;#a;constructor(e){super(),this.#a=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#n=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=fn(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#t}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#t=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fn(this.options);t.data!==void 0&&(this.setState(hn(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const s=ps(this.state.data,e,this.options);return this.#l({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(K).catch(K):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#e}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>ee(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Bs||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>ye(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!mr(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#a||this.#f()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#f(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const a=this.observers.find(l=>l.options.queryFn);a&&this.setOptions(a.options)}const s=new AbortController,n=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(this.#a=!0,s.signal)})},r=()=>{const a=Sr(this.options,t),u=(()=>{const d={client:this.#i,queryKey:this.queryKey,meta:this.meta};return n(d),d})();return this.#a=!1,this.options.persister?this.options.persister(a,u,this):a(u)},o=(()=>{const a={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:r};return n(a),a})();(this.#t==="infinite"?Hi(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#l({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=Cr({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:a=>{a instanceof vs&&a.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},onFail:(a,l)=>{this.#l({type:"failed",failureCount:a,error:l})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0});try{const a=await this.#r.start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),this.#n.config.onSuccess?.(a,this),this.#n.config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof vs){if(a.silent)return this.#r.promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw this.#l({type:"error",error:a}),this.#n.config.onError?.(a,this),this.#n.config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}#l(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Ir(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...hn(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=e.manual?n:void 0,n;case"error":const r=e.error;return{...s,error:r,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),U.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Ir(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:yr(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function hn(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fn(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,n=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var qi=class extends ze{constructor(e,t){super(),this.options=t,this.#t=e,this.#a=null,this.#o=ms(),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#s=void 0;#n=void 0;#i;#r;#o;#a;#f;#l;#c;#d;#u;#h;#g=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),gn(this.#e,this.options)?this.#p():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ss(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ss(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#C(),this.#R(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,s=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ee(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#I(),this.#e.setOptions(this.options),t._defaulted&&!xt(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const n=this.hasListeners();n&&pn(this.#e,s,this.options,t)&&this.#p(),this.updateResult(),n&&(this.#e!==s||ee(this.options.enabled,this.#e)!==ee(t.enabled,this.#e)||ye(this.options.staleTime,this.#e)!==ye(t.staleTime,this.#e))&&this.#m();const r=this.#v();n&&(this.#e!==s||ee(this.options.enabled,this.#e)!==ee(t.enabled,this.#e)||r!==this.#h)&&this.#S(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),s=this.createResult(t,e);return Ki(this,s)&&(this.#n=s,this.#r=this.options,this.#i=this.#e.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,n)=>(this.trackProp(n),t?.(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){this.#g.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),s=this.#t.getQueryCache().build(this.#t,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#p({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#p(e){this.#I();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(K)),t}#m(){this.#C();const e=ye(this.options.staleTime,this.#e);if(rt.isServer()||this.#n.isStale||!fs(e))return;const t=mr(this.#n.dataUpdatedAt,e)+1;this.#d=Ee.setTimeout(()=>{this.#n.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#S(e){this.#R(),this.#h=e,!(rt.isServer()||ee(this.options.enabled,this.#e)===!1||!fs(this.#h)||this.#h===0)&&(this.#u=Ee.setInterval(()=>{(this.options.refetchIntervalInBackground||ks.isFocused())&&this.#p()},this.#h))}#y(){this.#m(),this.#S(this.#v())}#C(){this.#d!==void 0&&(Ee.clearTimeout(this.#d),this.#d=void 0)}#R(){this.#u!==void 0&&(Ee.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const s=this.#e,n=this.options,r=this.#n,i=this.#i,o=this.#r,a=e!==s?e.state:this.#s,{state:l}=e;let u={...l},d=!1,c;if(t._optimisticResults){const R=this.hasListeners(),b=!R&&gn(e,t),_=R&&pn(e,s,t,n);(b||_)&&(u={...u,...Ir(l.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:h,errorUpdatedAt:f,status:g}=u;c=u.data;let p=!1;if(t.placeholderData!==void 0&&c===void 0&&g==="pending"){let R;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(R=r.data,p=!0):R=typeof t.placeholderData=="function"?t.placeholderData(this.#c?.state.data,this.#c):t.placeholderData,R!==void 0&&(g="success",c=ps(r?.data,R,t),d=!0)}if(t.select&&c!==void 0&&!p)if(r&&c===i?.data&&t.select===this.#f)c=this.#l;else try{this.#f=t.select,c=t.select(c),c=ps(r?.data,c,t),this.#l=c,this.#a=null}catch(R){this.#a=R}this.#a&&(h=this.#a,c=this.#l,f=Date.now(),g="error");const v=u.fetchStatus==="fetching",m=g==="pending",S=g==="error",C=m&&v,I=c!==void 0,y={status:g,fetchStatus:u.fetchStatus,isPending:m,isSuccess:g==="success",isError:S,isInitialLoading:C,isLoading:C,data:c,dataUpdatedAt:u.dataUpdatedAt,error:h,errorUpdatedAt:f,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>a.dataUpdateCount||u.errorUpdateCount>a.errorUpdateCount,isFetching:v,isRefetching:v&&!m,isLoadingError:S&&!I,isPaused:u.fetchStatus==="paused",isPlaceholderData:d,isRefetchError:S&&I,isStale:Vs(e,t),refetch:this.refetch,promise:this.#o,isEnabled:ee(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const R=y.data!==void 0,b=y.status==="error"&&!R,_=E=>{b?E.reject(y.error):R&&E.resolve(y.data)},M=()=>{const E=this.#o=y.promise=ms();_(E)},P=this.#o;switch(P.status){case"pending":e.queryHash===s.queryHash&&_(P);break;case"fulfilled":(b||y.data!==P.value)&&M();break;case"rejected":(!b||y.error!==P.reason)&&M();break}}return y}updateResult(){const e=this.#n,t=this.createResult(this.#e,this.options);if(this.#i=this.#e.state,this.#r=this.options,this.#i.data!==void 0&&(this.#c=this.#e),xt(t,e))return;this.#n=t;const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,r=typeof n=="function"?n():n;if(r==="all"||!r&&!this.#g.size)return!0;const i=new Set(r??this.#g);return this.options.throwOnError&&i.add("error"),Object.keys(this.#n).some(o=>{const a=o;return this.#n[a]!==e[a]&&i.has(a)})};this.#w({listeners:s()})}#I(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#s=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#w(e){U.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Wi(e,t){return ee(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&ee(t.retryOnMount,e)===!1)}function gn(e,t){return Wi(e,t)||e.state.data!==void 0&&Ss(e,t,t.refetchOnMount)}function Ss(e,t,s){if(ee(t.enabled,e)!==!1&&ye(t.staleTime,e)!=="static"){const n=typeof s=="function"?s(e):s;return n==="always"||n!==!1&&Vs(e,t)}return!1}function pn(e,t,s,n){return(e!==t||ee(n.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&Vs(e,s)}function Vs(e,t){return ee(t.enabled,e)!==!1&&e.isStaleByTime(ye(t.staleTime,e))}function Ki(e,t){return!xt(e.getCurrentResult(),t)}var Qi=class extends Rr{#t;#e;#s;#n;constructor(e){super(),this.#t=e.client,this.mutationId=e.mutationId,this.#s=e.mutationCache,this.#e=[],this.state=e.state||wr(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#e.includes(e)||(this.#e.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#i({type:"continue"})},s={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#n=Cr({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(i,o)=>{this.#i({type:"failed",failureCount:i,error:o})},onPause:()=>{this.#i({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#s.canRun(this)});const n=this.state.status==="pending",r=!this.#n.canStart();try{if(n)t();else{this.#i({type:"pending",variables:e,isPaused:r}),this.#s.config.onMutate&&await this.#s.config.onMutate(e,this,s);const o=await this.options.onMutate?.(e,s);o!==this.state.context&&this.#i({type:"pending",context:o,variables:e,isPaused:r})}const i=await this.#n.start();return await this.#s.config.onSuccess?.(i,e,this.state.context,this,s),await this.options.onSuccess?.(i,e,this.state.context,s),await this.#s.config.onSettled?.(i,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(i,null,e,this.state.context,s),this.#i({type:"success",data:i}),i}catch(i){try{await this.#s.config.onError?.(i,e,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(i,e,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,i,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,i,e,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#i({type:"error",error:i}),i}finally{this.#s.runNext(this)}}#i(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),U.batch(()=>{this.#e.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function wr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ji=class extends ze{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#s=0}#t;#e;#s;build(e,t,s){const n=new Qi({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(n),n}add(e){this.#t.add(e);const t=ht(e);if(typeof t=="string"){const s=this.#e.get(t);s?s.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=ht(e);if(typeof t=="string"){const s=this.#e.get(t);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=ht(e);if(typeof t=="string"){const s=this.#e.get(t)?.find(n=>n.state.status==="pending");return!s||s===e}else return!0}runNext(e){const t=ht(e);return typeof t=="string"?this.#e.get(t)?.find(s=>s!==e&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){U.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(s=>ln(t,s))}findAll(e={}){return this.getAll().filter(t=>ln(e,t))}notify(e){U.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return U.batch(()=>Promise.all(e.map(t=>t.continue().catch(K))))}};function ht(e){return e.options.scope?.id}var Xi=class extends ze{#t;#e=void 0;#s;#n;constructor(e,t){super(),this.#t=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#t.defaultMutationOptions(e),xt(this.options,t)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Ae(t.mutationKey)!==Ae(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#r(e)}getCurrentResult(){return this.#e}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#i(),this.#r()}mutate(e,t){return this.#n=t,this.#s?.removeObserver(this),this.#s=this.#t.getMutationCache().build(this.#t,this.options),this.#s.addObserver(this),this.#s.execute(e)}#i(){const e=this.#s?.state??wr();this.#e={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#r(e){U.batch(()=>{if(this.#n&&this.hasListeners()){const t=this.#e.variables,s=this.#e.context,n={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,t,s,n)}catch(r){Promise.reject(r)}try{this.#n.onSettled?.(e.data,null,t,s,n)}catch(r){Promise.reject(r)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,t,s,n)}catch(r){Promise.reject(r)}try{this.#n.onSettled?.(void 0,e.error,t,s,n)}catch(r){Promise.reject(r)}}}this.listeners.forEach(t=>{t(this.#e)})})}},Yi=class extends ze{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,s){const n=t.queryKey,r=t.queryHash??$s(n,t);let i=this.get(r);return i||(i=new zi({client:e,queryKey:n,queryHash:r,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(i)),i}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){U.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(s=>an(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>an(e,s)):t}notify(e){U.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){U.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){U.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},fc=class{#t;#e;#s;#n;#i;#r;#o;#a;constructor(e={}){this.#t=e.queryCache||new Yi,this.#e=e.mutationCache||new Ji,this.#s=e.defaultOptions||{},this.#n=new Map,this.#i=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=ks.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#a=Pt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),s=this.#t.build(this,t),n=s.state.data;return n===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(ye(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:s})=>[t,s.data])}setQueryData(e,t,s){const n=this.defaultQueryOptions({queryKey:e}),r=this.#t.get(n.queryHash)?.state.data,i=Li(t,r);if(i!==void 0)return this.#t.build(this,n).setData(i,{...s,manual:!0})}setQueriesData(e,t,s){return U.batch(()=>this.#t.findAll(e).map(({queryKey:n})=>[n,this.setQueryData(n,t,s)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;U.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#t;return U.batch(()=>(s.findAll(e).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},n=U.batch(()=>this.#t.findAll(e).map(r=>r.cancel(s)));return Promise.all(n).then(K).catch(K)}invalidateQueries(e,t={}){return U.batch(()=>(this.#t.findAll(e).forEach(s=>{s.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},n=U.batch(()=>this.#t.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,s);return s.throwOnError||(i=i.catch(K)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(n).then(K)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#t.build(this,t);return s.isStaleByTime(ye(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(K).catch(K)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(K).catch(K)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Pt.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#s}setDefaultOptions(e){this.#s=e}setQueryDefaults(e,t){this.#n.set(Ae(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(n=>{nt(e,n.queryKey)&&Object.assign(s,n.defaultOptions)}),s}setMutationDefaults(e,t){this.#i.set(Ae(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#i.values()],s={};return t.forEach(n=>{nt(e,n.mutationKey)&&Object.assign(s,n.defaultOptions)}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#s.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=$s(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Bs&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#s.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},w=pr(Ds(),1),x=Ei(),br=w.createContext(void 0),_r=e=>{const t=w.useContext(br);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gc=({client:e,children:t})=>(w.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,x.jsx)(br.Provider,{value:e,children:t})),Mr=w.createContext(!1),Zi=()=>w.useContext(Mr),pc=Mr.Provider;function eo(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var to=w.createContext(eo()),so=()=>w.useContext(to),no=(e,t,s)=>{const n=s?.state.error&&typeof e.throwOnError=="function"?Us(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||n)&&(t.isReset()||(e.retryOnMount=!1))},ro=e=>{w.useEffect(()=>{e.clearReset()},[e])},io=({result:e,errorResetBoundary:t,throwOnError:s,query:n,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&n&&(r&&e.data===void 0||Us(s,[e.error,n])),oo=e=>{if(e.suspense){const s=r=>r==="static"?r:Math.max(r??1e3,1e3),n=e.staleTime;e.staleTime=typeof n=="function"?(...r)=>s(n(...r)):s(n),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},ao=(e,t)=>e.isLoading&&e.isFetching&&!t,lo=(e,t)=>e?.suspense&&t.isPending,mn=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function uo(e,t,s){const n=Zi(),r=so(),i=_r(s),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const a=i.getQueryCache().get(o.queryHash);o._optimisticResults=n?"isRestoring":"optimistic",oo(o),no(o,r,a),ro(r);const l=!i.getQueryCache().get(o.queryHash),[u]=w.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),c=!n&&e.subscribed!==!1;if(w.useSyncExternalStore(w.useCallback(h=>{const f=c?u.subscribe(U.batchCalls(h)):K;return u.updateResult(),f},[u,c]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),w.useEffect(()=>{u.setOptions(o)},[o,u]),lo(o,d))throw mn(o,u,r);if(io({result:d,errorResetBoundary:r,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!rt.isServer()&&ao(d,n)&&(l?mn(o,u,r):a?.promise)?.catch(K).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function mc(e,t){return uo(e,qi,t)}function vc(e,t){const s=_r(t),[n]=w.useState(()=>new Xi(s,e));w.useEffect(()=>{n.setOptions(e)},[n,e]);const r=w.useSyncExternalStore(w.useCallback(o=>n.subscribe(U.batchCalls(o)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),i=w.useCallback((o,a)=>{n.mutate(o,a).catch(K)},[n]);if(r.error&&Us(n.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:i,mutateAsync:r.mutate}}var vn=w.use,et=typeof window<"u"?w.useLayoutEffect:w.useEffect;function Wt(e){const t=w.useRef({value:e,prev:null}),s=t.current.value;return e!==s&&(t.current={value:e,prev:s}),t.current.prev}function co(e,t,s={},n={}){w.useEffect(()=>{if(!e.current||n.disabled||typeof IntersectionObserver!="function")return;const r=new IntersectionObserver(([i])=>{t(i)},s);return r.observe(e.current),()=>{r.disconnect()}},[t,s,n.disabled,e])}function ho(e){const t=w.useRef(null);return w.useImperativeHandle(e,()=>t.current,[]),t}function it(e){return e[e.length-1]}function fo(e){return typeof e=="function"}function ue(e,t){return fo(e)?e(t):e}var Er=Object.prototype.hasOwnProperty,Sn=Object.prototype.propertyIsEnumerable;function Tt(e){for(const t in e)if(Er.call(e,t))return!0;return!1}var go=()=>Object.create(null),_e=(e,t)=>xe(e,t,go);function xe(e,t,s=()=>({}),n=0){if(e===t)return e;if(n>500)return t;const r=t,i=Rn(e)&&Rn(r);if(!i&&!(At(e)&&At(r)))return r;const o=i?e:yn(e);if(!o)return r;const a=i?r:yn(r);if(!a)return r;const l=o.length,u=a.length,d=i?new Array(u):s();let c=0;for(let h=0;h<u;h++){const f=i?h:a[h],g=e[f],p=r[f];if(g===p){d[f]=g,(i?h<l:Er.call(e,f))&&c++;continue}if(g===null||p===null||typeof g!="object"||typeof p!="object"){d[f]=p;continue}const v=xe(g,p,s,n+1);d[f]=v,v===g&&c++}return l===u&&c===l?e:d}function yn(e){const t=Object.getOwnPropertyNames(e);for(const r of t)if(!Sn.call(e,r))return!1;const s=Object.getOwnPropertySymbols(e);if(s.length===0)return t;const n=t;for(const r of s){if(!Sn.call(e,r))return!1;n.push(r)}return n}function At(e){if(!Cn(e))return!1;const t=e.constructor;if(typeof t>"u")return!0;const s=t.prototype;return!(!Cn(s)||!s.hasOwnProperty("isPrototypeOf"))}function Cn(e){return Object.prototype.toString.call(e)==="[object Object]"}function Rn(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ce(e,t,s){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(!Ce(e[n],t[n],s))return!1;return!0}if(At(e)&&At(t)){const n=s?.ignoreUndefined??!0;if(s?.partial){for(const o in t)if((!n||t[o]!==void 0)&&!Ce(e[o],t[o],s))return!1;return!0}let r=0;if(!n)r=Object.keys(e).length;else for(const o in e)e[o]!==void 0&&r++;let i=0;for(const o in t)if((!n||t[o]!==void 0)&&(i++,i>r||!Ce(e[o],t[o],s)))return!1;return r===i}return!1}function He(e){let t,s;const n=new Promise((r,i)=>{t=r,s=i});return n.status="pending",n.resolve=r=>{n.status="resolved",n.value=r,t(r),e?.(r)},n.reject=r=>{n.status="rejected",s(r)},n}function po(e){return typeof e?.message!="string"?!1:e.message.startsWith("Failed to fetch dynamically imported module")||e.message.startsWith("error loading dynamically imported module")||e.message.startsWith("Importing a module script failed")}function ot(e){return!!(e&&typeof e=="object"&&typeof e.then=="function")}var mo=/[\x00-\x1f\x7f"<>`{}]/g;function vo(e){return e.replace(mo,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function In(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,s=>{try{return decodeURI(s)}catch{return s}})}return vo(t)}var So=["http:","https:","mailto:","tel:"];function Me(e,t){if(!e)return!1;try{const s=new URL(e);return!t.has(s.protocol)}catch{return!1}}function Je(e){if(!e)return{path:e,handledProtocolRelativeURL:!1};if(!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith("//"))return{path:e,handledProtocolRelativeURL:!1};const t=/%25|%5C/gi;let s=0,n="",r;for(;(r=t.exec(e))!==null;)n+=In(e.slice(s,r.index))+r[0],s=t.lastIndex;n=n+In(s?e.slice(s):e);let i=!1;return n.startsWith("//")&&(i=!0,n="/"+n.replace(/^\/+/,"")),{path:n,handledProtocolRelativeURL:i}}function yo(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function Co(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;return!0}function de(){throw new Error("Invariant failed")}function at(e){const t=new Map;let s,n;const r=i=>{i.next&&(i.prev?(i.prev.next=i.next,i.next.prev=i.prev,i.next=void 0,n&&(n.next=i,i.prev=n)):(i.next.prev=void 0,s=i.next,i.next=void 0,n&&(i.prev=n,n.next=i)),n=i)};return{get(i){const o=t.get(i);if(o)return r(o),o.value},set(i,o){if(t.size>=e&&s){const l=s;t.delete(l.key),l.next&&(s=l.next,l.next.prev=void 0),l===n&&(n=void 0)}const a=t.get(i);if(a)a.value=o,r(a);else{const l={key:i,value:o,prev:n};n&&(n.next=l),n=l,s||(s=l),t.set(i,l)}},clear(){t.clear(),s=void 0,n=void 0}}}var pe=4,xr=5;function Ro(e){const t=e.indexOf("{");if(t===-1)return null;const s=e.indexOf("}",t);return s===-1||t+1>=e.length?null:[t,s]}function Pr(e,t,s=new Uint16Array(6)){const n=e.indexOf("/",t),r=n===-1?e.length:n,i=e.substring(t,r);if(!i||!i.includes("$"))return s[0]=0,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s;if(i==="$"){const a=e.length;return s[0]=2,s[1]=t,s[2]=t,s[3]=a,s[4]=a,s[5]=a,s}if(i.charCodeAt(0)===36)return s[0]=1,s[1]=t,s[2]=t+1,s[3]=r,s[4]=r,s[5]=r,s;const o=Ro(i);if(o){const[a,l]=o,u=i.charCodeAt(a+1);if(u===45){if(a+2<i.length&&i.charCodeAt(a+2)===36){const d=a+3,c=l;if(d<c)return s[0]=3,s[1]=t+a,s[2]=t+d,s[3]=t+c,s[4]=t+l+1,s[5]=r,s}}else if(u===36){const d=a+1,c=a+2;return c===l?(s[0]=2,s[1]=t+a,s[2]=t+d,s[3]=t+c,s[4]=t+l+1,s[5]=e.length,s):(s[0]=1,s[1]=t+a,s[2]=t+c,s[3]=t+l,s[4]=t+l+1,s[5]=r,s)}}return s[0]=0,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s}function Dt(e,t,s,n,r,i,o){o?.(s);let a=n;{const l=s.fullPath??s.from,u=l.length,d=s.options?.caseSensitive??e,c=s.options?.params?.parse??s.options?.parseParams;for(;a<u;){const f=Pr(l,a,t);let g;const p=a,v=f[5];switch(a=v+1,i++,f[0]){case 0:{const m=l.substring(f[2],f[3]);if(d){const S=r.static?.get(m);if(S)g=S;else{r.static??=new Map;const C=Pe(s.fullPath??s.from);C.parent=r,C.depth=i,g=C,r.static.set(m,C)}}else{const S=m.toLowerCase(),C=r.staticInsensitive?.get(S);if(C)g=C;else{r.staticInsensitive??=new Map;const I=Pe(s.fullPath??s.from);I.parent=r,I.depth=i,g=I,r.staticInsensitive.set(S,I)}}break}case 1:{const m=l.substring(p,f[1]),S=l.substring(f[4],v),C=d&&!!(m||S),I=m?C?m:m.toLowerCase():void 0,y=S?C?S:S.toLowerCase():void 0,R=!c&&r.dynamic?.find(b=>!b.parse&&b.caseSensitive===C&&b.prefix===I&&b.suffix===y);if(R)g=R;else{const b=Qt(1,s.fullPath??s.from,C,I,y);g=b,b.depth=i,b.parent=r,r.dynamic??=[],r.dynamic.push(b)}break}case 3:{const m=l.substring(p,f[1]),S=l.substring(f[4],v),C=d&&!!(m||S),I=m?C?m:m.toLowerCase():void 0,y=S?C?S:S.toLowerCase():void 0,R=!c&&r.optional?.find(b=>!b.parse&&b.caseSensitive===C&&b.prefix===I&&b.suffix===y);if(R)g=R;else{const b=Qt(3,s.fullPath??s.from,C,I,y);g=b,b.parent=r,b.depth=i,r.optional??=[],r.optional.push(b)}break}case 2:{const m=l.substring(p,f[1]),S=l.substring(f[4],v),C=d&&!!(m||S),I=m?C?m:m.toLowerCase():void 0,y=S?C?S:S.toLowerCase():void 0,R=Qt(2,s.fullPath??s.from,C,I,y);g=R,R.parent=r,R.depth=i,r.wildcard??=[],r.wildcard.push(R)}}r=g}if(c&&s.children&&!s.isRoot&&s.id&&s.id.charCodeAt(s.id.lastIndexOf("/")+1)===95){const f=Pe(s.fullPath??s.from);f.kind=xr,f.parent=r,i++,f.depth=i,r.pathless??=[],r.pathless.push(f),r=f}const h=(s.path||!s.children)&&!s.isRoot;if(h&&l.endsWith("/")){const f=Pe(s.fullPath??s.from);f.kind=pe,f.parent=r,i++,f.depth=i,r.index=f,r=f}r.parse=c??null,r.priority=s.options?.params?.priority??0,h&&!r.route&&(r.route=s,r.fullPath=s.fullPath??s.from)}if(s.children)for(const l of s.children)Dt(e,t,l,a,r,i,o)}function Kt(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function ge(e){if(e.pathless)for(const t of e.pathless)ge(t);if(e.static)for(const t of e.static.values())ge(t);if(e.staticInsensitive)for(const t of e.staticInsensitive.values())ge(t);if(e.dynamic?.length){e.dynamic.sort(Kt);for(const t of e.dynamic)ge(t)}if(e.optional?.length){e.optional.sort(Kt);for(const t of e.optional)ge(t)}if(e.wildcard?.length){e.wildcard.sort(Kt);for(const t of e.wildcard)ge(t)}}function Pe(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function Qt(e,t,s,n,r){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:s,prefix:n,suffix:r}}function Io(e,t){const s=Pe("/"),n=new Uint16Array(6);for(const r of e)Dt(!1,n,r,1,s,0);ge(s),t.masksTree=s,t.flatCache=at(1e3)}function wo(e,t){e||="/";const s=t.flatCache.get(e);if(s)return s;const n=Gs(e,t.masksTree);return t.flatCache.set(e,n),n}function bo(e,t,s,n,r){e||="/",n||="/";const i=t?`case\0${e}`:e;let o=r.singleCache.get(i);return o||(o=Pe("/"),Dt(t,new Uint16Array(6),{from:e},1,o,0),r.singleCache.set(i,o)),Gs(n,o,s)}function _o(e,t,s=!1){const n=s?e:`nofuzz\0${e}`,r=t.matchCache.get(n);if(r!==void 0)return r;e||="/";let i;try{i=Gs(e,t.segmentTree,s)}catch(o){if(o instanceof URIError)i=null;else throw o}return i&&(i.branch=Ar(i.route)),t.matchCache.set(n,i),i}function Mo(e){return e==="/"?e:e.replace(/\/{1,}$/,"")}function Eo(e,t=!1,s){const n=Pe(e.fullPath),r=new Uint16Array(6),i={},o={};let a=0;return Dt(t,r,e,1,n,0,l=>{if(s?.(l,a),l.id in i&&de(),i[l.id]=l,a!==0&&l.path){const u=Mo(l.fullPath);(!o[u]||l.fullPath.endsWith("/"))&&(o[u]=l)}a++}),ge(n),{processedTree:{segmentTree:n,singleCache:at(1e3),matchCache:at(1e3),flatCache:null,masksTree:null},routesById:i,routesByPath:o}}function Gs(e,t,s=!1){const n=e.split("/"),r=Po(e,n,t,s);if(!r)return null;const[i]=Tr(e,n,r);return{route:r.node.route,rawParams:i}}function Tr(e,t,s){const n=xo(s.node);let r=null;const i=Object.create(null);let o=s.extract?.part??0,a=s.extract?.node??0,l=s.extract?.path??0,u=s.extract?.segment??0;for(;a<n.length;o++,a++,l++,u++){const d=n[a];if(d.kind===pe)break;if(d.kind===xr){u--,o--,l--;continue}const c=t[o],h=l;if(c&&(l+=c.length),d.kind===1){r??=s.node.fullPath.split("/");const f=r[u],g=d.prefix?.length??0;if(f.charCodeAt(g)===123){const p=d.suffix?.length??0,v=f.substring(g+2,f.length-p-1),m=c.substring(g,c.length-p);i[v]=decodeURIComponent(m)}else{const p=f.substring(1);i[p]=decodeURIComponent(c)}}else if(d.kind===3){if(s.skipped&1<<a){o--,l=h-1;continue}r??=s.node.fullPath.split("/");const f=r[u],g=d.prefix?.length??0,p=d.suffix?.length??0,v=f.substring(g+3,f.length-p-1),m=d.suffix||d.prefix?c.substring(g,c.length-p):c;m&&(i[v]=decodeURIComponent(m))}else if(d.kind===2){const f=d,g=e.substring(h+(f.prefix?.length??0),e.length-(f.suffix?.length??0)),p=decodeURIComponent(g);i["*"]=p,i._splat=p;break}}return s.rawParams&&Object.assign(i,s.rawParams),[i,{part:o,node:a,path:l,segment:u}]}function Ar(e){const t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function xo(e){const t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function Po(e,t,s,n){if(e==="/"&&s.index)return{node:s.index,skipped:0};const r=!it(t),i=r&&e!=="/",o=t.length-(r?1:0),a=[{node:s,index:1,skipped:0,depth:1,statics:0,dynamics:0,optionals:0}];let l=null,u=null;for(;a.length;){const d=a.pop(),{node:c,index:h,skipped:f,depth:g,statics:p,dynamics:v,optionals:m}=d;let{extract:S,rawParams:C}=d;if(c.kind===2&&c.route&&!gt(u,d))continue;if(c.parse){if(!wn(e,t,d))continue;C=d.rawParams,S=d.extract}n&&c.route&&c.kind!==pe&>(l,d)&&(l=d);const I=h===o;if(I&&(c.route&&(!i||c.kind===pe||c.kind===2)&>(u,d)&&(u=d),!c.optional&&!c.wildcard&&!c.index&&!c.pathless))continue;const y=I?void 0:t[h];let R;if(I&&c.index){const b={node:c.index,index:h,skipped:f,depth:g+1,statics:p,dynamics:v,optionals:m,extract:S,rawParams:C};let _=!0;if(c.index.parse&&(wn(e,t,b)||(_=!1)),_){if(!v&&!m&&!f&&To(p,o))return b;gt(u,b)&&(u=b)}}if(c.wildcard)for(let b=c.wildcard.length-1;b>=0;b--){const _=c.wildcard[b],{prefix:M,suffix:P}=_;if(!(M&&(I||!(_.caseSensitive?y:R??=y.toLowerCase()).startsWith(M)))){if(P){if(I)continue;const E=t.slice(h).join("/").slice(-P.length);if((_.caseSensitive?E:E.toLowerCase())!==P)continue}a.push({node:_,index:o,skipped:f,depth:g+1,statics:p,dynamics:v,optionals:m,extract:S,rawParams:C})}}if(c.optional){const b=f|1<<g,_=g+1;for(let M=c.optional.length-1;M>=0;M--){const P=c.optional[M];a.push({node:P,index:h,skipped:b,depth:_,statics:p,dynamics:v,optionals:m,extract:S,rawParams:C})}if(!I)for(let M=c.optional.length-1;M>=0;M--){const P=c.optional[M],{prefix:E,suffix:O}=P;if(E||O){const se=P.caseSensitive?y:R??=y.toLowerCase();if(E&&!se.startsWith(E)||O&&!se.endsWith(O))continue}a.push({node:P,index:h+1,skipped:f,depth:_,statics:p,dynamics:v,optionals:m+ft(o,h),extract:S,rawParams:C})}}if(!I&&c.dynamic&&y)for(let b=c.dynamic.length-1;b>=0;b--){const _=c.dynamic[b],{prefix:M,suffix:P}=_;if(M||P){const E=_.caseSensitive?y:R??=y.toLowerCase();if(M&&!E.startsWith(M)||P&&!E.endsWith(P))continue}a.push({node:_,index:h+1,skipped:f,depth:g+1,statics:p,dynamics:v+ft(o,h),optionals:m,extract:S,rawParams:C})}if(!I&&c.staticInsensitive){const b=c.staticInsensitive.get(R??=y.toLowerCase());b&&a.push({node:b,index:h+1,skipped:f,depth:g+1,statics:p+ft(o,h),dynamics:v,optionals:m,extract:S,rawParams:C})}if(!I&&c.static){const b=c.static.get(y);b&&a.push({node:b,index:h+1,skipped:f,depth:g+1,statics:p+ft(o,h),dynamics:v,optionals:m,extract:S,rawParams:C})}if(c.pathless){const b=g+1;for(let _=c.pathless.length-1;_>=0;_--){const M=c.pathless[_];a.push({node:M,index:h,skipped:f,depth:b,statics:p,dynamics:v,optionals:m,extract:S,rawParams:C})}}}if(u)return u;if(n&&l){let d=l.index;for(let h=0;h<l.index;h++)d+=t[h].length;const c=d===e.length?"/":e.slice(d);return l.rawParams??=Object.create(null),l.rawParams["**"]=decodeURIComponent(c),l}return null}function ft(e,t){return 2**(e-t-1)}function To(e,t){return e===2**(t-1)-1}function wn(e,t,s){let n,r;try{[n,r]=Tr(e,t,s)}catch{return null}if(s.rawParams=n,s.extract=r,!s.node.parse)return!0;try{if(s.node.parse(n)===!1)return null}catch{}return!0}function gt(e,t){return e?t.statics>e.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===pe)>(e.node.kind===pe)||t.node.kind===pe==(e.node.kind===pe)&&t.depth>e.depth))):!0}function It(e){return Hs(e.filter(t=>t!==void 0).join("/"))}function Hs(e){return e.replace(/\/{2,}/g,"/")}function Or(e){return e==="/"?e:e.replace(/^\/{1,}/,"")}function ce(e){const t=e.length;return t>1&&e[t-1]==="/"?e.replace(/\/{1,}$/,""):e}function Lr(e){return ce(Or(e))}function Ve(e,t){return e?.endsWith("/")&&e!=="/"&&e!==`${t}/`?e.slice(0,-1):e}function bn(e,t,s){return Ve(e,s)===Ve(t,s)}function Ao({base:e,to:t,trailingSlash:s="never",cache:n}){const r=t.startsWith("/"),i=!r&&t===".";let o;if(n){o=r?t:i?e:e+"\0"+t;const u=n.get(o);if(u)return u}let a;if(i)a=e.split("/");else if(r)a=t.split("/");else{for(a=e.split("/");a.length>1&&it(a)==="";)a.pop();const u=t.split("/");for(let d=0,c=u.length;d<c;d++){const h=u[d];h===""?d?d===c-1&&a.push(h):a=[h]:h===".."?a.pop():h==="."||a.push(h)}}a.length>1&&(it(a)===""?s==="never"&&a.pop():s==="always"&&a.push(""));const l=Hs(a.join("/"))||"/";return o&&n&&n.set(o,l),l}function Oo(e){const t=new Map(e.map(r=>[encodeURIComponent(r),r])),s=Array.from(t.keys()).map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),n=new RegExp(s,"g");return r=>r.replace(n,i=>t.get(i)??i)}function Jt(e,t,s){const n=t[e];return typeof n!="string"?n:e==="_splat"?/^[a-zA-Z0-9\-._~!/]*$/.test(n)?n:n.split("/").map(r=>Mn(r,s)).join("/"):Mn(n,s)}function _n({path:e,params:t,decoder:s,...n}){let r=!1;const i=Object.create(null);if(!e||e==="/")return{interpolatedPath:"/",usedParams:i,isMissingParams:r};if(!e.includes("$"))return{interpolatedPath:e,usedParams:i,isMissingParams:r};const o=e.length;let a=0,l,u="";for(;a<o;){const d=a;l=Pr(e,d,l);const c=l[5];if(a=c+1,d===c)continue;const h=l[0];if(h===0){u+="/"+e.substring(d,c);continue}if(h===2){const f=t._splat;i._splat=f,i["*"]=f;const g=e.substring(d,l[1]),p=e.substring(l[4],c);if(!f){r=!0,(g||p)&&(u+="/"+g+p);continue}const v=Jt("_splat",t,s);u+="/"+g+v+p;continue}if(h===1){const f=e.substring(l[2],l[3]);!r&&!(f in t)&&(r=!0),i[f]=t[f];const g=e.substring(d,l[1]),p=e.substring(l[4],c),v=Jt(f,t,s)??"undefined";u+="/"+g+v+p;continue}if(h===3){const f=e.substring(l[2],l[3]),g=t[f];if(g==null)continue;i[f]=g;const p=e.substring(d,l[1]),v=e.substring(l[4],c),m=Jt(f,t,s)??"";u+="/"+p+m+v;continue}}return e.endsWith("/")&&(u+="/"),{usedParams:i,interpolatedPath:u||"/",isMissingParams:r}}function Mn(e,t){const s=encodeURIComponent(e);return t?.(s)??s}function q(e){return e?.isNotFound===!0}function Lo(e,t=String){const s=new URLSearchParams;for(const n in e){const r=e[n];r!==void 0&&s.set(n,t(r))}return s.toString()}function Xt(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function Fo(e){const t=new URLSearchParams(e),s=Object.create(null);for(const[n,r]of t.entries()){const i=s[n];i==null?s[n]=Xt(r):Array.isArray(i)?i.push(Xt(r)):s[n]=[i,Xt(r)]}return s}var No=ko(JSON.parse),Do=$o(JSON.stringify,JSON.parse);function ko(e){return t=>{t[0]==="?"&&(t=t.substring(1));const s=Fo(t);for(const n in s){const r=s[n];if(typeof r=="string")try{s[n]=e(r)}catch{}}return s}}function $o(e,t){const s=typeof t=="function";function n(r){if(typeof r=="object"&&r!==null)try{return e(r)}catch{}else if(s&&typeof r=="string")try{return t(r),e(r)}catch{}return r}return r=>{const i=Lo(r,n);return i?`?${i}`:""}}var wt="__root__";function Bo(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href=="string")try{new URL(e.href),e.reloadDocument=!0}catch{}const t=new Headers(e.headers);e.href&&t.get("Location")===null&&t.set("Location",e.href);const s=new Response(null,{status:e.statusCode,headers:t});if(s.options=e,e.throw)throw s;return s}function Y(e){return e instanceof Response&&!!e.options}var ys=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},Uo=e=>e.stores.matchesId.get().some(t=>e.stores.matchStores.get(t)?.get()._forcePending),kt=(e,t)=>!!(e.preload&&!e.router.stores.matchStores.has(t)),Te=(e,t,s=!0)=>{const n={...e.router.options.context??{}},r=s?t:t-1;for(let i=0;i<=r;i++){const o=e.matches[i];if(!o)continue;const a=e.router.getMatch(o.id);a&&Object.assign(n,a.__routeContext,a.__beforeLoadContext)}return n},En=(e,t)=>{if(!e.matches.length)return;const s=t.routeId,n=e.matches.findIndex(o=>o.routeId===e.router.routeTree.id),r=n>=0?n:0;let i=s?e.matches.findIndex(o=>o.routeId===s):e.firstBadMatchIndex??e.matches.length-1;i<0&&(i=r);for(let o=i;o>=0;o--){const a=e.matches[o];if(e.router.looseRoutesById[a.routeId].options.notFoundComponent)return o}return s?i:r},me=(e,t,s)=>{if(!(!Y(s)&&!q(s)))throw Y(s)&&s.redirectHandled&&!s.options.reloadDocument||(t&&(t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0,t._nonReactive.error=s,e.updateMatch(t.id,n=>({...n,status:Y(s)?"redirected":q(s)?"notFound":n.status==="pending"?"success":n.status,context:Te(e,t.index),isFetching:!1,error:s})),q(s)&&!s.routeId&&(s.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()),Y(s)&&(e.rendered=!0,s.options._fromLocation=e.location,s.redirectHandled=!0,s=e.router.resolveRedirect(s))),s},Fr=(e,t)=>{const s=e.router.getMatch(t);return!!(!s||s._nonReactive.dehydrated)},xn=(e,t,s)=>{const n=Te(e,s);e.updateMatch(t,r=>({...r,context:n}))},Xe=(e,t,s)=>{const{id:n,routeId:r}=e.matches[t],i=e.router.looseRoutesById[r];if(s instanceof Promise)throw s;e.firstBadMatchIndex??=t,me(e,e.router.getMatch(n),s);try{i.options.onError?.(s)}catch(o){s=o,me(e,e.router.getMatch(n),s)}e.updateMatch(n,o=>(o._nonReactive.beforeLoadPromise?.resolve(),o._nonReactive.beforeLoadPromise=void 0,o._nonReactive.loadPromise?.resolve(),{...o,error:s,status:"error",isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!Y(s)&&!q(s)&&(e.serialError??=s)};var Nr=(e,t,s,n)=>{if(n._nonReactive.pendingTimeout!==void 0)return;const r=s.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!kt(e,t)&&(s.options.loader||s.options.beforeLoad||kr(s))&&typeof r=="number"&&r!==1/0&&(s.options.pendingComponent??e.router.options?.defaultPendingComponent)){const i=setTimeout(()=>{ys(e)},r);n._nonReactive.pendingTimeout=i}},Vo=(e,t,s)=>{const n=e.router.getMatch(t);if(!n._nonReactive.beforeLoadPromise&&!n._nonReactive.loaderPromise)return;Nr(e,t,s,n);const r=()=>{const i=e.router.getMatch(t);i.preload&&(i.status==="redirected"||i.status==="notFound")&&me(e,i,i.error)};return n._nonReactive.beforeLoadPromise?n._nonReactive.beforeLoadPromise.then(r):r()},Go=(e,t,s,n)=>{const r=e.router.getMatch(t);let i=r._nonReactive.loadPromise;r._nonReactive.loadPromise=He(()=>{i?.resolve(),i=void 0});const{paramsError:o,searchError:a}=r;o&&Xe(e,s,o),a&&Xe(e,s,a),Nr(e,t,n,r);const l=new AbortController;let u=!1;const d=()=>{u||(u=!0,e.updateMatch(t,I=>({...I,isFetching:"beforeLoad",fetchCount:I.fetchCount+1,abortController:l})))},c=()=>{r._nonReactive.beforeLoadPromise?.resolve(),r._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,I=>({...I,isFetching:!1}))};if(!n.options.beforeLoad){e.router.batch(()=>{d(),c()});return}r._nonReactive.beforeLoadPromise=He();const h={...Te(e,s,!1),...r.__routeContext},{search:f,params:g,cause:p}=r,v=kt(e,t),m={search:f,abortController:l,params:g,preload:v,context:h,location:e.location,navigate:I=>e.router.navigate({...I,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:v?"preload":p,matches:e.matches,routeId:n.id,...e.router.options.additionalContext},S=I=>{if(I===void 0){e.router.batch(()=>{d(),c()});return}(Y(I)||q(I))&&(d(),Xe(e,s,I)),e.router.batch(()=>{d(),e.updateMatch(t,y=>({...y,__beforeLoadContext:I})),c()})};let C;try{if(C=n.options.beforeLoad(m),ot(C))return d(),C.catch(I=>{Xe(e,s,I)}).then(S)}catch(I){d(),Xe(e,s,I)}S(C)},Ho=(e,t)=>{const{id:s,routeId:n}=e.matches[t],r=e.router.looseRoutesById[n],i=()=>a(),o=()=>Go(e,s,t,r),a=()=>{if(Fr(e,s))return;const l=Vo(e,s,r);return ot(l)?l.then(o):o()};return i()},jo=(e,t,s)=>{const n=e.router.getMatch(t);if(!n||!s.options.head&&!s.options.scripts&&!s.options.headers)return;const r={ssr:e.router.options.ssr,matches:e.matches,match:n,params:n.params,loaderData:n.loaderData};return Promise.all([s.options.head?.(r),s.options.scripts?.(r),s.options.headers?.(r)]).then(([i,o,a])=>({meta:i?.meta,links:i?.links,headScripts:i?.scripts,headers:a,scripts:o,styles:i?.styles}))},Dr=(e,t,s,n,r)=>{const i=t[n-1],{params:o,loaderDeps:a,abortController:l,cause:u}=e.router.getMatch(s),d=Te(e,n),c=kt(e,s);return{params:o,deps:a,preload:!!c,parentMatchPromise:i,abortController:l,context:d,location:e.location,navigate:h=>e.router.navigate({...h,_fromLocation:e.location}),cause:c?"preload":u,route:r,...e.router.options.additionalContext}},Pn=async(e,t,s,n,r)=>{try{const i=e.router.getMatch(s);try{lt(r);const o=r.options.loader,a=typeof o=="function"?o:o?.handler,l=a?.(Dr(e,t,s,n,r)),u=!!a&&ot(l);if((u||r._lazyPromise||r._componentsPromise||r.options.head||r.options.scripts||r.options.headers||i._nonReactive.minPendingPromise)&&e.updateMatch(s,c=>({...c,isFetching:"loader"})),a){const c=u?await l:l;me(e,e.router.getMatch(s),c),c!==void 0&&e.updateMatch(s,h=>({...h,loaderData:c}))}r._lazyPromise&&await r._lazyPromise;const d=i._nonReactive.minPendingPromise;d&&await d,r._componentsPromise&&await r._componentsPromise,e.updateMatch(s,c=>({...c,error:void 0,context:Te(e,n),status:"success",isFetching:!1,updatedAt:Date.now()}))}catch(o){let a=o;if(a?.name==="AbortError"){if(i.abortController.signal.aborted){i._nonReactive.loaderPromise?.resolve(),i._nonReactive.loaderPromise=void 0;return}e.updateMatch(s,u=>({...u,status:u.status==="pending"?"success":u.status,isFetching:!1,context:Te(e,n)}));return}const l=i._nonReactive.minPendingPromise;l&&await l,q(o)&&await r.options.notFoundComponent?.preload?.(),me(e,e.router.getMatch(s),o);try{r.options.onError?.(o)}catch(u){a=u,me(e,e.router.getMatch(s),u)}!Y(a)&&!q(a)&&await lt(r,["errorComponent"]),e.updateMatch(s,u=>({...u,error:a,context:Te(e,n),status:"error",isFetching:!1}))}}catch(i){const o=e.router.getMatch(s);o&&(o._nonReactive.loaderPromise=void 0),me(e,o,i)}},zo=async(e,t,s)=>{async function n(f,g,p,v,m){const S=Date.now()-g.updatedAt,C=f?m.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:m.options.staleTime??e.router.options.defaultStaleTime??0,I=m.options.shouldReload,y=typeof I=="function"?I(Dr(e,t,r,s,m)):I,{status:R,invalid:b}=v,_=S>=C&&(!!e.forceStaleReload||v.cause==="enter"||p!==void 0&&p!==v.id);o=R==="success"&&(b||(y??_)),f&&m.options.preload===!1||(o&&!e.sync&&d?(a=!0,(async()=>{try{await Pn(e,t,r,s,m);const M=e.router.getMatch(r);M._nonReactive.loaderPromise?.resolve(),M._nonReactive.loadPromise?.resolve(),M._nonReactive.loaderPromise=void 0,M._nonReactive.loadPromise=void 0}catch(M){Y(M)&&await e.router.navigate(M.options)}})()):R!=="success"||o?await Pn(e,t,r,s,m):xn(e,r,s))}const{id:r,routeId:i}=e.matches[s];let o=!1,a=!1;const l=e.router.looseRoutesById[i],u=l.options.loader,d=((typeof u=="function"?void 0:u?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!=="blocking";if(Fr(e,r)){if(!e.router.getMatch(r))return e.matches[s];xn(e,r,s)}else{const f=e.router.getMatch(r),g=e.router.stores.matchesId.get()[s],p=(g&&e.router.stores.matchStores.get(g)||null)?.routeId===i?g:e.router.stores.matches.get().find(m=>m.routeId===i)?.id,v=kt(e,r);if(f._nonReactive.loaderPromise){if(f.status==="success"&&!e.sync&&!f.preload&&d)return f;await f._nonReactive.loaderPromise;const m=e.router.getMatch(r),S=m._nonReactive.error||m.error;S&&me(e,m,S),m.status==="pending"&&await n(v,f,p,m,l)}else{const m=v&&!e.router.stores.matchStores.has(r),S=e.router.getMatch(r);S._nonReactive.loaderPromise=He(),m!==S.preload&&e.updateMatch(r,C=>({...C,preload:m})),await n(v,f,p,S,l)}}const c=e.router.getMatch(r);a||(c._nonReactive.loaderPromise?.resolve(),c._nonReactive.loadPromise?.resolve(),c._nonReactive.loadPromise=void 0),clearTimeout(c._nonReactive.pendingTimeout),c._nonReactive.pendingTimeout=void 0,a||(c._nonReactive.loaderPromise=void 0),c._nonReactive.dehydrated=void 0;const h=a?c.isFetching:!1;return h!==c.isFetching||c.invalid!==!1?(e.updateMatch(r,f=>({...f,isFetching:h,invalid:!1})),e.router.getMatch(r)):c};async function Tn(e){const t=e,s=[];Uo(t.router)&&ys(t);let n;for(let h=0;h<t.matches.length;h++){try{const f=Ho(t,h);ot(f)&&await f}catch(f){if(Y(f))throw f;if(q(f))n=f;else if(!t.preload)throw f;break}if(t.serialError||t.firstBadMatchIndex!=null)break}const r=t.firstBadMatchIndex??t.matches.length,i=n&&!t.preload?En(t,n):void 0,o=n&&t.preload?0:i!==void 0?Math.min(i+1,r):r;let a,l;for(let h=0;h<o;h++)s.push(zo(t,s,h));try{await Promise.all(s)}catch{const h=await Promise.allSettled(s);for(const f of h){if(f.status!=="rejected")continue;const g=f.reason;if(Y(g))throw g;q(g)?a??=g:l??=g}if(l!==void 0)throw l}const u=a??(n&&!t.preload?n:void 0);let d=t.firstBadMatchIndex!==void 0?t.firstBadMatchIndex:t.matches.length-1;if(!u&&n&&t.preload)return t.matches;if(u){const h=En(t,u);h===void 0&&de();const f=t.matches[h],g=t.router.looseRoutesById[f.routeId],p=t.router.options?.defaultNotFoundComponent;!g.options.notFoundComponent&&p&&(g.options.notFoundComponent=p),u.routeId=f.routeId;const v=f.routeId===t.router.routeTree.id;t.updateMatch(f.id,m=>({...m,...v?{status:"success",globalNotFound:!0,error:void 0}:{status:"notFound",error:u},isFetching:!1})),d=h,await lt(g,["notFoundComponent"])}else if(!t.preload){const h=t.matches[0];h.globalNotFound||t.router.getMatch(h.id)?.globalNotFound&&t.updateMatch(h.id,f=>({...f,globalNotFound:!1,error:void 0}))}if(t.serialError&&t.firstBadMatchIndex!==void 0){const h=t.router.looseRoutesById[t.matches[t.firstBadMatchIndex].routeId];await lt(h,["errorComponent"])}for(let h=0;h<=d;h++){const{id:f,routeId:g}=t.matches[h],p=t.router.looseRoutesById[g];try{const v=jo(t,f,p);if(v){const m=await v;t.updateMatch(f,S=>({...S,...m}))}}catch(v){console.error(`Error executing head for route ${g}:`,v)}}const c=ys(t);if(ot(c)&&await c,u)throw u;if(t.serialError&&!t.preload&&!t.onReady)throw t.serialError;return t.matches}function An(e,t){const s=t.map(n=>e.options[n]?.preload?.()).filter(Boolean);if(s.length!==0)return Promise.all(s)}function lt(e,t=bt){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(n=>{const{id:r,...i}=n.options;Object.assign(e.options,i),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);const s=()=>e._componentsLoaded?void 0:t===bt?(()=>{if(e._componentsPromise===void 0){const n=An(e,bt);n?e._componentsPromise=n.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():An(e,t);return e._lazyPromise?e._lazyPromise.then(s):s()}function kr(e){for(const t of bt)if(e.options[t]?.preload)return!0;return!1}var bt=["component","errorComponent","pendingComponent","notFoundComponent"];function qo(e){return{input:({url:t})=>{for(const s of e)t=Cs(s,t);return t},output:({url:t})=>{for(let s=e.length-1;s>=0;s--)t=$r(e[s],t);return t}}}function Wo(e){const t=Lr(e.basepath),s=`/${t}`,n=e.caseSensitive?s:s.toLowerCase(),r=`${n}/`;return{input:({url:i})=>{const o=e.caseSensitive?i.pathname:i.pathname.toLowerCase();return o===n?i.pathname="/":o.startsWith(r)&&(i.pathname=i.pathname.slice(s.length)),i},output:({url:i})=>(i.pathname=It(["/",t,i.pathname]),i)}}function Cs(e,t){const s=e?.input?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function $r(e,t){const s=e?.output?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function Ko(e,t){const{createMutableStore:s,createReadonlyStore:n,batch:r,init:i}=t,o=new Map,a=new Map,l=new Map,u=s(e.status),d=s(e.loadedAt),c=s(e.isLoading),h=s(e.isTransitioning),f=s(e.location),g=s(e.resolvedLocation),p=s(e.statusCode),v=s(e.redirect),m=s([]),S=s([]),C=s([]),I=n(()=>Yt(o,m.get())),y=n(()=>Yt(a,S.get())),R=n(()=>Yt(l,C.get())),b=n(()=>m.get()[0]),_=n(()=>m.get().some(F=>o.get(F)?.get().status==="pending")),M=n(()=>({locationHref:f.get().href,resolvedLocationHref:g.get()?.href,status:u.get()})),P=n(()=>({status:u.get(),loadedAt:d.get(),isLoading:c.get(),isTransitioning:h.get(),matches:I.get(),location:f.get(),resolvedLocation:g.get(),statusCode:p.get(),redirect:v.get()})),E=at(64);function O(F){let L=E.get(F);return L||(L=n(()=>{const B=m.get();for(const N of B){const he=o.get(N);if(he&&he.routeId===F)return he.get()}}),E.set(F,L)),L}const se={status:u,loadedAt:d,isLoading:c,isTransitioning:h,location:f,resolvedLocation:g,statusCode:p,redirect:v,matchesId:m,pendingIds:S,cachedIds:C,matches:I,pendingMatches:y,cachedMatches:R,firstId:b,hasPending:_,matchRouteDeps:M,matchStores:o,pendingMatchStores:a,cachedMatchStores:l,__store:P,getRouteMatchStore:O,setMatches:H,setPending:j,setCached:Z};H(e.matches),i?.(se);function H(F){Zt(F,o,m,s,r)}function j(F){Zt(F,a,S,s,r)}function Z(F){Zt(F,l,C,s,r)}return se}function Yt(e,t){const s=[];for(const n of t){const r=e.get(n);r&&s.push(r.get())}return s}function Zt(e,t,s,n,r){const i=e.map(a=>a.id),o=new Set(i);r(()=>{for(const a of t.keys())o.has(a)||t.delete(a);for(const a of e){const l=t.get(a.id);if(!l){const u=n(a);u.routeId=a.routeId,t.set(a.id,u);continue}l.routeId=a.routeId,l.get()!==a&&l.set(a)}Co(s.get(),i)||s.set(i)})}var Re="__TSR_index",On="popstate",Ln="beforeunload";function Qo(e){let t=e.getLocation();const s=new Set,n=o=>{t=e.getLocation(),s.forEach(a=>a({location:t,action:o}))},r=o=>{e.notifyOnIndexChange??!0?n(o):t=e.getLocation()},i=async({task:o,navigateOpts:a,...l})=>{if(a?.ignoreBlocker??!1){o();return}const u=e.getBlockers?.()??[],d=l.type==="PUSH"||l.type==="REPLACE";if(typeof document<"u"&&u.length&&d)for(const c of u){const h=Ot(l.path,l.state);if(await c.blockerFn({currentLocation:t,nextLocation:h,action:l.type})){e.onBlocked?.();return}}o()};return{get location(){return t},get length(){return e.getLength()},subscribers:s,subscribe:o=>(s.add(o),()=>{s.delete(o)}),push:(o,a,l)=>{const u=t.state[Re];a=Fn(u+1,a),i({task:()=>{e.pushState(o,a),n({type:"PUSH"})},navigateOpts:l,type:"PUSH",path:o,state:a})},replace:(o,a,l)=>{const u=t.state[Re];a=Fn(u,a),i({task:()=>{e.replaceState(o,a),n({type:"REPLACE"})},navigateOpts:l,type:"REPLACE",path:o,state:a})},go:(o,a)=>{i({task:()=>{e.go(o),r({type:"GO",index:o})},navigateOpts:a,type:"GO"})},back:o=>{i({task:()=>{e.back(o?.ignoreBlocker??!1),r({type:"BACK"})},navigateOpts:o,type:"BACK"})},forward:o=>{i({task:()=>{e.forward(o?.ignoreBlocker??!1),r({type:"FORWARD"})},navigateOpts:o,type:"FORWARD"})},canGoBack:()=>t.state[Re]!==0,createHref:o=>e.createHref(o),block:o=>{if(!e.setBlockers)return()=>{};const a=e.getBlockers?.()??[];return e.setBlockers([...a,o]),()=>{const l=e.getBlockers?.()??[];e.setBlockers?.(l.filter(u=>u!==o))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:n}}function Fn(e,t){t||(t={});const s=js();return{...t,key:s,__TSR_key:s,[Re]:e}}function Jo(e){const t=e?.window??(typeof document<"u"?window:void 0),s=t.history.pushState,n=t.history.replaceState;let r=[];const i=()=>r,o=_=>r=_,a=e?.createHref??(_=>_),l=e?.parseLocation??(()=>Ot(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){const _=js();t.history.replaceState({[Re]:0,key:_,__TSR_key:_},"")}let u=l(),d,c=!1,h=!1,f=!1,g=!1;const p=()=>u;let v,m;const S=()=>{v&&(b._ignoreSubscribers=!0,(v.isPush?t.history.pushState:t.history.replaceState)(v.state,"",v.href),b._ignoreSubscribers=!1,v=void 0,m=void 0,d=void 0)},C=(_,M,P)=>{const E=a(M);m||(d=u),u=Ot(M,P),v={href:E,state:P,isPush:v?.isPush||_==="push"},m||(m=Promise.resolve().then(()=>S()))},I=_=>{u=l(),b.notify({type:_})},y=async()=>{if(h){h=!1;return}const _=l(),M=_.state[Re]-u.state[Re],P=M===1,E=M===-1,O=!P&&!E||c;c=!1;const se=O?"GO":E?"BACK":"FORWARD",H=O?{type:"GO",index:M}:{type:E?"BACK":"FORWARD"};if(f)f=!1;else{const j=i();if(typeof document<"u"&&j.length){for(const Z of j)if(await Z.blockerFn({currentLocation:u,nextLocation:_,action:se})){h=!0,t.history.go(1),b.notify(H);return}}}u=l(),b.notify(H)},R=_=>{if(g){g=!1;return}let M=!1;const P=i();if(typeof document<"u"&&P.length)for(const E of P){const O=E.enableBeforeUnload??!0;if(O===!0){M=!0;break}if(typeof O=="function"&&O()===!0){M=!0;break}}if(M)return _.preventDefault(),_.returnValue=""},b=Qo({getLocation:p,getLength:()=>t.history.length,pushState:(_,M)=>C("push",_,M),replaceState:(_,M)=>C("replace",_,M),back:_=>(_&&(f=!0),g=!0,t.history.back()),forward:_=>{_&&(f=!0),g=!0,t.history.forward()},go:_=>{c=!0,t.history.go(_)},createHref:_=>a(_),flush:S,destroy:()=>{t.history.pushState=s,t.history.replaceState=n,t.removeEventListener(Ln,R,{capture:!0}),t.removeEventListener(On,y)},onBlocked:()=>{d&&u!==d&&(u=d)},getBlockers:i,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Ln,R,{capture:!0}),t.addEventListener(On,y),t.history.pushState=function(..._){const M=s.apply(t.history,_);return b._ignoreSubscribers||I("PUSH"),M},t.history.replaceState=function(..._){const M=n.apply(t.history,_);return b._ignoreSubscribers||I("REPLACE"),M},b}function Xo(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"");return t.startsWith("//")&&(t="/"+t.replace(/^\/+/,"")),t}function Ot(e,t){const s=Xo(e),n=s.indexOf("#"),r=s.indexOf("?"),i=js();return{href:s,pathname:s.substring(0,n>0?r>0?Math.min(n,r):n:r>0?r:s.length),hash:n>-1?s.substring(n):"",search:r>-1?s.slice(r,n===-1?void 0:n):"",state:t||{[Re]:0,key:i,__TSR_key:i}}}function js(){return(Math.random()+1).toString(36).substring(7)}function Ge(e,t){const s=t,n=e;return{fromLocation:s,toLocation:n,pathChanged:s?.pathname!==n.pathname,hrefChanged:s?.href!==n.href,hashChanged:s?.hash!==n.hash}}var Rs=new WeakMap,Yo=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=s=>s(),this.update=s=>{const n=this.options,r=this.basepath??n?.basepath??"/",i=this.basepath===void 0,o=n?.rewrite;if(this.options={...n,...s},this.isServer=this.options.isServer??typeof document>"u",this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=Oo(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=Jo()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost"),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let d;this.resolvePathCache=at(1e3),d=this.buildRouteTree(),this.setRoutes(d)}if(!this.stores&&this.latestLocation){const d=this.getStoreConfig(this);this.batch=d.batch,this.stores=Ko(ea(this.latestLocation),d),da(this)}let a=!1;const l=this.options.basepath??"/",u=this.options.rewrite;if(i||r!==l||o!==u){this.basepath=l;const d=[],c=Lr(l);c&&c!=="/"&&d.push(Wo({basepath:l})),u&&d.push(u),this.rewrite=d.length===0?void 0:d.length===1?d[0]:qo(d),this.history&&this.updateLatestLocation(),a=!0}a&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<"u"&&"CSS"in window&&typeof window.CSS?.supports=="function"&&(this.isViewTransitionTypesSupported=window.CSS.supports("selector(:active-view-transition-type(a))"))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const s=Eo(this.routeTree,this.options.caseSensitive,(n,r)=>{n.init({originalIndex:r})});return this.options.routeMasks&&Io(this.options.routeMasks,s.processedTree),s},this.subscribe=(s,n)=>{const r={eventType:s,fn:n};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=s=>{this.subscribers.forEach(n=>{n.eventType===s.type&&n.fn(s)})},this.parseLocation=(s,n)=>{const r=({pathname:l,search:u,hash:d,href:c,state:h})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(l)){const m=this.options.parseSearch(u),S=this.options.stringifySearch(m);return{href:l+S+d,publicHref:l+S+d,pathname:Je(l).path,external:!1,searchStr:S,search:_e(n?.search,m),hash:Je(d.slice(1)).path,state:xe(n?.state,h)}}const f=new URL(c,this.origin),g=Cs(this.rewrite,f),p=this.options.parseSearch(g.search),v=this.options.stringifySearch(p);return g.search=v,{href:g.href.replace(g.origin,""),publicHref:c,pathname:Je(g.pathname).path,external:!!this.rewrite&&g.origin!==this.origin,searchStr:v,search:_e(n?.search,p),hash:Je(g.hash.slice(1)).path,state:xe(n?.state,h)}},i=r(s),{__tempLocation:o,__tempKey:a}=i.state;if(o&&(!a||a===this.tempLocationKey)){const l=r(o);return l.state.key=i.state.key,l.state.__TSR_key=i.state.__TSR_key,delete l.state.__tempLocation,{...l,maskedLocation:i}}return i},this.resolvePathWithBase=(s,n)=>Ao({base:s,to:n.includes("//")?Hs(n):n,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(s,n,r)=>typeof s=="string"?this.matchRoutesInternal({pathname:s,search:n},r):this.matchRoutesInternal(s,n),this.getMatchedRoutes=s=>ta({pathname:s,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=s=>{const n=this.getMatch(s);n&&(n.abortController.abort(),clearTimeout(n._nonReactive.pendingTimeout),n._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(s=>{this.cancelMatch(s)}),this.stores.matchesId.get().forEach(s=>{if(this.stores.pendingMatchStores.has(s))return;const n=this.stores.matchStores.get(s)?.get();n&&(n.status==="pending"||n.isFetching==="loader")&&this.cancelMatch(s)})},this.buildLocation=s=>{const n=(i={})=>{const o=i._fromLocation||this.pendingBuiltLocation||this.latestLocation,a=this.matchRoutesLightweight(o);i.from;const l=i.unsafeRelative==="path"?o.pathname:i.from??a.fullPath,u=i.to?`${i.to}`:void 0,d=a.search,c=Object.assign(Object.create(null),a.params),h=u?.charCodeAt(0)===47?"/":this.resolvePathWithBase(l,"."),f=u?this.resolvePathWithBase(h,u):h,g=i.params===!1||i.params===null?Object.create(null):(i.params??!0)===!0?c:Object.assign(c,ue(i.params,c)),p=this.routesByPath[ce(f)];let v;if(p)v=this.getRouteBranch(p);else if(f.includes("$"))v=[];else{const E=this.getMatchedRoutes(f);v=E.matchedRoutes,this.options.notFoundRoute&&(!E.foundRoute||E.foundRoute.path!=="/"&&E.routeParams["**"])&&(v=[...v,this.options.notFoundRoute])}if(v.length&&Tt(g))for(const E of v){const O=E.options.params?.stringify??E.options.stringifyParams;if(O)try{Object.assign(g,O(g))}catch{}}const m=s.leaveParams?f:Je(_n({path:f,params:g,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path;let S=d;if(s._includeValidateSearch&&this.options.search?.strict){const E={};v.forEach(O=>{if(O.options.validateSearch)try{Object.assign(E,_t(O.options.validateSearch,{...E,...S}))}catch{}}),S=E}S=sa({search:S,dest:i,destRoutes:v,_includeValidateSearch:s._includeValidateSearch}),S=_e(d,S);const C=this.options.stringifySearch(S),I=i.hash===!0?o.hash:i.hash?ue(i.hash,o.hash):void 0,y=I?`#${I}`:"";let R=i.state===!0?o.state:i.state?ue(i.state,o.state):{};R=xe(o.state,R);const b=`${m}${C}${y}`;let _,M,P=!1;if(this.rewrite){const E=new URL(b,this.origin),O=$r(this.rewrite,E);_=E.href.replace(E.origin,""),O.origin!==this.origin?(M=O.href,P=!0):M=O.pathname+O.search+O.hash}else _=yo(b),M=_;return{publicHref:M,href:_,pathname:m,search:S,searchStr:C,state:R,hash:I??"",external:P,unmaskOnReload:i.unmaskOnReload}},r=(i={},o)=>{const a=n(i);let l=o?n(o):void 0;if(!l){const u=Object.create(null);if(this.options.routeMasks){const d=wo(a.pathname,this.processedTree);if(d){Object.assign(u,d.rawParams);const{from:c,params:h,...f}=d.route,g=h===!1||h===null?Object.create(null):(h??!0)===!0?u:Object.assign(u,ue(h,u));o={from:s.from,...f,params:g},l=n(o)}}}return l&&(a.maskedLocation=l),a};return s.mask?r(s,{from:s.from,...s.mask}):r(s)},this.commitLocation=async({viewTransition:s,ignoreBlocker:n,...r})=>{let i;const o=()=>{const u=["key","__TSR_key","__TSR_index","__hashScrollIntoViewOptions"];u.forEach(c=>{r.state[c]=this.latestLocation.state[c]});const d=Ce(r.state,this.latestLocation.state);return u.forEach(c=>{delete r.state[c]}),d},a=ce(this.latestLocation.href)===ce(r.href);let l=this.commitLocationPromise;if(this.commitLocationPromise=He(()=>{l?.resolve(),l=void 0}),a&&o())this.load();else{let{maskedLocation:u,hashScrollIntoView:d,...c}=r;u&&(c={...u,state:{...u.state,__tempKey:void 0,__tempLocation:{...c,search:c.searchStr,state:{...c.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(c.unmaskOnReload??this.options.unmaskOnReload??!1)&&(c.state.__tempKey=this.tempLocationKey)),c.state.__hashScrollIntoViewOptions=d??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=s,i=r.replace?"REPLACE":"PUSH",this.history[i==="REPLACE"?"replace":"push"](c.publicHref,c.state,{ignoreBlocker:n})}return this._scroll.next=r.resetScroll??!0,this.history.subscribers.size||this.load(i?{action:{type:i}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:s,resetScroll:n,hashScrollIntoView:r,viewTransition:i,ignoreBlocker:o,href:a,...l}={})=>{if(a){const c=this.history.location.state.__TSR_index,h=Ot(a,{__TSR_index:s?c:c+1}),f=new URL(h.pathname,this.origin);l.to=Cs(this.rewrite,f).pathname,l.search=this.options.parseSearch(h.search),l.hash=h.hash.slice(1)}const u=this.buildLocation({...l,_includeValidateSearch:!0});this.pendingBuiltLocation=u;const d=this.commitLocation({...u,viewTransition:i,replace:s,resetScroll:n,hashScrollIntoView:r,ignoreBlocker:o});return queueMicrotask(()=>{this.pendingBuiltLocation===u&&(this.pendingBuiltLocation=void 0)}),d},this.navigate=async({to:s,reloadDocument:n,href:r,publicHref:i,...o})=>{let a=!1;if(r)try{new URL(`${r}`),a=!0}catch{}if(a&&!n&&(n=!0),n){if(s!==void 0||!r){const u=this.buildLocation({to:s,...o});r=r??u.publicHref,i=i??u.publicHref}const l=!a&&i?i:r;if(Me(l,this.protocolAllowlist))return;if(!o.ignoreBlocker){const u=this.history.getBlockers?.()??[];for(const d of u)if(d?.blockerFn&&await d.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:"PUSH"}))return}o.replace?window.location.replace(l):window.location.href=l;return}return this.buildAndCommitLocation({...o,href:r,to:s,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();const s=this.matchRoutes(this.latestLocation),n=this.stores.cachedMatches.get().filter(r=>!s.some(i=>i.id===r.id));this.batch(()=>{this.stores.status.set("pending"),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(s),this.stores.setCached(n)})},this.load=async s=>{const n=s?.action?.type;let r,i,o;const a=this.stores.resolvedLocation.get()??this.stores.location.get();for(o=new Promise(u=>{this.startTransition(async()=>{try{this.beforeLoad(),n?Rs.set(this.latestLocation,n):Rs.delete(this.latestLocation);const d=this.latestLocation,c=Ge(d,this.stores.resolvedLocation.get());this.stores.redirect.get()||this.emit({type:"onBeforeNavigate",...c}),this.emit({type:"onBeforeLoad",...c}),await Tn({router:this,sync:s?.sync,forceStaleReload:a.href===d.href,matches:this.stores.pendingMatches.get(),location:d,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let h=null,f=null,g=null,p=null;this.batch(()=>{const v=this.stores.pendingMatches.get(),m=v.length,S=this.stores.matches.get();h=m?S.filter(y=>!this.stores.pendingMatchStores.has(y.id)):null;const C=new Set;for(const y of this.stores.pendingMatchStores.values())y.routeId&&C.add(y.routeId);const I=new Set;for(const y of this.stores.matchStores.values())y.routeId&&I.add(y.routeId);f=m?S.filter(y=>!C.has(y.routeId)):null,g=m?v.filter(y=>!I.has(y.routeId)):null,p=m?v.filter(y=>I.has(y.routeId)):S,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),m&&(this.stores.setMatches(v),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...h.filter(y=>y.status!=="error"&&y.status!=="notFound"&&y.status!=="redirected")]),this.clearExpiredCache())});for(const[v,m]of[[f,"onLeave"],[g,"onEnter"],[p,"onStay"]])if(v)for(const S of v)this.looseRoutesById[S.routeId].options[m]?.(S)})})}})}catch(d){Y(d)?(r=d,this.navigate({...r.options,replace:!0,ignoreBlocker:!0})):q(d)&&(i=d);const c=r?r.status:i?404:this.stores.matches.get().some(h=>h.status==="error")?500:200;this.batch(()=>{this.stores.statusCode.set(c),this.stores.redirect.set(r)})}this.latestLoadPromise===o&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),u()})}),this.latestLoadPromise=o,await o;this.latestLoadPromise&&o!==this.latestLoadPromise;)await this.latestLoadPromise;let l;this.hasNotFoundMatch()?l=404:this.stores.matches.get().some(u=>u.status==="error")&&(l=500),l!==void 0&&this.stores.statusCode.set(l)},this.startViewTransition=s=>{const n=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,n&&typeof document<"u"&&"startViewTransition"in document&&typeof document.startViewTransition=="function"){let r;if(typeof n=="object"&&this.isViewTransitionTypesSupported){const i=this.latestLocation,o=this.stores.resolvedLocation.get(),a=typeof n.types=="function"?n.types(Ge(i,o)):n.types;if(a===!1){s();return}r={update:s,types:a}}else r=s;document.startViewTransition(r)}else s()},this.updateMatch=(s,n)=>{this.startTransition(()=>{const r=this.stores.pendingMatchStores.get(s);if(r){r.set(n);return}const i=this.stores.matchStores.get(s);if(i){i.set(n);return}const o=this.stores.cachedMatchStores.get(s);if(o){const a=n(o.get());a.status==="redirected"?this.stores.cachedMatchStores.delete(s)&&this.stores.cachedIds.set(l=>l.filter(u=>u!==s)):o.set(a)}})},this.getMatch=s=>this.stores.cachedMatchStores.get(s)?.get()??this.stores.pendingMatchStores.get(s)?.get()??this.stores.matchStores.get(s)?.get(),this.invalidate=s=>{const n=r=>s?.filter?.(r)??!0?{...r,invalid:!0,...s?.forcePending||r.status==="error"||r.status==="notFound"?{status:"pending",error:void 0}:void 0}:r;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(n)),this.stores.setCached(this.stores.cachedMatches.get().map(n)),this.stores.setPending(this.stores.pendingMatches.get().map(n))}),this.shouldViewTransition=!1,this.load({sync:s?.sync})},this.getParsedLocationHref=s=>s.publicHref||"/",this.resolveRedirect=s=>{const n=s.headers.get("Location");if(!s.options.href||s.options._builtLocation){const r=s.options._builtLocation??this.buildLocation(s.options),i=this.getParsedLocationHref(r);s.options.href=i,s.headers.set("Location",i)}else if(n)try{const r=new URL(n);if(this.origin&&r.origin===this.origin){const i=r.pathname+r.search+r.hash;s.options.href=i,s.headers.set("Location",i)}}catch{}if(s.options.href&&!s.options._builtLocation&&Me(s.options.href,this.protocolAllowlist))throw new Error("Redirect blocked: unsafe protocol");return s.headers.get("Location")||s.headers.set("Location",s.options.href),s},this.clearCache=s=>{const n=s?.filter;n!==void 0?this.stores.setCached(this.stores.cachedMatches.get().filter(r=>!n(r))):this.stores.setCached([])},this.clearExpiredCache=()=>{const s=Date.now(),n=r=>{const i=this.looseRoutesById[r.routeId];if(!i.options.loader)return!0;const o=(r.preload?i.options.preloadGcTime??this.options.defaultPreloadGcTime:i.options.gcTime??this.options.defaultGcTime)??300*1e3;return r.status==="error"?!0:s-r.updatedAt>=o};this.clearCache({filter:n})},this.loadRouteChunk=lt,this.preloadRoute=async s=>{const n=s._builtLocation??this.buildLocation(s);let r=this.matchRoutes(n,{throwOnError:!0,preload:!0,dest:s});const i=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),o=new Set([...i,...this.stores.cachedIds.get()]),a=r.filter(l=>!o.has(l.id));if(a.length){const l=this.stores.cachedMatches.get();this.stores.setCached([...l,...a])}try{return r=await Tn({router:this,matches:r,location:n,preload:!0,updateMatch:(l,u)=>{i.has(l)?r=r.map(d=>d.id===l?u(d):d):this.updateMatch(l,u)}}),r}catch(l){if(Y(l))return l.options.reloadDocument?void 0:await this.preloadRoute({...l.options,_fromLocation:n});q(l)||console.error(l);return}},this.matchRoute=(s,n)=>{const r={...s,to:s.to?this.resolvePathWithBase(s.from||"",s.to):void 0,params:s.params||{},leaveParams:!0},i=this.buildLocation(r);if(n?.pending&&this.stores.status.get()!=="pending")return!1;const o=(n?.pending===void 0?!this.stores.isLoading.get():n.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),a=bo(i.pathname,n?.caseSensitive??!1,n?.fuzzy??!1,o.pathname,this.processedTree);return!a||s.params&&!Ce(a.rawParams,s.params,{partial:!0})?!1:n?.includeSearch??!0?Ce(o.search,i.search,{partial:!0})?a.rawParams:!1:a.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(s=>s.status==="notFound"||s.globalNotFound),this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??"fuzzy",stringifySearch:e.stringifySearch??Do,parseSearch:e.parseSearch??No,protocolAllowlist:e.protocolAllowlist??So}),typeof document<"u"&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:s}){this.routesById=e,this.routesByPath=t,this.processedTree=s;const n=this.options.notFoundRoute;n&&(n.init({originalIndex:99999999999}),this.routesById[n.id]=n)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=Ar(e),this.routeBranchCache.set(e,t)),t}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,t){const s=this.getMatchedRoutes(e.pathname),{foundRoute:n,routeParams:r}=s;let{matchedRoutes:i}=s,o=!1;(n?n.path!=="/"&&r["**"]:ce(e.pathname))&&(this.options.notFoundRoute?i=[...i,this.options.notFoundRoute]:o=!0);const a=o?ra(this.options.notFoundMode,i):void 0,l=new Array(i.length),u=new Map;for(const d of this.stores.matchStores.values())d.routeId&&u.set(d.routeId,d.get());for(let d=0;d<i.length;d++){const c=i[d],h=l[d-1];let f,g,p;{const O=h?.search??e.search,se=h?._strictSearch??void 0;try{const H=_t(c.options.validateSearch,{...O})??void 0;f={...O,...H},g={...se,...H},p=void 0}catch(H){let j=H;if(H instanceof Lt||(j=new Lt(H.message,{cause:H})),t?.throwOnError)throw j;f=O,g={},p=j}}const v=c.options.loaderDeps?.({search:f})??"",m=v?JSON.stringify(v):"",{interpolatedPath:S,usedParams:C}=_n({path:c.fullPath,params:r,decoder:this.pathParamsDecoder,server:this.isServer}),I=c.id+S+m,y=this.getMatch(I),R=u.get(c.id),b=y?._strictParams??C;let _;if(!y)try{Nn(c,b)}catch(O){if(q(O)||Y(O)?_=O:_=new Zo(O.message,{cause:O}),t?.throwOnError)throw _}Object.assign(r,b);const M=R?"stay":"enter";let P;if(y)P={...y,cause:M,params:R?.params??r,_strictParams:b,search:_e(R?R.search:y.search,f),_strictSearch:g};else{const O=c.options.loader||c.options.beforeLoad||c.lazyFn||kr(c)?"pending":"success";P={id:I,ssr:c.options.ssr,index:d,routeId:c.id,params:R?.params??r,_strictParams:b,pathname:S,updatedAt:Date.now(),search:R?_e(R.search,f):f,_strictSearch:g,searchError:void 0,status:O,isFetching:!1,error:void 0,paramsError:_,__routeContext:void 0,_nonReactive:{loadPromise:He()},__beforeLoadContext:void 0,context:{},abortController:new AbortController,fetchCount:0,cause:M,loaderDeps:R?xe(R.loaderDeps,v):v,invalid:!1,preload:!1,links:void 0,scripts:void 0,headScripts:void 0,meta:void 0,staticData:c.options.staticData||{},fullPath:c.fullPath}}t?.preload||(P.globalNotFound=a===c.id),P.searchError=p;const E=this.getParentContext(h);P.context={...E,...P.__routeContext,...P.__beforeLoadContext},l[d]=P}for(let d=0;d<l.length;d++){const c=l[d],h=this.looseRoutesById[c.routeId],f=this.getMatch(c.id),g=u.get(c.routeId);if(c.params=g?_e(g.params,r):r,!f){const p=l[d-1],v=this.getParentContext(p);if(h.options.context){const m={deps:c.loaderDeps,params:c.params,context:v??{},location:e,navigate:S=>this.navigate({...S,_fromLocation:e}),buildLocation:this.buildLocation,cause:c.cause,abortController:c.abortController,preload:!!c.preload,matches:l,routeId:h.id};c.__routeContext=h.options.context(m)??void 0}c.context={...v,...c.__routeContext,...c.__beforeLoadContext}}}return l}matchRoutesLightweight(e){const t=it(this.stores.matchesId.get()),s=this.lightweightCache.get(e);if(s&&s[0]===t)return s[1];const{matchedRoutes:n,routeParams:r}=this.getMatchedRoutes(e.pathname),i=it(n),o={...e.search};for(const c of n)try{Object.assign(o,_t(c.options.validateSearch,o))}catch{}const a=t&&this.stores.matchStores.get(t)?.get(),l=a&&a.routeId===i.id&&a.pathname===e.pathname;let u;if(l)u=a.params;else{const c=Object.assign(Object.create(null),r);for(const h of n)try{Nn(h,c)}catch{}u=c}const d={matchedRoutes:n,fullPath:i.fullPath,search:o,params:u};return this.lightweightCache.set(e,[t,d]),d}},Lt=class extends Error{},Zo=class extends Error{};function ea(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:"idle",resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function _t(e,t){if(e==null)return{};if("~standard"in e){const s=e["~standard"].validate(t);if(s instanceof Promise)throw new Lt("Async validation not supported");if(s.issues)throw new Lt(JSON.stringify(s.issues,void 0,2),{cause:s});return s.value}return"parse"in e?e.parse(t):typeof e=="function"?e(t):{}}function ta({pathname:e,routesById:t,processedTree:s}){const n=Object.create(null),r=ce(e);let i;const o=_o(r,s,!0);return o&&(i=o.route,Object.assign(n,o.rawParams)),{matchedRoutes:o?.branch||[t.__root__],routeParams:n,foundRoute:i}}function sa({search:e,dest:t,destRoutes:s,_includeValidateSearch:n}){return na(s)(e,t,n??!1)}function na(e){let t,s;const n=[];for(const i of e){const o=i.options;if("search"in o)o.search?.middlewares&&n.push(...o.search.middlewares);else if(o.preSearchFilters||o.postSearchFilters){const l=({search:u,next:d})=>{const c=d(o.preSearchFilters?o.preSearchFilters.reduce((h,f)=>f(h),u):u);return o.postSearchFilters?o.postSearchFilters.reduce((h,f)=>f(h),c):c};n.push(l)}const a=o.validateSearch;if(a){const l=({search:u,next:d,meta:c})=>{const h=d(u);if(s)try{const f=_t(a,h);if(c&&f)for(const g in f)g in h||(c.defaulted||=new Map).set(g,f[g]);return{...h,...f}}catch{}return h};n.push(l)}}const r=(i,o,a)=>{if(i>=n.length){if(!t.search)return{};if(t.search===!0)return o;const u=ue(t.search,o);return a&&(a.explicit=u),u}const l=(u,d)=>{if(d){const c=a||{};return{search:r(i+1,u,c),meta:c}}return r(i+1,u,a)};return n[i]({search:o,next:l,meta:a})};return function(o,a,l){return t=a,s=l,r(0,o)}}function ra(e,t){if(e!=="root")for(let s=t.length-1;s>=0;s--){const n=t[s];if(n.children)return n.id}return wt}function Nn(e,t){const s=e.options.params?.parse??e.options.parseParams;if(s){const n=s(t);if(n===!1)throw new Error("Route params.parse returned false for a matched route");Object.assign(t,n)}}function ia(){try{return sessionStorage}catch{return}}var oa="tsr-scroll-restoration-v1_3",Br=ia();function aa(){try{return JSON.parse(Br?.getItem("tsr-scroll-restoration-v1_3")||"{}")}catch{return{}}}function la(){try{Br?.setItem(oa,JSON.stringify($e))}catch{}}var $e=aa(),Dn="data-scroll-restoration-id",ua=e=>e.state.__TSR_key||e.href;function ca(e){const t=e.getAttribute(Dn);if(t)return`[${Dn}="${t}"]`;let s="",n=e,r;for(;r=n.parentNode;){let i=1,o=n;for(;o=o.previousElementSibling;)i++;const a=`${n.localName}:nth-child(${i})`;s=s?`${a} > ${s}`:a,n=r}return s}var pt=!1,Be="window";function Is(e){try{return typeof e=="function"?e():document.querySelector(e)}catch{}}function kn(e){const t=[];for(const s of e){if(s===Be)continue;const n=Is(s);n&&t.push(n)}return t}function da(e,t){const s=t??e.options.scrollRestoration,n=e._scroll;s&&(n.restoring=!0);const r=e.options.getScrollRestorationKey||ua,i=new Map,o=(u,d,c)=>{const h=i.get(u)||{};h.scrollX=d,h.scrollY=c,i.set(u,h)},a=u=>{if(!(pt||!n.restoring))if(u.target===document)o(Be,scrollX,scrollY);else{const d=u.target;o(d,d.scrollLeft,d.scrollTop)}},l=u=>{if(!n.restoring)return;const d=$e[u]||={};for(const[c,h]of i)c===Be?d[Be]=h:c.isConnected&&(d[ca(c)]=h)};s&&!n.restoration&&(n.restoration=!0,pt=!1,history.scrollRestoration="manual",document.addEventListener("scroll",a,!0),e.subscribe("onBeforeLoad",u=>{u.fromLocation&&l(r(u.fromLocation)),i.clear()}),addEventListener("pagehide",()=>{l(r(e.stores.resolvedLocation.get()??e.stores.location.get())),la()})),!n.reset&&(n.reset=!0,e.subscribe("onRendered",u=>{const d=e.options.scrollRestorationBehavior,c=e.options.scrollToTopSelectors,h=n.next;let f;if(i.clear(),h||(n.next=!0),typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation}))return;const g=r(u.toLocation),p=u.fromLocation&&r(u.fromLocation);if(n.restoring&&p&&p!==g){const v=$e[p];if(v){let m=$e[g];for(const S in v){if(S===Be){if(h)continue}else{const C=Is(S);if(!C||h&&c&&(f??=kn(c),f.includes(C)))continue}m||(m=$e[g]={}),m[S]??=v[S]}}}pt=!0;try{const v=u.toLocation.hash,m=u.toLocation.state.__hashScrollIntoViewOptions??!0;let S=!1;if(h){const C=Rs.get(u.toLocation),I=v&&m&&(C==="PUSH"||C==="REPLACE"),y=n.restoring?$e[g]:void 0;if(y)for(const R in y){const{scrollX:b,scrollY:_}=y[R];if(R===Be){if(I)continue;scrollTo({top:_,left:b,behavior:d}),S=!0}else{const M=Is(R);M&&(M.scrollLeft=b,M.scrollTop=_)}}if(!S&&!v){const R={top:0,left:0,behavior:d};if(scrollTo(R),c){f??=kn(c);for(const b of f)b.scrollTo(R)}}}!S&&v&&m&&document.getElementById(v)?.scrollIntoView(m)}finally{pt=!1}}))}var ha="Error preloading route! ☝️",Ur=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=t=>{this.originalIndex=t.originalIndex;const s=this.options,n=!s?.path&&!s?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=wt:this.parentRoute||de();let r=n?wt:s?.path;r&&r!=="/"&&(r=Or(r));const i=s?.id||r;let o=n?wt:It([this.parentRoute.id==="__root__"?"":this.parentRoute.id,i]);r==="__root__"&&(r="/"),o!=="__root__"&&(o=It(["/",o]));const a=o==="__root__"?"/":It([this.parentRoute.fullPath,r]);this._path=r,this._id=o,this._fullPath=a,this._to=ce(a)},this.addChildren=t=>this._addFileChildren(t),this._addFileChildren=t=>(Array.isArray(t)&&(this.children=t),typeof t=="object"&&t!==null&&(this.children=Object.values(t)),this),this._addFileTypes=()=>this,this.updateLoader=t=>(Object.assign(this.options,t),this),this.update=t=>(Object.assign(this.options,t),this),this.lazy=t=>(this.lazyFn=t,this),this.redirect=t=>Bo({from:this.fullPath,...t}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw new Error("Route cannot have both an 'id' and a 'path' option.")}},fa=class extends Ur{constructor(e){super(e)}};function zs(e){const t=e.errorComponent??qs;return(0,x.jsx)(ga,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:s,reset:n})=>s?w.createElement(t,{error:s,reset:n}):e.children})}var ga=class extends w.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,t){const s=e.getResetKey();return t.error&&t.resetKey!==s?{resetKey:s,error:null}:{resetKey:s}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,t){this.props.onCatch&&this.props.onCatch(e,t)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function qs({error:e}){const[t,s]=w.useState(!1);return(0,x.jsxs)("div",{style:{padding:".5rem",maxWidth:"100%"},children:[(0,x.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:".5rem"},children:[(0,x.jsx)("strong",{style:{fontSize:"1rem"},children:"Something went wrong!"}),(0,x.jsx)("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:()=>s(n=>!n),children:t?"Hide Error":"Show Error"})]}),(0,x.jsx)("div",{style:{height:".25rem"}}),t?(0,x.jsx)("div",{children:(0,x.jsx)("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"},children:e.message?(0,x.jsx)("code",{children:e.message}):null})}):null]})}function pa({children:e,fallback:t=null}){return Vr()?(0,x.jsx)(w.Fragment,{children:e}):(0,x.jsx)(w.Fragment,{children:t})}function Vr(){return w.useSyncExternalStore(ma,()=>!0,()=>!1)}function ma(){return()=>{}}var Gr=w.createContext(null);function re(e){return w.useContext(Gr)}var $t=w.createContext(void 0),va=w.createContext(void 0),$=(e=>(e[e.None=0]="None",e[e.Mutable=1]="Mutable",e[e.Watching=2]="Watching",e[e.RecursedCheck=4]="RecursedCheck",e[e.Recursed=8]="Recursed",e[e.Dirty=16]="Dirty",e[e.Pending=32]="Pending",e))($||{});function Sa({update:e,notify:t,unwatched:s}){return{link:n,unlink:r,propagate:i,checkDirty:o,shallowPropagate:a};function n(u,d,c){const h=d.depsTail;if(h!==void 0&&h.dep===u)return;const f=h!==void 0?h.nextDep:d.deps;if(f!==void 0&&f.dep===u){f.version=c,d.depsTail=f;return}const g=u.subsTail;if(g!==void 0&&g.version===c&&g.sub===d)return;const p=d.depsTail=u.subsTail={version:c,dep:u,sub:d,prevDep:h,nextDep:f,prevSub:g,nextSub:void 0};f!==void 0&&(f.prevDep=p),h!==void 0?h.nextDep=p:d.deps=p,g!==void 0?g.nextSub=p:u.subs=p}function r(u,d=u.sub){const c=u.dep,h=u.prevDep,f=u.nextDep,g=u.nextSub,p=u.prevSub;return f!==void 0?f.prevDep=h:d.depsTail=h,h!==void 0?h.nextDep=f:d.deps=f,g!==void 0?g.prevSub=p:c.subsTail=p,p!==void 0?p.nextSub=g:(c.subs=g)===void 0&&s(c),f}function i(u){let d=u.nextSub,c;e:do{const h=u.sub;let f=h.flags;if(f&60?f&12?f&4?!(f&48)&&l(u,h)?(h.flags=f|40,f&=1):f=0:h.flags=f&-9|32:f=0:h.flags=f|32,f&2&&t(h),f&1){const g=h.subs;if(g!==void 0){const p=(u=g).nextSub;p!==void 0&&(c={value:d,prev:c},d=p);continue}}if((u=d)!==void 0){d=u.nextSub;continue}for(;c!==void 0;)if(u=c.value,c=c.prev,u!==void 0){d=u.nextSub;continue e}break}while(!0)}function o(u,d){let c,h=0,f=!1;e:do{const g=u.dep,p=g.flags;if(d.flags&16)f=!0;else if((p&17)===17){if(e(g)){const v=g.subs;v.nextSub!==void 0&&a(v),f=!0}}else if((p&33)===33){(u.nextSub!==void 0||u.prevSub!==void 0)&&(c={value:u,prev:c}),u=g.deps,d=g,++h;continue}if(!f){const v=u.nextDep;if(v!==void 0){u=v;continue}}for(;h--;){const v=d.subs,m=v.nextSub!==void 0;if(m?(u=c.value,c=c.prev):u=v,f){if(e(d)){m&&a(v),d=u.sub;continue}f=!1}else d.flags&=-33;d=u.sub;const S=u.nextDep;if(S!==void 0){u=S;continue e}}return f}while(!0)}function a(u){do{const d=u.sub,c=d.flags;(c&48)===32&&(d.flags=c|16,(c&6)===2&&t(d))}while((u=u.nextSub)!==void 0)}function l(u,d){let c=d.depsTail;for(;c!==void 0;){if(c===u)return!0;c=c.prevDep}return!1}}function ya(e,t,s){const n=typeof e=="object",r=n?e:void 0;return{next:(n?e.next:e)?.bind(r),error:(n?e.error:t)?.bind(r),complete:(n?e.complete:s)?.bind(r)}}var ws=[],Mt=0,{link:$n,unlink:Ca,propagate:Ra,checkDirty:Hr,shallowPropagate:Bn}=Sa({update(e){return e._update()},notify(e){ws[bs++]=e,e.flags&=~$.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=$.Mutable|$.Dirty,Ft(e))}}),mt=0,bs=0,ae,_s=0;function jr(e){try{++_s,e()}finally{--_s||zr()}}function Ft(e){const t=e.depsTail;let s=t!==void 0?t.nextDep:e.deps;for(;s!==void 0;)s=Ca(s,e)}function zr(){if(!(_s>0)){for(;mt<bs;){const e=ws[mt];ws[mt++]=void 0,e.notify()}mt=0,bs=0}}function Un(e,t){const s=typeof e=="function",n=e,r={_snapshot:s?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:s?$.None:$.Mutable,get(){return ae!==void 0&&$n(r,ae,Mt),r._snapshot},subscribe(i){const o=ya(i),a={current:!1},l=Ia(()=>{r.get(),a.current?o.next?.(r._snapshot):a.current=!0});return{unsubscribe:()=>{l.stop()}}},_update(i){const o=ae,a=t?.compare??Object.is;if(s)ae=r,++Mt,r.depsTail=void 0;else if(i===void 0)return!1;s&&(r.flags=$.Mutable|$.RecursedCheck);try{const l=r._snapshot,u=typeof i=="function"?i(l):i===void 0&&s?n(l):i;return l===void 0||!a(l,u)?(r._snapshot=u,!0):!1}finally{ae=o,s&&(r.flags&=~$.RecursedCheck),Ft(r)}}};return s?(r.flags=$.Mutable|$.Dirty,r.get=function(){const i=r.flags;if(i&$.Dirty||i&$.Pending&&Hr(r.deps,r)){if(r._update()){const o=r.subs;o!==void 0&&Bn(o)}}else i&$.Pending&&(r.flags=i&~$.Pending);return ae!==void 0&&$n(r,ae,Mt),r._snapshot}):r.set=function(i){if(r._update(i)){const o=r.subs;o!==void 0&&(Ra(o),Bn(o),zr())}},r}function Ia(e){const t=()=>{const n=ae;ae=s,++Mt,s.depsTail=void 0,s.flags=$.Watching|$.RecursedCheck;try{return e()}finally{ae=n,s.flags&=~$.RecursedCheck,Ft(s)}},s={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:$.Watching|$.RecursedCheck,notify(){const n=this.flags;n&$.Dirty||n&$.Pending&&Hr(this.deps,this)?t():this.flags=$.Watching},stop(){this.flags=$.None,this.depsTail=void 0,Ft(this)}};return t(),s}var wa=je((e=>{var t=Ds();function s(h,f){return h===f&&(h!==0||1/h===1/f)||h!==h&&f!==f}var n=typeof Object.is=="function"?Object.is:s,r=t.useState,i=t.useEffect,o=t.useLayoutEffect,a=t.useDebugValue;function l(h,f){var g=f(),p=r({inst:{value:g,getSnapshot:f}}),v=p[0].inst,m=p[1];return o(function(){v.value=g,v.getSnapshot=f,u(v)&&m({inst:v})},[h,g,f]),i(function(){return u(v)&&m({inst:v}),h(function(){u(v)&&m({inst:v})})},[h]),a(g),g}function u(h){var f=h.getSnapshot;h=h.value;try{var g=f();return!n(h,g)}catch{return!0}}function d(h,f){return f()}var c=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;e.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:c})),ba=je(((e,t)=>{t.exports=wa()})),_a=je((e=>{var t=Ds(),s=ba();function n(d,c){return d===c&&(d!==0||1/d===1/c)||d!==d&&c!==c}var r=typeof Object.is=="function"?Object.is:n,i=s.useSyncExternalStore,o=t.useRef,a=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(d,c,h,f,g){var p=o(null);if(p.current===null){var v={hasValue:!1,value:null};p.current=v}else v=p.current;p=l(function(){function S(b){if(!C){if(C=!0,I=b,b=f(b),g!==void 0&&v.hasValue){var _=v.value;if(g(_,b))return y=_}return y=b}if(_=y,r(I,b))return _;var M=f(b);return g!==void 0&&g(_,M)?(I=b,_):(I=b,y=M)}var C=!1,I,y,R=h===void 0?null:h;return[function(){return S(c())},R===null?void 0:function(){return S(R())}]},[c,h,f,g]);var m=i(d,p[0],p[1]);return a(function(){v.hasValue=!0,v.value=m},[m]),u(m),m}})),Ma=je(((e,t)=>{t.exports=_a()})),Ea=Ma();function xa(e,t){return e===t}function Q(e,t,s=xa){const n=(0,w.useCallback)(i=>{if(!e)return()=>{};const{unsubscribe:o}=e.subscribe(i);return o},[e]),r=(0,w.useCallback)(()=>e?.get(),[e]);return(0,Ea.useSyncExternalStoreWithSelector)(n,r,r,t,s)}var es={get(){},subscribe(){return{unsubscribe(){}}}};function qr(e,t){const s=w.useRef();return n=>{const r=e?.select?e.select(n):n;return e?.structuralSharing??t.options.defaultStructuralSharing?s.current=xe(s.current,r):r}}function Oe(e){const t=re(),s=w.useContext(e.from?va:$t),n=e.from?t.stores.getRouteMatchStore(e.from):t.stores.matchStores.get(s),r=qr(e,t),i=Q(n??es,o=>o?r(o):es);if(i!==es)return i;(e.shouldThrow??!0)&&de()}function Wr(e){return Oe({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function Kr(e){const{select:t,...s}=e;return Oe({...s,select:n=>t?t(n.loaderDeps):n.loaderDeps})}function Qr(e){return Oe({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const s=e.strict===!1?t.params:t._strictParams;return e.select?e.select(s):s}})}function Jr(e){return Oe({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function Xr(e){const t=re();return w.useCallback(s=>t.navigate({...s,from:s.from??e?.from}),[e?.from,t])}function Yr(e){return Oe({...e,select:t=>e.select?e.select(t.context):t.context})}var Zr=pr(Mi(),1);function Pa(e,t){const s=re(),n=ho(t),r=!1,{activeProps:i,inactiveProps:o,activeOptions:a,to:l,preload:u,preloadDelay:d,preloadIntentProximity:c,hashScrollIntoView:h,replace:f,startTransition:g,resetScroll:p,viewTransition:v,children:m,target:S,disabled:C,style:I,className:y,onClick:R,onBlur:b,onFocus:_,onMouseEnter:M,onMouseLeave:P,onTouchStart:E,ignoreBlocker:O,params:se,search:H,hash:j,state:Z,mask:F,reloadDocument:L,unsafeRelative:B,from:N,_fromLocation:he,...fe}=e;if(r){const k=zn(l);if(typeof l=="string"&&!k&&l.indexOf(":")>-1)try{return new URL(l),Me(l,s.protocolAllowlist)?{...fe,ref:n,href:void 0,...m&&{children:m},...S&&{target:S},...C&&{disabled:C},...I&&{style:I},...y&&{className:y}}:{...fe,ref:n,href:l,...m&&{children:m},...S&&{target:S},...C&&{disabled:C},...I&&{style:I},...y&&{className:y}}}catch{}const D=s.buildLocation({...e,from:e.from}),ne=jn(D.maskedLocation?D.maskedLocation.publicHref:D.publicHref,D.maskedLocation?D.maskedLocation.external:D.external,s.history,C),Qe=(()=>{if(ne?.external)return Me(ne.href,s.protocolAllowlist)?void 0:ne.href;if(!k&&typeof l=="string"&&l.indexOf(":")>-1)try{return new URL(l),Me(l,s.protocolAllowlist)?void 0:l}catch{}})(),jt=(()=>{if(Qe)return!1;const V=s.stores.location.get(),J=a?.exact??!1;if(J){if(!bn(V.pathname,D.pathname,s.basepath))return!1}else{const G=Ve(V.pathname,s.basepath),X=Ve(D.pathname,s.basepath);if(!(G.startsWith(X)&&(G.length===X.length||G[X.length]==="/")))return!1}if((a?.includeSearch??!0)&&V.search!==D.search){const G=!V.search||typeof V.search=="object"&&!Tt(V.search),X=!D.search||typeof D.search=="object"&&!Tt(D.search);if(!(G&&X)&&!Ce(V.search,D.search,{partial:!J,ignoreUndefined:!a?.explicitUndefined}))return!1}return!a?.includeHash})();if(Qe)return{...fe,ref:n,href:Qe,...m&&{children:m},...S&&{target:S},...C&&{disabled:C},...I&&{style:I},...y&&{className:y}};const zt=jt?ue(i,{})??Vn:Fe,qt=jt?Fe:ue(o,{})??Fe,rn=(()=>{const V=I,J=zt.style,G=qt.style;if(!(!V&&!J&&!G))return V&&!J&&!G?V:!V&&J&&!G?J:!V&&!J&&G?G:{...V,...J,...G}})(),on=(()=>{const V=y,J=zt.className,G=qt.className;if(!V&&!J&&!G)return"";let X="";return V&&(X=V),J&&(X=X?`${X} ${J}`:J),G&&(X=X?`${X} ${G}`:G),X})();return{...fe,...zt,...qt,href:ne?.href,ref:n,disabled:!!C,target:S,...rn&&{style:rn},...on&&{className:on},...C&&Gn,...jt&&Hn}}const Vt=Vr(),qe=w.useMemo(()=>e,[s,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),we=Q(s.stores.location,k=>k,(k,D)=>k.href===D.href),W=w.useMemo(()=>{const k={_fromLocation:we,...qe};return s.buildLocation(k)},[s,we,qe]),Js=W.maskedLocation?W.maskedLocation.publicHref:W.publicHref,Xs=W.maskedLocation?W.maskedLocation.external:W.external,We=w.useMemo(()=>jn(Js,Xs,s.history,C),[C,Xs,Js,s.history]),Ke=w.useMemo(()=>{if(We?.external)return Me(We.href,s.protocolAllowlist)?void 0:We.href;if(!zn(l)&&!(typeof l!="string"||l.indexOf(":")===-1))try{return new URL(l),Me(l,s.protocolAllowlist)?void 0:l}catch{}},[l,We,s.protocolAllowlist]),Gt=w.useMemo(()=>{if(Ke)return!1;if(a?.exact){if(!bn(we.pathname,W.pathname,s.basepath))return!1}else{const k=Ve(we.pathname,s.basepath),D=Ve(W.pathname,s.basepath);if(!(k.startsWith(D)&&(k.length===D.length||k[D.length]==="/")))return!1}return(a?.includeSearch??!0)&&!Ce(we.search,W.search,{partial:!a?.exact,ignoreUndefined:!a?.explicitUndefined})?!1:a?.includeHash?Vt&&we.hash===W.hash:!0},[a?.exact,a?.explicitUndefined,a?.includeHash,a?.includeSearch,we,Ke,Vt,W.hash,W.pathname,W.search,s.basepath]),ct=Gt?ue(i,{})??Vn:Fe,dt=Gt?Fe:ue(o,{})??Fe,Ys=[y,ct.className,dt.className].filter(Boolean).join(" "),Zs=(I||ct.style||dt.style)&&{...I,...ct.style,...dt.style},[wi,en]=w.useState(!1),tn=w.useRef(!1),Le=e.reloadDocument||Ke?!1:u??s.options.defaultPreload,Ht=d??s.options.defaultPreloadDelay??0,be=w.useCallback(()=>{s.preloadRoute({...qe,_builtLocation:W}).catch(k=>{console.warn(k),console.warn(ha)})},[s,qe,W]);co(n,w.useCallback(k=>{k?.isIntersecting&&be()},[be]),Aa,{disabled:!!C||Le!=="viewport"}),w.useEffect(()=>{tn.current||!C&&Le==="render"&&(be(),tn.current=!0)},[C,be,Le]);const bi=k=>{const D=k.currentTarget.getAttribute("target"),ne=S!==void 0?S:D;if(!C&&!Oa(k)&&!k.defaultPrevented&&(!ne||ne==="_self")&&k.button===0){k.preventDefault(),(0,Zr.flushSync)(()=>{en(!0)});const Qe=s.subscribe("onResolved",()=>{Qe(),en(!1)});s.navigate({...qe,replace:f,resetScroll:p,hashScrollIntoView:h,startTransition:g,viewTransition:v,ignoreBlocker:O})}};if(Ke)return{...fe,ref:n,href:Ke,...m&&{children:m},...S&&{target:S},...C&&{disabled:C},...I&&{style:I},...y&&{className:y},...R&&{onClick:R},...b&&{onBlur:b},..._&&{onFocus:_},...M&&{onMouseEnter:M},...P&&{onMouseLeave:P},...E&&{onTouchStart:E}};const sn=k=>{if(C||Le!=="intent")return;if(!Ht){be();return}const D=k.currentTarget;if(Ye.has(D))return;const ne=setTimeout(()=>{Ye.delete(D),be()},Ht);Ye.set(D,ne)},_i=k=>{C||Le!=="intent"||be()},nn=k=>{if(C||!Le||!Ht)return;const D=k.currentTarget,ne=Ye.get(D);ne&&(clearTimeout(ne),Ye.delete(D))};return{...fe,...ct,...dt,href:We?.href,ref:n,onClick:Ne([R,bi]),onBlur:Ne([b,nn]),onFocus:Ne([_,sn]),onMouseEnter:Ne([M,sn]),onMouseLeave:Ne([P,nn]),onTouchStart:Ne([E,_i]),disabled:!!C,target:S,...Zs&&{style:Zs},...Ys&&{className:Ys},...C&&Gn,...Gt&&Hn,...Vt&&wi&&Ta}}var Fe={},Vn={className:"active"},Gn={role:"link","aria-disabled":!0},Hn={"data-status":"active","aria-current":"page"},Ta={"data-transitioning":"transitioning"},Ye=new WeakMap,Aa={rootMargin:"100px"},Ne=e=>t=>{for(const s of e)if(s){if(t.defaultPrevented)return;s(t)}};function jn(e,t,s,n){if(!n)return t?{href:e,external:!0}:{href:s.createHref(e)||"/",external:!1}}function zn(e){if(typeof e!="string")return!1;const t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var ei=w.forwardRef((e,t)=>{const{_asChild:s,...n}=e,{type:r,...i}=Pa(n,t),o=typeof n.children=="function"?n.children({isActive:i["data-status"]==="active"}):n.children;if(!s){const{disabled:a,...l}=i;return w.createElement("a",l,o)}return w.createElement(s,i,o)});function Oa(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var La=class extends Ur{constructor(e){super(e),this.useMatch=t=>Oe({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>Yr({...t,from:this.id}),this.useSearch=t=>Jr({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>Qr({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>Kr({...t,from:this.id}),this.useLoaderData=t=>Wr({...t,from:this.id}),this.useNavigate=()=>Xr({from:this.fullPath}),this.Link=w.forwardRef((t,s)=>(0,x.jsx)(ei,{ref:s,from:this.fullPath,...t}))}};function Fa(e){return new La(e)}var Na=class extends fa{constructor(e){super(e),this.useMatch=t=>Oe({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>Yr({...t,from:this.id}),this.useSearch=t=>Jr({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>Qr({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>Kr({...t,from:this.id}),this.useLoaderData=t=>Wr({...t,from:this.id}),this.useNavigate=()=>Xr({from:this.fullPath}),this.Link=w.forwardRef((t,s)=>(0,x.jsx)(ei,{ref:s,from:this.fullPath,...t}))}};function Sc(e){return new Na(e)}function yc(e){return new Da(e,{silent:!0}).createRoute}var Da=class{constructor(e,t){this.path=e,this.createRoute=s=>{const n=Fa(s);return n.isRoot=!1,n},this.silent=t?.silent}};function Cc(e,t){let s,n,r,i;const o=()=>(s||(s=e().then(l=>{s=void 0,n=l[t??"default"]}).catch(l=>{if(r=l,po(r)&&r instanceof Error&&typeof window<"u"&&typeof sessionStorage<"u"){const u=`tanstack_router_reload:${r.message}`;sessionStorage.getItem(u)||(sessionStorage.setItem(u,"1"),i=!0)}})),s),a=function(u){if(i)throw window.location.reload(),new Promise(()=>{});if(r)throw r;if(!n)if(vn)vn(o());else throw o();return w.createElement(n,u)};return a.preload=o,a}function ka(e){const t=re(),s=`not-found-${Q(t.stores.location,n=>n.pathname)}-${Q(t.stores.status,n=>n)}`;return(0,x.jsx)(zs,{getResetKey:()=>s,onCatch:(n,r)=>{if(q(n))e.onCatch?.(n,r);else throw n},errorComponent:({error:n})=>{if(q(n))return e.fallback?.(n);throw n},children:e.children})}function $a(){return(0,x.jsx)("p",{children:"Not Found"})}function Ue(e){return(0,x.jsx)(x.Fragment,{children:e.children})}function ti(e,t,s){return t.options.notFoundComponent?(0,x.jsx)(t.options.notFoundComponent,{...s}):e.options.defaultNotFoundComponent?(0,x.jsx)(e.options.defaultNotFoundComponent,{...s}):(0,x.jsx)($a,{})}var Ba=(e,t)=>e.routeId===t.routeId&&e._displayPending===t._displayPending,Ua=(e,t)=>e[0]===t[0]&&e[1]===t[1],si=w.memo(function({matchId:t}){const s=re(),n=s.stores.matchStores.get(t);n||de();const r=Q(s.stores.loadedAt,o=>o),i=Q(n,o=>o,Ba);return(0,x.jsx)(Va,{router:s,matchId:t,resetKey:r,matchState:w.useMemo(()=>{const o=i.routeId,a=s.routesById[o].parentRoute?.id;return{routeId:o,ssr:i.ssr,_displayPending:i._displayPending,parentRouteId:a}},[i._displayPending,i.routeId,i.ssr,s.routesById])})});function Va({router:e,matchId:t,resetKey:s,matchState:n}){const r=e.routesById[n.routeId],i=r.options.pendingComponent??e.options.defaultPendingComponent,o=i?(0,x.jsx)(i,{}):null,a=r.options.errorComponent??e.options.defaultErrorComponent,l=r.options.onCatch??e.options.defaultOnCatch,u=r.isRoot?r.options.notFoundComponent??e.options.notFoundRoute?.options.component:r.options.notFoundComponent,d=n.ssr===!1||n.ssr==="data-only",c=(!r.isRoot||r.options.wrapInSuspense||d)&&(r.options.wrapInSuspense??i??(r.options.errorComponent?.preload||d))?w.Suspense:Ue,h=a?zs:Ue,f=u?ka:Ue;return(0,x.jsxs)(r.isRoot?r.options.shellComponent??Ue:Ue,{children:[(0,x.jsx)($t.Provider,{value:t,children:(0,x.jsx)(c,{fallback:o,children:(0,x.jsx)(h,{getResetKey:()=>s,errorComponent:a||qs,onCatch:(g,p)=>{if(q(g))throw g.routeId??=n.routeId,g;l?.(g,p)},children:(0,x.jsx)(f,{fallback:g=>{if(g.routeId??=n.routeId,!u||g.routeId&&g.routeId!==n.routeId||!g.routeId&&!r.isRoot)throw g;return w.createElement(u,g)},children:d||n._displayPending?(0,x.jsx)(pa,{fallback:o,children:(0,x.jsx)(qn,{matchId:t})}):(0,x.jsx)(qn,{matchId:t})})})})}),n.parentRouteId==="__root__"?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ga,{}),(e.options.scrollRestoration,null)]}):null]})}function Ga(){const e=re(),t=w.useRef();return et(()=>{const s=e.stores.resolvedLocation.get(),n=t.current;s&&(!n||n.href!==s.href)&&e.emit({type:"onRendered",...Ge(e.stores.location.get(),n??s)}),t.current=s},[Q(e.stores.resolvedLocation,s=>s?.state.__TSR_key),e]),null}var qn=w.memo(function({matchId:t}){const s=re(),n=(d,c)=>s.getMatch(d.id)?._nonReactive[c]??d._nonReactive[c],r=s.stores.matchStores.get(t);r||de();const i=Q(r,d=>d),o=i.routeId,a=s.routesById[o],l=w.useMemo(()=>{const d=(s.routesById[o].options.remountDeps??s.options.defaultRemountDeps)?.({routeId:o,loaderDeps:i.loaderDeps,params:i._strictParams,search:i._strictSearch});return d?JSON.stringify(d):void 0},[o,i.loaderDeps,i._strictParams,i._strictSearch,s.options.defaultRemountDeps,s.routesById]),u=w.useMemo(()=>{const d=a.options.component??s.options.defaultComponent;return d?(0,x.jsx)(d,{},l):(0,x.jsx)(Ha,{})},[l,a.options.component,s.options.defaultComponent]);if(i._displayPending)throw n(i,"displayPendingPromise");if(i._forcePending)throw n(i,"minPendingPromise");if(i.status==="pending"){const d=a.options.pendingMinMs??s.options.defaultPendingMinMs;if(d){const c=s.getMatch(i.id);if(c&&!c._nonReactive.minPendingPromise){const h=He();c._nonReactive.minPendingPromise=h,setTimeout(()=>{h.resolve(),c._nonReactive.minPendingPromise=void 0},d)}}throw n(i,"loadPromise")}if(i.status==="notFound")return q(i.error)||de(),ti(s,a,i.error);if(i.status==="redirected")throw Y(i.error)||de(),n(i,"loadPromise");if(i.status==="error")throw i.error;return u}),Ha=w.memo(function(){const t=re(),s=w.useContext($t);let n,r=!1,i;{const u=s?t.stores.matchStores.get(s):void 0;[n,r]=Q(u,d=>[d?.routeId,d?.globalNotFound??!1],Ua),i=Q(t.stores.matchesId,d=>d[d.findIndex(c=>c===s)+1])}const o=n?t.routesById[n]:void 0,a=t.options.defaultPendingComponent?(0,x.jsx)(t.options.defaultPendingComponent,{}):null;if(r)return o||de(),ti(t,o,void 0);if(!i)return null;const l=(0,x.jsx)(si,{matchId:i});return n==="__root__"?(0,x.jsx)(w.Suspense,{fallback:a,children:l}):l});function ja(){const e=re(),t=w.useRef({router:e,mounted:!1}),[s,n]=w.useState(!1),r=Q(e.stores.isLoading,c=>c),i=Q(e.stores.hasPending,c=>c),o=Wt(r),a=r||s||i,l=Wt(a),u=r||i,d=Wt(u);return e.startTransition=c=>{n(!0),w.startTransition(()=>{c(),n(!1)})},w.useEffect(()=>{const c=e.history.subscribe(e.load),h=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return ce(e.latestLocation.publicHref)!==ce(h.publicHref)&&e.commitLocation({...h,replace:!0}),()=>{c()}},[e,e.history]),et(()=>{if(typeof window<"u"&&e.ssr||t.current.router===e&&t.current.mounted)return;t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(h){console.error(h)}})()},[e]),et(()=>{o&&!r&&e.emit({type:"onLoad",...Ge(e.stores.location.get(),e.stores.resolvedLocation.get())})},[o,e,r]),et(()=>{d&&!u&&e.emit({type:"onBeforeRouteMount",...Ge(e.stores.location.get(),e.stores.resolvedLocation.get())})},[u,d,e]),et(()=>{if(l&&!a){const c=Ge(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:"onResolved",...c}),jr(()=>{e.stores.status.set("idle"),e.stores.resolvedLocation.set(e.stores.location.get())})}},[a,l,e]),null}function za(){const e=re(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,s=t?(0,x.jsx)(t,{}):null,n=(0,x.jsxs)(typeof document<"u"&&e.ssr?Ue:w.Suspense,{fallback:s,children:[(0,x.jsx)(ja,{}),(0,x.jsx)(qa,{})]});return e.options.InnerWrap?(0,x.jsx)(e.options.InnerWrap,{children:n}):n}function qa(){const e=re(),t=!1,s=t?e.stores.firstId.get():Q(e.stores.firstId,i=>i),n=t?e.stores.loadedAt.get():Q(e.stores.loadedAt,i=>i),r=s?(0,x.jsx)(si,{matchId:s}):null;return(0,x.jsx)($t.Provider,{value:s,children:e.options.disableGlobalCatchBoundary?r:(0,x.jsx)(zs,{getResetKey:()=>n,errorComponent:qs,onCatch:void 0,children:r})})}var Wa=e=>({createMutableStore:Un,createReadonlyStore:Un,batch:jr}),Rc=e=>new Ka(e),Ka=class extends Yo{constructor(e){super(e,Wa)}};function Qa({router:e,children:t,...s}){Tt(s)&&e.update({...e.options,...s,context:{...e.options.context,...s.context}});const n=(0,x.jsx)(Gr.Provider,{value:e,children:t});return e.options.Wrap?(0,x.jsx)(e.options.Wrap,{children:n}):n}function Ic({router:e,...t}){return(0,x.jsx)(Qa,{router:e,...t,children:(0,x.jsx)(za,{})})}function wc(e){const t=re();return Q(t.stores.location,qr(e,t))}function ve(e,t){return typeof e=="function"?e(t):e}function te(e,t){return s=>{t.setState(n=>({...n,[e]:ve(s,n[e])}))}}function Bt(e){return e instanceof Function}function Ja(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Xa(e,t){const s=[],n=r=>{r.forEach(i=>{s.push(i);const o=t(i);o!=null&&o.length&&n(o)})};return n(e),s}function T(e,t,s){let n=[],r;return i=>{let o;s.key&&s.debug&&(o=Date.now());const a=e(i);if(!(a.length!==n.length||a.some((u,d)=>n[d]!==u)))return r;n=a;let l;if(s.key&&s.debug&&(l=Date.now()),r=t(...a),s==null||s.onChange==null||s.onChange(r),s.key&&s.debug&&s!=null&&s.debug()){const u=Math.round((Date.now()-o)*100)/100,d=Math.round((Date.now()-l)*100)/100,c=d/16,h=(f,g)=>{for(f=String(f);f.length<g;)f=" "+f;return f};console.info(`%c⏱ ${h(d,5)} /${h(u,5)} ms`,`
|
|
1
|
+
import{r as pr,t as je}from"./rolldown-runtime-b3L32Ng1.js";import{nt as Ds}from"./icons-B5bSDd0r.js";import{Dt as Eo,Ot as xo}from"./radix-ui-DS4zDRqg.js";var ze=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Po=class extends ze{#t;#e;#s;constructor(){super(),this.#s=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#s=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},ks=new Po,To={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ao=class{#t=To;#e=!1;setTimeoutProvider(e){this.#t=e}setTimeout(e,t){return this.#t.setTimeout(e,t)}clearTimeout(e){this.#t.clearTimeout(e)}setInterval(e,t){return this.#t.setInterval(e,t)}clearInterval(e){this.#t.clearInterval(e)}},Ee=new Ao;function Oo(e){setTimeout(e,0)}var Lo=typeof window>"u"||"Deno"in globalThis;function K(){}function Fo(e,t){return typeof e=="function"?e(t):e}function fs(e){return typeof e=="number"&&e>=0&&e!==1/0}function mr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ye(e,t){return typeof e=="function"?e(t):e}function ee(e,t){return typeof e=="function"?e(t):e}function an(e,t){const{type:s="all",exact:n,fetchStatus:r,predicate:o,queryKey:i,stale:a}=e;if(i){if(n){if(t.queryHash!==$s(i,t.options))return!1}else if(!nt(t.queryKey,i))return!1}if(s!=="all"){const l=t.isActive();if(s==="active"&&!l||s==="inactive"&&l)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||r&&r!==t.state.fetchStatus||o&&!o(t))}function ln(e,t){const{exact:s,status:n,predicate:r,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(s){if(Ae(t.options.mutationKey)!==Ae(o))return!1}else if(!nt(t.options.mutationKey,o))return!1}return!(n&&t.state.status!==n||r&&!r(t))}function $s(e,t){return(t?.queryKeyHashFn||Ae)(e)}function Ae(e){return JSON.stringify(e,(t,s)=>gs(s)?Object.keys(s).sort().reduce((n,r)=>(n[r]=s[r],n),{}):s)}function nt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>nt(e[s],t[s])):!1}var No=Object.prototype.hasOwnProperty;function vr(e,t,s=0){if(e===t)return e;if(s>500)return t;const n=un(e)&&un(t);if(!n&&!(gs(e)&&gs(t)))return t;const r=(n?e:Object.keys(e)).length,o=n?t:Object.keys(t),i=o.length,a=n?new Array(i):{};let l=0;for(let u=0;u<i;u++){const c=n?u:o[u],d=e[c],h=t[c];if(d===h){a[c]=d,(n?u<r:No.call(e,c))&&l++;continue}if(d===null||h===null||typeof d!="object"||typeof h!="object"){a[c]=h;continue}const f=vr(d,h,s+1);a[c]=f,f===d&&l++}return r===i&&l===r?e:a}function xt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function un(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function gs(e){if(!cn(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!cn(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function cn(e){return Object.prototype.toString.call(e)==="[object Object]"}function Do(e){return new Promise(t=>{Ee.setTimeout(t,e)})}function ps(e,t,s){return typeof s.structuralSharing=="function"?s.structuralSharing(e,t):s.structuralSharing!==!1?vr(e,t):t}function ko(e,t,s=0){const n=[...e,t];return s&&n.length>s?n.slice(1):n}function $o(e,t,s=0){const n=[t,...e];return s&&n.length>s?n.slice(0,-1):n}var Bs=Symbol();function Sr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Bs?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Us(e,t){return typeof e=="function"?e(...t):!!e}function Bo(e,t,s){let n=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),n||(n=!0,r.aborted?s():r.addEventListener("abort",s,{once:!0})),r)}),e}var rt=(()=>{let e=()=>Lo;return{isServer(){return e()},setIsServer(t){e=t}}})();function ms(){let e,t;const s=new Promise((r,o)=>{e=r,t=o});s.status="pending",s.catch(()=>{});function n(r){Object.assign(s,r),delete s.resolve,delete s.reject}return s.resolve=r=>{n({status:"fulfilled",value:r}),e(r)},s.reject=r=>{n({status:"rejected",reason:r}),t(r)},s}function gc(e){return e.state.status==="success"}var Uo=Oo;function Vo(){let e=[],t=0,s=a=>{a()},n=a=>{a()},r=Uo;const o=a=>{t?e.push(a):r(()=>{s(a)})},i=()=>{const a=e;e=[],a.length&&r(()=>{n(()=>{a.forEach(l=>{s(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||i()}return l},batchCalls:a=>(...l)=>{o(()=>{a(...l)})},schedule:o,setNotifyFunction:a=>{s=a},setBatchNotifyFunction:a=>{n=a},setScheduler:a=>{r=a}}}var U=Vo(),Go=class extends ze{#t=!0;#e;#s;constructor(){super(),this.#s=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#s=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#t}},Pt=new Go;function Ho(e){return Math.min(1e3*2**e,3e4)}function yr(e){return(e??"online")==="online"?Pt.isOnline():!0}var vs=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Cr(e){let t=!1,s=0,n;const r=ms(),o=()=>r.status!=="pending",i=p=>{if(!o()){const v=new vs(p);h(v),e.onCancel?.(v)}},a=()=>{t=!0},l=()=>{t=!1},u=()=>ks.isFocused()&&(e.networkMode==="always"||Pt.isOnline())&&e.canRun(),c=()=>yr(e.networkMode)&&e.canRun(),d=p=>{o()||(n?.(),r.resolve(p))},h=p=>{o()||(n?.(),r.reject(p))},f=()=>new Promise(p=>{n=v=>{(o()||u())&&p(v)},e.onPause?.()}).then(()=>{n=void 0,o()||e.onContinue?.()}),g=()=>{if(o())return;let p;const v=s===0?e.initialPromise:void 0;try{p=v??e.fn()}catch(m){p=Promise.reject(m)}Promise.resolve(p).then(d).catch(m=>{if(o())return;const S=e.retry??(rt.isServer()?0:3),C=e.retryDelay??Ho,I=typeof C=="function"?C(s,m):C,y=S===!0||typeof S=="number"&&s<S||typeof S=="function"&&S(s,m);if(t||!y){h(m);return}s++,e.onFail?.(s,m),Do(I).then(()=>u()?void 0:f()).then(()=>{t?h(m):g()})})};return{promise:r,status:()=>r.status,cancel:i,continue:()=>(n?.(),r),cancelRetry:a,continueRetry:l,canStart:c,start:()=>(c()?g():f().then(g),r)}}var Rr=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),fs(this.gcTime)&&(this.#t=Ee.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(rt.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#t!==void 0&&(Ee.clearTimeout(this.#t),this.#t=void 0)}};function jo(e){return{onFetch:(t,s)=>{const n=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],i=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let c=!1;const d=g=>{Bo(g,()=>t.signal,()=>c=!0)},h=Sr(t.options,t.fetchOptions),f=async(g,p,v)=>{if(c)return Promise.reject(t.signal.reason);if(p==null&&g.pages.length)return Promise.resolve(g);const S=(()=>{const R={client:t.client,queryKey:t.queryKey,pageParam:p,direction:v?"backward":"forward",meta:t.options.meta};return d(R),R})(),C=await h(S),{maxPages:I}=t.options,y=v?$o:ko;return{pages:y(g.pages,C,I),pageParams:y(g.pageParams,p,I)}};if(r&&o.length){const g=r==="backward",p=g?zo:dn,v={pages:o,pageParams:i};a=await f(v,p(n,v),g)}else{const g=e??o.length;do{const p=l===0?i[0]??n.initialPageParam:dn(n,a);if(l>0&&p==null)break;a=await f(a,p),l++}while(l<g)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=u}}}function dn(e,{pages:t,pageParams:s}){const n=t.length-1;return t.length>0?e.getNextPageParam(t[n],t,s[n],s):void 0}function zo(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var qo=class extends Rr{#t;#e;#s;#n;#o;#r;#i;#a;constructor(e){super(),this.#a=!1,this.#i=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#o=e.client,this.#n=this.#o.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=fn(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#t}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#i,...e},e?._type&&(this.#t=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=fn(this.options);t.data!==void 0&&(this.setState(hn(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const s=ps(this.state.data,e,this.options);return this.#l({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(K).catch(K):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#e}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>ee(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Bs||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>ye(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!mr(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#a||this.#f()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#f(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const a=this.observers.find(l=>l.options.queryFn);a&&this.setOptions(a.options)}const s=new AbortController,n=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(this.#a=!0,s.signal)})},r=()=>{const a=Sr(this.options,t),u=(()=>{const c={client:this.#o,queryKey:this.queryKey,meta:this.meta};return n(c),c})();return this.#a=!1,this.options.persister?this.options.persister(a,u,this):a(u)},i=(()=>{const a={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#o,state:this.state,fetchFn:r};return n(a),a})();(this.#t==="infinite"?jo(this.options.pages):this.options.behavior)?.onFetch(i,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#l({type:"fetch",meta:i.fetchOptions?.meta}),this.#r=Cr({initialPromise:t?.initialPromise,fn:i.fetchFn,onCancel:a=>{a instanceof vs&&a.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},onFail:(a,l)=>{this.#l({type:"failed",failureCount:a,error:l})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0});try{const a=await this.#r.start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),this.#n.config.onSuccess?.(a,this),this.#n.config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof vs){if(a.silent)return this.#r.promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw this.#l({type:"error",error:a}),this.#n.config.onError?.(a,this),this.#n.config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}#l(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Ir(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...hn(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=e.manual?n:void 0,n;case"error":const r=e.error;return{...s,error:r,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),U.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Ir(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:yr(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function hn(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function fn(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,n=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var Wo=class extends ze{constructor(e,t){super(),this.options=t,this.#t=e,this.#a=null,this.#i=ms(),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#s=void 0;#n=void 0;#o;#r;#i;#a;#f;#l;#c;#d;#u;#h;#g=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),gn(this.#e,this.options)?this.#p():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ss(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ss(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#C(),this.#R(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,s=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ee(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#I(),this.#e.setOptions(this.options),t._defaulted&&!xt(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const n=this.hasListeners();n&&pn(this.#e,s,this.options,t)&&this.#p(),this.updateResult(),n&&(this.#e!==s||ee(this.options.enabled,this.#e)!==ee(t.enabled,this.#e)||ye(this.options.staleTime,this.#e)!==ye(t.staleTime,this.#e))&&this.#m();const r=this.#v();n&&(this.#e!==s||ee(this.options.enabled,this.#e)!==ee(t.enabled,this.#e)||r!==this.#h)&&this.#S(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),s=this.createResult(t,e);return Qo(this,s)&&(this.#n=s,this.#r=this.options,this.#o=this.#e.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,n)=>(this.trackProp(n),t?.(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#i.status==="pending"&&this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){this.#g.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),s=this.#t.getQueryCache().build(this.#t,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#p({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#p(e){this.#I();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(K)),t}#m(){this.#C();const e=ye(this.options.staleTime,this.#e);if(rt.isServer()||this.#n.isStale||!fs(e))return;const t=mr(this.#n.dataUpdatedAt,e)+1;this.#d=Ee.setTimeout(()=>{this.#n.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#S(e){this.#R(),this.#h=e,!(rt.isServer()||ee(this.options.enabled,this.#e)===!1||!fs(this.#h)||this.#h===0)&&(this.#u=Ee.setInterval(()=>{(this.options.refetchIntervalInBackground||ks.isFocused())&&this.#p()},this.#h))}#y(){this.#m(),this.#S(this.#v())}#C(){this.#d!==void 0&&(Ee.clearTimeout(this.#d),this.#d=void 0)}#R(){this.#u!==void 0&&(Ee.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const s=this.#e,n=this.options,r=this.#n,o=this.#o,i=this.#r,a=e!==s?e.state:this.#s,{state:l}=e;let u={...l},c=!1,d;if(t._optimisticResults){const R=this.hasListeners(),b=!R&&gn(e,t),_=R&&pn(e,s,t,n);(b||_)&&(u={...u,...Ir(l.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:h,errorUpdatedAt:f,status:g}=u;d=u.data;let p=!1;if(t.placeholderData!==void 0&&d===void 0&&g==="pending"){let R;r?.isPlaceholderData&&t.placeholderData===i?.placeholderData?(R=r.data,p=!0):R=typeof t.placeholderData=="function"?t.placeholderData(this.#c?.state.data,this.#c):t.placeholderData,R!==void 0&&(g="success",d=ps(r?.data,R,t),c=!0)}if(t.select&&d!==void 0&&!p)if(r&&d===o?.data&&t.select===this.#f)d=this.#l;else try{this.#f=t.select,d=t.select(d),d=ps(r?.data,d,t),this.#l=d,this.#a=null}catch(R){this.#a=R}this.#a&&(h=this.#a,d=this.#l,f=Date.now(),g="error");const v=u.fetchStatus==="fetching",m=g==="pending",S=g==="error",C=m&&v,I=d!==void 0,y={status:g,fetchStatus:u.fetchStatus,isPending:m,isSuccess:g==="success",isError:S,isInitialLoading:C,isLoading:C,data:d,dataUpdatedAt:u.dataUpdatedAt,error:h,errorUpdatedAt:f,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>a.dataUpdateCount||u.errorUpdateCount>a.errorUpdateCount,isFetching:v,isRefetching:v&&!m,isLoadingError:S&&!I,isPaused:u.fetchStatus==="paused",isPlaceholderData:c,isRefetchError:S&&I,isStale:Vs(e,t),refetch:this.refetch,promise:this.#i,isEnabled:ee(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const R=y.data!==void 0,b=y.status==="error"&&!R,_=E=>{b?E.reject(y.error):R&&E.resolve(y.data)},M=()=>{const E=this.#i=y.promise=ms();_(E)},P=this.#i;switch(P.status){case"pending":e.queryHash===s.queryHash&&_(P);break;case"fulfilled":(b||y.data!==P.value)&&M();break;case"rejected":(!b||y.error!==P.reason)&&M();break}}return y}updateResult(){const e=this.#n,t=this.createResult(this.#e,this.options);if(this.#o=this.#e.state,this.#r=this.options,this.#o.data!==void 0&&(this.#c=this.#e),xt(t,e))return;this.#n=t;const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,r=typeof n=="function"?n():n;if(r==="all"||!r&&!this.#g.size)return!0;const o=new Set(r??this.#g);return this.options.throwOnError&&o.add("error"),Object.keys(this.#n).some(i=>{const a=i;return this.#n[a]!==e[a]&&o.has(a)})};this.#w({listeners:s()})}#I(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#s=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#w(e){U.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Ko(e,t){return ee(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&ee(t.retryOnMount,e)===!1)}function gn(e,t){return Ko(e,t)||e.state.data!==void 0&&Ss(e,t,t.refetchOnMount)}function Ss(e,t,s){if(ee(t.enabled,e)!==!1&&ye(t.staleTime,e)!=="static"){const n=typeof s=="function"?s(e):s;return n==="always"||n!==!1&&Vs(e,t)}return!1}function pn(e,t,s,n){return(e!==t||ee(n.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&Vs(e,s)}function Vs(e,t){return ee(t.enabled,e)!==!1&&e.isStaleByTime(ye(t.staleTime,e))}function Qo(e,t){return!xt(e.getCurrentResult(),t)}var Jo=class extends Rr{#t;#e;#s;#n;constructor(e){super(),this.#t=e.client,this.mutationId=e.mutationId,this.#s=e.mutationCache,this.#e=[],this.state=e.state||wr(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#e.includes(e)||(this.#e.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#o({type:"continue"})},s={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#n=Cr({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(o,i)=>{this.#o({type:"failed",failureCount:o,error:i})},onPause:()=>{this.#o({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#s.canRun(this)});const n=this.state.status==="pending",r=!this.#n.canStart();try{if(n)t();else{this.#o({type:"pending",variables:e,isPaused:r}),this.#s.config.onMutate&&await this.#s.config.onMutate(e,this,s);const i=await this.options.onMutate?.(e,s);i!==this.state.context&&this.#o({type:"pending",context:i,variables:e,isPaused:r})}const o=await this.#n.start();return await this.#s.config.onSuccess?.(o,e,this.state.context,this,s),await this.options.onSuccess?.(o,e,this.state.context,s),await this.#s.config.onSettled?.(o,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(o,null,e,this.state.context,s),this.#o({type:"success",data:o}),o}catch(o){try{await this.#s.config.onError?.(o,e,this.state.context,this,s)}catch(i){Promise.reject(i)}try{await this.options.onError?.(o,e,this.state.context,s)}catch(i){Promise.reject(i)}try{await this.#s.config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,s)}catch(i){Promise.reject(i)}try{await this.options.onSettled?.(void 0,o,e,this.state.context,s)}catch(i){Promise.reject(i)}throw this.#o({type:"error",error:o}),o}finally{this.#s.runNext(this)}}#o(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),U.batch(()=>{this.#e.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function wr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Xo=class extends ze{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#s=0}#t;#e;#s;build(e,t,s){const n=new Jo({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(n),n}add(e){this.#t.add(e);const t=ht(e);if(typeof t=="string"){const s=this.#e.get(t);s?s.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=ht(e);if(typeof t=="string"){const s=this.#e.get(t);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=ht(e);if(typeof t=="string"){const s=this.#e.get(t)?.find(n=>n.state.status==="pending");return!s||s===e}else return!0}runNext(e){const t=ht(e);return typeof t=="string"?this.#e.get(t)?.find(s=>s!==e&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){U.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(s=>ln(t,s))}findAll(e={}){return this.getAll().filter(t=>ln(e,t))}notify(e){U.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return U.batch(()=>Promise.all(e.map(t=>t.continue().catch(K))))}};function ht(e){return e.options.scope?.id}var Yo=class extends ze{#t;#e=void 0;#s;#n;constructor(e,t){super(),this.#t=e,this.setOptions(t),this.bindMethods(),this.#o()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#t.defaultMutationOptions(e),xt(this.options,t)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Ae(t.mutationKey)!==Ae(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#o(),this.#r(e)}getCurrentResult(){return this.#e}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#o(),this.#r()}mutate(e,t){return this.#n=t,this.#s?.removeObserver(this),this.#s=this.#t.getMutationCache().build(this.#t,this.options),this.#s.addObserver(this),this.#s.execute(e)}#o(){const e=this.#s?.state??wr();this.#e={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#r(e){U.batch(()=>{if(this.#n&&this.hasListeners()){const t=this.#e.variables,s=this.#e.context,n={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,t,s,n)}catch(r){Promise.reject(r)}try{this.#n.onSettled?.(e.data,null,t,s,n)}catch(r){Promise.reject(r)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,t,s,n)}catch(r){Promise.reject(r)}try{this.#n.onSettled?.(void 0,e.error,t,s,n)}catch(r){Promise.reject(r)}}}this.listeners.forEach(t=>{t(this.#e)})})}},Zo=class extends ze{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,s){const n=t.queryKey,r=t.queryHash??$s(n,t);let o=this.get(r);return o||(o=new qo({client:e,queryKey:n,queryHash:r,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(o)),o}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){U.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(s=>an(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>an(e,s)):t}notify(e){U.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){U.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){U.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},pc=class{#t;#e;#s;#n;#o;#r;#i;#a;constructor(e={}){this.#t=e.queryCache||new Zo,this.#e=e.mutationCache||new Xo,this.#s=e.defaultOptions||{},this.#n=new Map,this.#o=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#i=ks.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#a=Pt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#i?.(),this.#i=void 0,this.#a?.(),this.#a=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),s=this.#t.build(this,t),n=s.state.data;return n===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(ye(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:s})=>[t,s.data])}setQueryData(e,t,s){const n=this.defaultQueryOptions({queryKey:e}),r=this.#t.get(n.queryHash)?.state.data,o=Fo(t,r);if(o!==void 0)return this.#t.build(this,n).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return U.batch(()=>this.#t.findAll(e).map(({queryKey:n})=>[n,this.setQueryData(n,t,s)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;U.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#t;return U.batch(()=>(s.findAll(e).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},n=U.batch(()=>this.#t.findAll(e).map(r=>r.cancel(s)));return Promise.all(n).then(K).catch(K)}invalidateQueries(e,t={}){return U.batch(()=>(this.#t.findAll(e).forEach(s=>{s.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},n=U.batch(()=>this.#t.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let o=r.fetch(void 0,s);return s.throwOnError||(o=o.catch(K)),r.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(n).then(K)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#t.build(this,t);return s.isStaleByTime(ye(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(K).catch(K)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(K).catch(K)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Pt.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#s}setDefaultOptions(e){this.#s=e}setQueryDefaults(e,t){this.#n.set(Ae(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(n=>{nt(e,n.queryKey)&&Object.assign(s,n.defaultOptions)}),s}setMutationDefaults(e,t){this.#o.set(Ae(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],s={};return t.forEach(n=>{nt(e,n.mutationKey)&&Object.assign(s,n.defaultOptions)}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#s.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=$s(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Bs&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#s.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},w=pr(Ds(),1),x=xo(),br=w.createContext(void 0),_r=e=>{const t=w.useContext(br);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},mc=({client:e,children:t})=>(w.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,x.jsx)(br.Provider,{value:e,children:t})),Mr=w.createContext(!1),ei=()=>w.useContext(Mr),vc=Mr.Provider;function ti(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var si=w.createContext(ti()),ni=()=>w.useContext(si),ri=(e,t,s)=>{const n=s?.state.error&&typeof e.throwOnError=="function"?Us(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||n)&&(t.isReset()||(e.retryOnMount=!1))},oi=e=>{w.useEffect(()=>{e.clearReset()},[e])},ii=({result:e,errorResetBoundary:t,throwOnError:s,query:n,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&n&&(r&&e.data===void 0||Us(s,[e.error,n])),ai=e=>{if(e.suspense){const s=r=>r==="static"?r:Math.max(r??1e3,1e3),n=e.staleTime;e.staleTime=typeof n=="function"?(...r)=>s(n(...r)):s(n),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},li=(e,t)=>e.isLoading&&e.isFetching&&!t,ui=(e,t)=>e?.suspense&&t.isPending,mn=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function ci(e,t,s){const n=ei(),r=ni(),o=_r(s),i=o.defaultQueryOptions(e);o.getDefaultOptions().queries?._experimental_beforeQuery?.(i);const a=o.getQueryCache().get(i.queryHash);i._optimisticResults=n?"isRestoring":"optimistic",ai(i),ri(i,r,a),oi(r);const l=!o.getQueryCache().get(i.queryHash),[u]=w.useState(()=>new t(o,i)),c=u.getOptimisticResult(i),d=!n&&e.subscribed!==!1;if(w.useSyncExternalStore(w.useCallback(h=>{const f=d?u.subscribe(U.batchCalls(h)):K;return u.updateResult(),f},[u,d]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),w.useEffect(()=>{u.setOptions(i)},[i,u]),ui(i,c))throw mn(i,u,r);if(ii({result:c,errorResetBoundary:r,throwOnError:i.throwOnError,query:a,suspense:i.suspense}))throw c.error;return o.getDefaultOptions().queries?._experimental_afterQuery?.(i,c),i.experimental_prefetchInRender&&!rt.isServer()&&li(c,n)&&(l?mn(i,u,r):a?.promise)?.catch(K).finally(()=>{u.updateResult()}),i.notifyOnChangeProps?c:u.trackResult(c)}function Sc(e,t){return ci(e,Wo,t)}function yc(e,t){const s=_r(t),[n]=w.useState(()=>new Yo(s,e));w.useEffect(()=>{n.setOptions(e)},[n,e]);const r=w.useSyncExternalStore(w.useCallback(i=>n.subscribe(U.batchCalls(i)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),o=w.useCallback((i,a)=>{n.mutate(i,a).catch(K)},[n]);if(r.error&&Us(n.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:o,mutateAsync:r.mutate}}var vn=w.use,et=typeof window<"u"?w.useLayoutEffect:w.useEffect;function Wt(e){const t=w.useRef({value:e,prev:null}),s=t.current.value;return e!==s&&(t.current={value:e,prev:s}),t.current.prev}function di(e,t,s={},n={}){w.useEffect(()=>{if(!e.current||n.disabled||typeof IntersectionObserver!="function")return;const r=new IntersectionObserver(([o])=>{t(o)},s);return r.observe(e.current),()=>{r.disconnect()}},[t,s,n.disabled,e])}function hi(e){const t=w.useRef(null);return w.useImperativeHandle(e,()=>t.current,[]),t}function ot(e){return e[e.length-1]}function fi(e){return typeof e=="function"}function ue(e,t){return fi(e)?e(t):e}var Er=Object.prototype.hasOwnProperty,Sn=Object.prototype.propertyIsEnumerable;function Tt(e){for(const t in e)if(Er.call(e,t))return!0;return!1}var gi=()=>Object.create(null),_e=(e,t)=>xe(e,t,gi);function xe(e,t,s=()=>({}),n=0){if(e===t)return e;if(n>500)return t;const r=t,o=Rn(e)&&Rn(r);if(!o&&!(At(e)&&At(r)))return r;const i=o?e:yn(e);if(!i)return r;const a=o?r:yn(r);if(!a)return r;const l=i.length,u=a.length,c=o?new Array(u):s();let d=0;for(let h=0;h<u;h++){const f=o?h:a[h],g=e[f],p=r[f];if(g===p){c[f]=g,(o?h<l:Er.call(e,f))&&d++;continue}if(g===null||p===null||typeof g!="object"||typeof p!="object"){c[f]=p;continue}const v=xe(g,p,s,n+1);c[f]=v,v===g&&d++}return l===u&&d===l?e:c}function yn(e){const t=Object.getOwnPropertyNames(e);for(const r of t)if(!Sn.call(e,r))return!1;const s=Object.getOwnPropertySymbols(e);if(s.length===0)return t;const n=t;for(const r of s){if(!Sn.call(e,r))return!1;n.push(r)}return n}function At(e){if(!Cn(e))return!1;const t=e.constructor;if(typeof t>"u")return!0;const s=t.prototype;return!(!Cn(s)||!s.hasOwnProperty("isPrototypeOf"))}function Cn(e){return Object.prototype.toString.call(e)==="[object Object]"}function Rn(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ce(e,t,s){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(!Ce(e[n],t[n],s))return!1;return!0}if(At(e)&&At(t)){const n=s?.ignoreUndefined??!0;if(s?.partial){for(const i in t)if((!n||t[i]!==void 0)&&!Ce(e[i],t[i],s))return!1;return!0}let r=0;if(!n)r=Object.keys(e).length;else for(const i in e)e[i]!==void 0&&r++;let o=0;for(const i in t)if((!n||t[i]!==void 0)&&(o++,o>r||!Ce(e[i],t[i],s)))return!1;return r===o}return!1}function He(e){let t,s;const n=new Promise((r,o)=>{t=r,s=o});return n.status="pending",n.resolve=r=>{n.status="resolved",n.value=r,t(r),e?.(r)},n.reject=r=>{n.status="rejected",s(r)},n}function pi(e){return typeof e?.message!="string"?!1:e.message.startsWith("Failed to fetch dynamically imported module")||e.message.startsWith("error loading dynamically imported module")||e.message.startsWith("Importing a module script failed")}function it(e){return!!(e&&typeof e=="object"&&typeof e.then=="function")}var mi=/[\x00-\x1f\x7f"<>`{}]/g;function vi(e){return e.replace(mi,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function In(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,s=>{try{return decodeURI(s)}catch{return s}})}return vi(t)}var Si=["http:","https:","mailto:","tel:"];function Me(e,t){if(!e)return!1;try{const s=new URL(e);return!t.has(s.protocol)}catch{return!1}}function Je(e){if(!e)return{path:e,handledProtocolRelativeURL:!1};if(!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith("//"))return{path:e,handledProtocolRelativeURL:!1};const t=/%25|%5C/gi;let s=0,n="",r;for(;(r=t.exec(e))!==null;)n+=In(e.slice(s,r.index))+r[0],s=t.lastIndex;n=n+In(s?e.slice(s):e);let o=!1;return n.startsWith("//")&&(o=!0,n="/"+n.replace(/^\/+/,"")),{path:n,handledProtocolRelativeURL:o}}function yi(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function Ci(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;return!0}function de(){throw new Error("Invariant failed")}function at(e){const t=new Map;let s,n;const r=o=>{o.next&&(o.prev?(o.prev.next=o.next,o.next.prev=o.prev,o.next=void 0,n&&(n.next=o,o.prev=n)):(o.next.prev=void 0,s=o.next,o.next=void 0,n&&(o.prev=n,n.next=o)),n=o)};return{get(o){const i=t.get(o);if(i)return r(i),i.value},set(o,i){if(t.size>=e&&s){const l=s;t.delete(l.key),l.next&&(s=l.next,l.next.prev=void 0),l===n&&(n=void 0)}const a=t.get(o);if(a)a.value=i,r(a);else{const l={key:o,value:i,prev:n};n&&(n.next=l),n=l,s||(s=l),t.set(o,l)}},clear(){t.clear(),s=void 0,n=void 0}}}var pe=4,xr=5;function Ri(e){const t=e.indexOf("{");if(t===-1)return null;const s=e.indexOf("}",t);return s===-1||t+1>=e.length?null:[t,s]}function Pr(e,t,s=new Uint16Array(6)){const n=e.indexOf("/",t),r=n===-1?e.length:n,o=e.substring(t,r);if(!o||!o.includes("$"))return s[0]=0,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s;if(o==="$"){const a=e.length;return s[0]=2,s[1]=t,s[2]=t,s[3]=a,s[4]=a,s[5]=a,s}if(o.charCodeAt(0)===36)return s[0]=1,s[1]=t,s[2]=t+1,s[3]=r,s[4]=r,s[5]=r,s;const i=Ri(o);if(i){const[a,l]=i,u=o.charCodeAt(a+1);if(u===45){if(a+2<o.length&&o.charCodeAt(a+2)===36){const c=a+3,d=l;if(c<d)return s[0]=3,s[1]=t+a,s[2]=t+c,s[3]=t+d,s[4]=t+l+1,s[5]=r,s}}else if(u===36){const c=a+1,d=a+2;return d===l?(s[0]=2,s[1]=t+a,s[2]=t+c,s[3]=t+d,s[4]=t+l+1,s[5]=e.length,s):(s[0]=1,s[1]=t+a,s[2]=t+d,s[3]=t+l,s[4]=t+l+1,s[5]=r,s)}}return s[0]=0,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s}function Dt(e,t,s,n,r,o,i){i?.(s);let a=n;{const l=s.fullPath??s.from,u=l.length,c=s.options?.caseSensitive??e,d=s.options?.params?.parse??s.options?.parseParams;for(;a<u;){const f=Pr(l,a,t);let g;const p=a,v=f[5];switch(a=v+1,o++,f[0]){case 0:{const m=l.substring(f[2],f[3]);if(c){const S=r.static?.get(m);if(S)g=S;else{r.static??=new Map;const C=Pe(s.fullPath??s.from);C.parent=r,C.depth=o,g=C,r.static.set(m,C)}}else{const S=m.toLowerCase(),C=r.staticInsensitive?.get(S);if(C)g=C;else{r.staticInsensitive??=new Map;const I=Pe(s.fullPath??s.from);I.parent=r,I.depth=o,g=I,r.staticInsensitive.set(S,I)}}break}case 1:{const m=l.substring(p,f[1]),S=l.substring(f[4],v),C=c&&!!(m||S),I=m?C?m:m.toLowerCase():void 0,y=S?C?S:S.toLowerCase():void 0,R=!d&&r.dynamic?.find(b=>!b.parse&&b.caseSensitive===C&&b.prefix===I&&b.suffix===y);if(R)g=R;else{const b=Qt(1,s.fullPath??s.from,C,I,y);g=b,b.depth=o,b.parent=r,r.dynamic??=[],r.dynamic.push(b)}break}case 3:{const m=l.substring(p,f[1]),S=l.substring(f[4],v),C=c&&!!(m||S),I=m?C?m:m.toLowerCase():void 0,y=S?C?S:S.toLowerCase():void 0,R=!d&&r.optional?.find(b=>!b.parse&&b.caseSensitive===C&&b.prefix===I&&b.suffix===y);if(R)g=R;else{const b=Qt(3,s.fullPath??s.from,C,I,y);g=b,b.parent=r,b.depth=o,r.optional??=[],r.optional.push(b)}break}case 2:{const m=l.substring(p,f[1]),S=l.substring(f[4],v),C=c&&!!(m||S),I=m?C?m:m.toLowerCase():void 0,y=S?C?S:S.toLowerCase():void 0,R=Qt(2,s.fullPath??s.from,C,I,y);g=R,R.parent=r,R.depth=o,r.wildcard??=[],r.wildcard.push(R)}}r=g}if(d&&s.children&&!s.isRoot&&s.id&&s.id.charCodeAt(s.id.lastIndexOf("/")+1)===95){const f=Pe(s.fullPath??s.from);f.kind=xr,f.parent=r,o++,f.depth=o,r.pathless??=[],r.pathless.push(f),r=f}const h=(s.path||!s.children)&&!s.isRoot;if(h&&l.endsWith("/")){const f=Pe(s.fullPath??s.from);f.kind=pe,f.parent=r,o++,f.depth=o,r.index=f,r=f}r.parse=d??null,r.priority=s.options?.params?.priority??0,h&&!r.route&&(r.route=s,r.fullPath=s.fullPath??s.from)}if(s.children)for(const l of s.children)Dt(e,t,l,a,r,o,i)}function Kt(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function ge(e){if(e.pathless)for(const t of e.pathless)ge(t);if(e.static)for(const t of e.static.values())ge(t);if(e.staticInsensitive)for(const t of e.staticInsensitive.values())ge(t);if(e.dynamic?.length){e.dynamic.sort(Kt);for(const t of e.dynamic)ge(t)}if(e.optional?.length){e.optional.sort(Kt);for(const t of e.optional)ge(t)}if(e.wildcard?.length){e.wildcard.sort(Kt);for(const t of e.wildcard)ge(t)}}function Pe(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function Qt(e,t,s,n,r){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:s,prefix:n,suffix:r}}function Ii(e,t){const s=Pe("/"),n=new Uint16Array(6);for(const r of e)Dt(!1,n,r,1,s,0);ge(s),t.masksTree=s,t.flatCache=at(1e3)}function wi(e,t){e||="/";const s=t.flatCache.get(e);if(s)return s;const n=Gs(e,t.masksTree);return t.flatCache.set(e,n),n}function bi(e,t,s,n,r){e||="/",n||="/";const o=t?`case\0${e}`:e;let i=r.singleCache.get(o);return i||(i=Pe("/"),Dt(t,new Uint16Array(6),{from:e},1,i,0),r.singleCache.set(o,i)),Gs(n,i,s)}function _i(e,t,s=!1){const n=s?e:`nofuzz\0${e}`,r=t.matchCache.get(n);if(r!==void 0)return r;e||="/";let o;try{o=Gs(e,t.segmentTree,s)}catch(i){if(i instanceof URIError)o=null;else throw i}return o&&(o.branch=Ar(o.route)),t.matchCache.set(n,o),o}function Mi(e){return e==="/"?e:e.replace(/\/{1,}$/,"")}function Ei(e,t=!1,s){const n=Pe(e.fullPath),r=new Uint16Array(6),o={},i={};let a=0;return Dt(t,r,e,1,n,0,l=>{if(s?.(l,a),l.id in o&&de(),o[l.id]=l,a!==0&&l.path){const u=Mi(l.fullPath);(!i[u]||l.fullPath.endsWith("/"))&&(i[u]=l)}a++}),ge(n),{processedTree:{segmentTree:n,singleCache:at(1e3),matchCache:at(1e3),flatCache:null,masksTree:null},routesById:o,routesByPath:i}}function Gs(e,t,s=!1){const n=e.split("/"),r=Pi(e,n,t,s);if(!r)return null;const[o]=Tr(e,n,r);return{route:r.node.route,rawParams:o}}function Tr(e,t,s){const n=xi(s.node);let r=null;const o=Object.create(null);let i=s.extract?.part??0,a=s.extract?.node??0,l=s.extract?.path??0,u=s.extract?.segment??0;for(;a<n.length;i++,a++,l++,u++){const c=n[a];if(c.kind===pe)break;if(c.kind===xr){u--,i--,l--;continue}const d=t[i],h=l;if(d&&(l+=d.length),c.kind===1){r??=s.node.fullPath.split("/");const f=r[u],g=c.prefix?.length??0;if(f.charCodeAt(g)===123){const p=c.suffix?.length??0,v=f.substring(g+2,f.length-p-1),m=d.substring(g,d.length-p);o[v]=decodeURIComponent(m)}else{const p=f.substring(1);o[p]=decodeURIComponent(d)}}else if(c.kind===3){if(s.skipped&1<<a){i--,l=h-1;continue}r??=s.node.fullPath.split("/");const f=r[u],g=c.prefix?.length??0,p=c.suffix?.length??0,v=f.substring(g+3,f.length-p-1),m=c.suffix||c.prefix?d.substring(g,d.length-p):d;m&&(o[v]=decodeURIComponent(m))}else if(c.kind===2){const f=c,g=e.substring(h+(f.prefix?.length??0),e.length-(f.suffix?.length??0)),p=decodeURIComponent(g);o["*"]=p,o._splat=p;break}}return s.rawParams&&Object.assign(o,s.rawParams),[o,{part:i,node:a,path:l,segment:u}]}function Ar(e){const t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function xi(e){const t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function Pi(e,t,s,n){if(e==="/"&&s.index)return{node:s.index,skipped:0};const r=!ot(t),o=r&&e!=="/",i=t.length-(r?1:0),a=[{node:s,index:1,skipped:0,depth:1,statics:0,dynamics:0,optionals:0}];let l=null,u=null;for(;a.length;){const c=a.pop(),{node:d,index:h,skipped:f,depth:g,statics:p,dynamics:v,optionals:m}=c;let{extract:S,rawParams:C}=c;if(d.kind===2&&d.route&&!gt(u,c))continue;if(d.parse){if(!wn(e,t,c))continue;C=c.rawParams,S=c.extract}n&&d.route&&d.kind!==pe&>(l,c)&&(l=c);const I=h===i;if(I&&(d.route&&(!o||d.kind===pe||d.kind===2)&>(u,c)&&(u=c),!d.optional&&!d.wildcard&&!d.index&&!d.pathless))continue;const y=I?void 0:t[h];let R;if(I&&d.index){const b={node:d.index,index:h,skipped:f,depth:g+1,statics:p,dynamics:v,optionals:m,extract:S,rawParams:C};let _=!0;if(d.index.parse&&(wn(e,t,b)||(_=!1)),_){if(!v&&!m&&!f&&Ti(p,i))return b;gt(u,b)&&(u=b)}}if(d.wildcard)for(let b=d.wildcard.length-1;b>=0;b--){const _=d.wildcard[b],{prefix:M,suffix:P}=_;if(!(M&&(I||!(_.caseSensitive?y:R??=y.toLowerCase()).startsWith(M)))){if(P){if(I)continue;const E=t.slice(h).join("/").slice(-P.length);if((_.caseSensitive?E:E.toLowerCase())!==P)continue}a.push({node:_,index:i,skipped:f,depth:g+1,statics:p,dynamics:v,optionals:m,extract:S,rawParams:C})}}if(d.optional){const b=f|1<<g,_=g+1;for(let M=d.optional.length-1;M>=0;M--){const P=d.optional[M];a.push({node:P,index:h,skipped:b,depth:_,statics:p,dynamics:v,optionals:m,extract:S,rawParams:C})}if(!I)for(let M=d.optional.length-1;M>=0;M--){const P=d.optional[M],{prefix:E,suffix:O}=P;if(E||O){const se=P.caseSensitive?y:R??=y.toLowerCase();if(E&&!se.startsWith(E)||O&&!se.endsWith(O))continue}a.push({node:P,index:h+1,skipped:f,depth:_,statics:p,dynamics:v,optionals:m+ft(i,h),extract:S,rawParams:C})}}if(!I&&d.dynamic&&y)for(let b=d.dynamic.length-1;b>=0;b--){const _=d.dynamic[b],{prefix:M,suffix:P}=_;if(M||P){const E=_.caseSensitive?y:R??=y.toLowerCase();if(M&&!E.startsWith(M)||P&&!E.endsWith(P))continue}a.push({node:_,index:h+1,skipped:f,depth:g+1,statics:p,dynamics:v+ft(i,h),optionals:m,extract:S,rawParams:C})}if(!I&&d.staticInsensitive){const b=d.staticInsensitive.get(R??=y.toLowerCase());b&&a.push({node:b,index:h+1,skipped:f,depth:g+1,statics:p+ft(i,h),dynamics:v,optionals:m,extract:S,rawParams:C})}if(!I&&d.static){const b=d.static.get(y);b&&a.push({node:b,index:h+1,skipped:f,depth:g+1,statics:p+ft(i,h),dynamics:v,optionals:m,extract:S,rawParams:C})}if(d.pathless){const b=g+1;for(let _=d.pathless.length-1;_>=0;_--){const M=d.pathless[_];a.push({node:M,index:h,skipped:f,depth:b,statics:p,dynamics:v,optionals:m,extract:S,rawParams:C})}}}if(u)return u;if(n&&l){let c=l.index;for(let h=0;h<l.index;h++)c+=t[h].length;const d=c===e.length?"/":e.slice(c);return l.rawParams??=Object.create(null),l.rawParams["**"]=decodeURIComponent(d),l}return null}function ft(e,t){return 2**(e-t-1)}function Ti(e,t){return e===2**(t-1)-1}function wn(e,t,s){let n,r;try{[n,r]=Tr(e,t,s)}catch{return null}if(s.rawParams=n,s.extract=r,!s.node.parse)return!0;try{if(s.node.parse(n)===!1)return null}catch{}return!0}function gt(e,t){return e?t.statics>e.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===pe)>(e.node.kind===pe)||t.node.kind===pe==(e.node.kind===pe)&&t.depth>e.depth))):!0}function It(e){return Hs(e.filter(t=>t!==void 0).join("/"))}function Hs(e){return e.replace(/\/{2,}/g,"/")}function Or(e){return e==="/"?e:e.replace(/^\/{1,}/,"")}function ce(e){const t=e.length;return t>1&&e[t-1]==="/"?e.replace(/\/{1,}$/,""):e}function Lr(e){return ce(Or(e))}function Ve(e,t){return e?.endsWith("/")&&e!=="/"&&e!==`${t}/`?e.slice(0,-1):e}function bn(e,t,s){return Ve(e,s)===Ve(t,s)}function Ai({base:e,to:t,trailingSlash:s="never",cache:n}){const r=t.startsWith("/"),o=!r&&t===".";let i;if(n){i=r?t:o?e:e+"\0"+t;const u=n.get(i);if(u)return u}let a;if(o)a=e.split("/");else if(r)a=t.split("/");else{for(a=e.split("/");a.length>1&&ot(a)==="";)a.pop();const u=t.split("/");for(let c=0,d=u.length;c<d;c++){const h=u[c];h===""?c?c===d-1&&a.push(h):a=[h]:h===".."?a.pop():h==="."||a.push(h)}}a.length>1&&(ot(a)===""?s==="never"&&a.pop():s==="always"&&a.push(""));const l=Hs(a.join("/"))||"/";return i&&n&&n.set(i,l),l}function Oi(e){const t=new Map(e.map(r=>[encodeURIComponent(r),r])),s=Array.from(t.keys()).map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),n=new RegExp(s,"g");return r=>r.replace(n,o=>t.get(o)??o)}function Jt(e,t,s){const n=t[e];return typeof n!="string"?n:e==="_splat"?/^[a-zA-Z0-9\-._~!/]*$/.test(n)?n:n.split("/").map(r=>Mn(r,s)).join("/"):Mn(n,s)}function _n({path:e,params:t,decoder:s,...n}){let r=!1;const o=Object.create(null);if(!e||e==="/")return{interpolatedPath:"/",usedParams:o,isMissingParams:r};if(!e.includes("$"))return{interpolatedPath:e,usedParams:o,isMissingParams:r};const i=e.length;let a=0,l,u="";for(;a<i;){const c=a;l=Pr(e,c,l);const d=l[5];if(a=d+1,c===d)continue;const h=l[0];if(h===0){u+="/"+e.substring(c,d);continue}if(h===2){const f=t._splat;o._splat=f,o["*"]=f;const g=e.substring(c,l[1]),p=e.substring(l[4],d);if(!f){r=!0,(g||p)&&(u+="/"+g+p);continue}const v=Jt("_splat",t,s);u+="/"+g+v+p;continue}if(h===1){const f=e.substring(l[2],l[3]);!r&&!(f in t)&&(r=!0),o[f]=t[f];const g=e.substring(c,l[1]),p=e.substring(l[4],d),v=Jt(f,t,s)??"undefined";u+="/"+g+v+p;continue}if(h===3){const f=e.substring(l[2],l[3]),g=t[f];if(g==null)continue;o[f]=g;const p=e.substring(c,l[1]),v=e.substring(l[4],d),m=Jt(f,t,s)??"";u+="/"+p+m+v;continue}}return e.endsWith("/")&&(u+="/"),{usedParams:o,interpolatedPath:u||"/",isMissingParams:r}}function Mn(e,t){const s=encodeURIComponent(e);return t?.(s)??s}function q(e){return e?.isNotFound===!0}function Li(e,t=String){const s=new URLSearchParams;for(const n in e){const r=e[n];r!==void 0&&s.set(n,t(r))}return s.toString()}function Xt(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function Fi(e){const t=new URLSearchParams(e),s=Object.create(null);for(const[n,r]of t.entries()){const o=s[n];o==null?s[n]=Xt(r):Array.isArray(o)?o.push(Xt(r)):s[n]=[o,Xt(r)]}return s}var Ni=ki(JSON.parse),Di=$i(JSON.stringify,JSON.parse);function ki(e){return t=>{t[0]==="?"&&(t=t.substring(1));const s=Fi(t);for(const n in s){const r=s[n];if(typeof r=="string")try{s[n]=e(r)}catch{}}return s}}function $i(e,t){const s=typeof t=="function";function n(r){if(typeof r=="object"&&r!==null)try{return e(r)}catch{}else if(s&&typeof r=="string")try{return t(r),e(r)}catch{}return r}return r=>{const o=Li(r,n);return o?`?${o}`:""}}var wt="__root__";function Bi(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href=="string")try{new URL(e.href),e.reloadDocument=!0}catch{}const t=new Headers(e.headers);e.href&&t.get("Location")===null&&t.set("Location",e.href);const s=new Response(null,{status:e.statusCode,headers:t});if(s.options=e,e.throw)throw s;return s}function Y(e){return e instanceof Response&&!!e.options}var ys=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},Ui=e=>e.stores.matchesId.get().some(t=>e.stores.matchStores.get(t)?.get()._forcePending),kt=(e,t)=>!!(e.preload&&!e.router.stores.matchStores.has(t)),Te=(e,t,s=!0)=>{const n={...e.router.options.context??{}},r=s?t:t-1;for(let o=0;o<=r;o++){const i=e.matches[o];if(!i)continue;const a=e.router.getMatch(i.id);a&&Object.assign(n,a.__routeContext,a.__beforeLoadContext)}return n},En=(e,t)=>{if(!e.matches.length)return;const s=t.routeId,n=e.matches.findIndex(i=>i.routeId===e.router.routeTree.id),r=n>=0?n:0;let o=s?e.matches.findIndex(i=>i.routeId===s):e.firstBadMatchIndex??e.matches.length-1;o<0&&(o=r);for(let i=o;i>=0;i--){const a=e.matches[i];if(e.router.looseRoutesById[a.routeId].options.notFoundComponent)return i}return s?o:r},me=(e,t,s)=>{if(!(!Y(s)&&!q(s)))throw Y(s)&&s.redirectHandled&&!s.options.reloadDocument||(t&&(t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0,t._nonReactive.error=s,e.updateMatch(t.id,n=>({...n,status:Y(s)?"redirected":q(s)?"notFound":n.status==="pending"?"success":n.status,context:Te(e,t.index),isFetching:!1,error:s})),q(s)&&!s.routeId&&(s.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()),Y(s)&&(e.rendered=!0,s.options._fromLocation=e.location,s.redirectHandled=!0,s=e.router.resolveRedirect(s))),s},Fr=(e,t)=>{const s=e.router.getMatch(t);return!!(!s||s._nonReactive.dehydrated)},xn=(e,t,s)=>{const n=Te(e,s);e.updateMatch(t,r=>({...r,context:n}))},Xe=(e,t,s)=>{const{id:n,routeId:r}=e.matches[t],o=e.router.looseRoutesById[r];if(s instanceof Promise)throw s;e.firstBadMatchIndex??=t,me(e,e.router.getMatch(n),s);try{o.options.onError?.(s)}catch(i){s=i,me(e,e.router.getMatch(n),s)}e.updateMatch(n,i=>(i._nonReactive.beforeLoadPromise?.resolve(),i._nonReactive.beforeLoadPromise=void 0,i._nonReactive.loadPromise?.resolve(),{...i,error:s,status:"error",isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!Y(s)&&!q(s)&&(e.serialError??=s)};var Nr=(e,t,s,n)=>{if(n._nonReactive.pendingTimeout!==void 0)return;const r=s.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!kt(e,t)&&(s.options.loader||s.options.beforeLoad||kr(s))&&typeof r=="number"&&r!==1/0&&(s.options.pendingComponent??e.router.options?.defaultPendingComponent)){const o=setTimeout(()=>{ys(e)},r);n._nonReactive.pendingTimeout=o}},Vi=(e,t,s)=>{const n=e.router.getMatch(t);if(!n._nonReactive.beforeLoadPromise&&!n._nonReactive.loaderPromise)return;Nr(e,t,s,n);const r=()=>{const o=e.router.getMatch(t);o.preload&&(o.status==="redirected"||o.status==="notFound")&&me(e,o,o.error)};return n._nonReactive.beforeLoadPromise?n._nonReactive.beforeLoadPromise.then(r):r()},Gi=(e,t,s,n)=>{const r=e.router.getMatch(t);let o=r._nonReactive.loadPromise;r._nonReactive.loadPromise=He(()=>{o?.resolve(),o=void 0});const{paramsError:i,searchError:a}=r;i&&Xe(e,s,i),a&&Xe(e,s,a),Nr(e,t,n,r);const l=new AbortController;let u=!1;const c=()=>{u||(u=!0,e.updateMatch(t,I=>({...I,isFetching:"beforeLoad",fetchCount:I.fetchCount+1,abortController:l})))},d=()=>{r._nonReactive.beforeLoadPromise?.resolve(),r._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,I=>({...I,isFetching:!1}))};if(!n.options.beforeLoad){e.router.batch(()=>{c(),d()});return}r._nonReactive.beforeLoadPromise=He();const h={...Te(e,s,!1),...r.__routeContext},{search:f,params:g,cause:p}=r,v=kt(e,t),m={search:f,abortController:l,params:g,preload:v,context:h,location:e.location,navigate:I=>e.router.navigate({...I,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:v?"preload":p,matches:e.matches,routeId:n.id,...e.router.options.additionalContext},S=I=>{if(I===void 0){e.router.batch(()=>{c(),d()});return}(Y(I)||q(I))&&(c(),Xe(e,s,I)),e.router.batch(()=>{c(),e.updateMatch(t,y=>({...y,__beforeLoadContext:I})),d()})};let C;try{if(C=n.options.beforeLoad(m),it(C))return c(),C.catch(I=>{Xe(e,s,I)}).then(S)}catch(I){c(),Xe(e,s,I)}S(C)},Hi=(e,t)=>{const{id:s,routeId:n}=e.matches[t],r=e.router.looseRoutesById[n],o=()=>a(),i=()=>Gi(e,s,t,r),a=()=>{if(Fr(e,s))return;const l=Vi(e,s,r);return it(l)?l.then(i):i()};return o()},ji=(e,t,s)=>{const n=e.router.getMatch(t);if(!n||!s.options.head&&!s.options.scripts&&!s.options.headers)return;const r={ssr:e.router.options.ssr,matches:e.matches,match:n,params:n.params,loaderData:n.loaderData};return Promise.all([s.options.head?.(r),s.options.scripts?.(r),s.options.headers?.(r)]).then(([o,i,a])=>({meta:o?.meta,links:o?.links,headScripts:o?.scripts,headers:a,scripts:i,styles:o?.styles}))},Dr=(e,t,s,n,r)=>{const o=t[n-1],{params:i,loaderDeps:a,abortController:l,cause:u}=e.router.getMatch(s),c=Te(e,n),d=kt(e,s);return{params:i,deps:a,preload:!!d,parentMatchPromise:o,abortController:l,context:c,location:e.location,navigate:h=>e.router.navigate({...h,_fromLocation:e.location}),cause:d?"preload":u,route:r,...e.router.options.additionalContext}},Pn=async(e,t,s,n,r)=>{try{const o=e.router.getMatch(s);try{lt(r);const i=r.options.loader,a=typeof i=="function"?i:i?.handler,l=a?.(Dr(e,t,s,n,r)),u=!!a&&it(l);if((u||r._lazyPromise||r._componentsPromise||r.options.head||r.options.scripts||r.options.headers||o._nonReactive.minPendingPromise)&&e.updateMatch(s,d=>({...d,isFetching:"loader"})),a){const d=u?await l:l;me(e,e.router.getMatch(s),d),d!==void 0&&e.updateMatch(s,h=>({...h,loaderData:d}))}r._lazyPromise&&await r._lazyPromise;const c=o._nonReactive.minPendingPromise;c&&await c,r._componentsPromise&&await r._componentsPromise,e.updateMatch(s,d=>({...d,error:void 0,context:Te(e,n),status:"success",isFetching:!1,updatedAt:Date.now()}))}catch(i){let a=i;if(a?.name==="AbortError"){if(o.abortController.signal.aborted){o._nonReactive.loaderPromise?.resolve(),o._nonReactive.loaderPromise=void 0;return}e.updateMatch(s,u=>({...u,status:u.status==="pending"?"success":u.status,isFetching:!1,context:Te(e,n)}));return}const l=o._nonReactive.minPendingPromise;l&&await l,q(i)&&await r.options.notFoundComponent?.preload?.(),me(e,e.router.getMatch(s),i);try{r.options.onError?.(i)}catch(u){a=u,me(e,e.router.getMatch(s),u)}!Y(a)&&!q(a)&&await lt(r,["errorComponent"]),e.updateMatch(s,u=>({...u,error:a,context:Te(e,n),status:"error",isFetching:!1}))}}catch(o){const i=e.router.getMatch(s);i&&(i._nonReactive.loaderPromise=void 0),me(e,i,o)}},zi=async(e,t,s)=>{async function n(f,g,p,v,m){const S=Date.now()-g.updatedAt,C=f?m.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:m.options.staleTime??e.router.options.defaultStaleTime??0,I=m.options.shouldReload,y=typeof I=="function"?I(Dr(e,t,r,s,m)):I,{status:R,invalid:b}=v,_=S>=C&&(!!e.forceStaleReload||v.cause==="enter"||p!==void 0&&p!==v.id);i=R==="success"&&(b||(y??_)),f&&m.options.preload===!1||(i&&!e.sync&&c?(a=!0,(async()=>{try{await Pn(e,t,r,s,m);const M=e.router.getMatch(r);M._nonReactive.loaderPromise?.resolve(),M._nonReactive.loadPromise?.resolve(),M._nonReactive.loaderPromise=void 0,M._nonReactive.loadPromise=void 0}catch(M){Y(M)&&await e.router.navigate(M.options)}})()):R!=="success"||i?await Pn(e,t,r,s,m):xn(e,r,s))}const{id:r,routeId:o}=e.matches[s];let i=!1,a=!1;const l=e.router.looseRoutesById[o],u=l.options.loader,c=((typeof u=="function"?void 0:u?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!=="blocking";if(Fr(e,r)){if(!e.router.getMatch(r))return e.matches[s];xn(e,r,s)}else{const f=e.router.getMatch(r),g=e.router.stores.matchesId.get()[s],p=(g&&e.router.stores.matchStores.get(g)||null)?.routeId===o?g:e.router.stores.matches.get().find(m=>m.routeId===o)?.id,v=kt(e,r);if(f._nonReactive.loaderPromise){if(f.status==="success"&&!e.sync&&!f.preload&&c)return f;await f._nonReactive.loaderPromise;const m=e.router.getMatch(r),S=m._nonReactive.error||m.error;S&&me(e,m,S),m.status==="pending"&&await n(v,f,p,m,l)}else{const m=v&&!e.router.stores.matchStores.has(r),S=e.router.getMatch(r);S._nonReactive.loaderPromise=He(),m!==S.preload&&e.updateMatch(r,C=>({...C,preload:m})),await n(v,f,p,S,l)}}const d=e.router.getMatch(r);a||(d._nonReactive.loaderPromise?.resolve(),d._nonReactive.loadPromise?.resolve(),d._nonReactive.loadPromise=void 0),clearTimeout(d._nonReactive.pendingTimeout),d._nonReactive.pendingTimeout=void 0,a||(d._nonReactive.loaderPromise=void 0),d._nonReactive.dehydrated=void 0;const h=a?d.isFetching:!1;return h!==d.isFetching||d.invalid!==!1?(e.updateMatch(r,f=>({...f,isFetching:h,invalid:!1})),e.router.getMatch(r)):d};async function Tn(e){const t=e,s=[];Ui(t.router)&&ys(t);let n;for(let h=0;h<t.matches.length;h++){try{const f=Hi(t,h);it(f)&&await f}catch(f){if(Y(f))throw f;if(q(f))n=f;else if(!t.preload)throw f;break}if(t.serialError||t.firstBadMatchIndex!=null)break}const r=t.firstBadMatchIndex??t.matches.length,o=n&&!t.preload?En(t,n):void 0,i=n&&t.preload?0:o!==void 0?Math.min(o+1,r):r;let a,l;for(let h=0;h<i;h++)s.push(zi(t,s,h));try{await Promise.all(s)}catch{const h=await Promise.allSettled(s);for(const f of h){if(f.status!=="rejected")continue;const g=f.reason;if(Y(g))throw g;q(g)?a??=g:l??=g}if(l!==void 0)throw l}const u=a??(n&&!t.preload?n:void 0);let c=t.firstBadMatchIndex!==void 0?t.firstBadMatchIndex:t.matches.length-1;if(!u&&n&&t.preload)return t.matches;if(u){const h=En(t,u);h===void 0&&de();const f=t.matches[h],g=t.router.looseRoutesById[f.routeId],p=t.router.options?.defaultNotFoundComponent;!g.options.notFoundComponent&&p&&(g.options.notFoundComponent=p),u.routeId=f.routeId;const v=f.routeId===t.router.routeTree.id;t.updateMatch(f.id,m=>({...m,...v?{status:"success",globalNotFound:!0,error:void 0}:{status:"notFound",error:u},isFetching:!1})),c=h,await lt(g,["notFoundComponent"])}else if(!t.preload){const h=t.matches[0];h.globalNotFound||t.router.getMatch(h.id)?.globalNotFound&&t.updateMatch(h.id,f=>({...f,globalNotFound:!1,error:void 0}))}if(t.serialError&&t.firstBadMatchIndex!==void 0){const h=t.router.looseRoutesById[t.matches[t.firstBadMatchIndex].routeId];await lt(h,["errorComponent"])}for(let h=0;h<=c;h++){const{id:f,routeId:g}=t.matches[h],p=t.router.looseRoutesById[g];try{const v=ji(t,f,p);if(v){const m=await v;t.updateMatch(f,S=>({...S,...m}))}}catch(v){console.error(`Error executing head for route ${g}:`,v)}}const d=ys(t);if(it(d)&&await d,u)throw u;if(t.serialError&&!t.preload&&!t.onReady)throw t.serialError;return t.matches}function An(e,t){const s=t.map(n=>e.options[n]?.preload?.()).filter(Boolean);if(s.length!==0)return Promise.all(s)}function lt(e,t=bt){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(n=>{const{id:r,...o}=n.options;Object.assign(e.options,o),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);const s=()=>e._componentsLoaded?void 0:t===bt?(()=>{if(e._componentsPromise===void 0){const n=An(e,bt);n?e._componentsPromise=n.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():An(e,t);return e._lazyPromise?e._lazyPromise.then(s):s()}function kr(e){for(const t of bt)if(e.options[t]?.preload)return!0;return!1}var bt=["component","errorComponent","pendingComponent","notFoundComponent"];function qi(e){return{input:({url:t})=>{for(const s of e)t=Cs(s,t);return t},output:({url:t})=>{for(let s=e.length-1;s>=0;s--)t=$r(e[s],t);return t}}}function Wi(e){const t=Lr(e.basepath),s=`/${t}`,n=e.caseSensitive?s:s.toLowerCase(),r=`${n}/`;return{input:({url:o})=>{const i=e.caseSensitive?o.pathname:o.pathname.toLowerCase();return i===n?o.pathname="/":i.startsWith(r)&&(o.pathname=o.pathname.slice(s.length)),o},output:({url:o})=>(o.pathname=It(["/",t,o.pathname]),o)}}function Cs(e,t){const s=e?.input?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function $r(e,t){const s=e?.output?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function Ki(e,t){const{createMutableStore:s,createReadonlyStore:n,batch:r,init:o}=t,i=new Map,a=new Map,l=new Map,u=s(e.status),c=s(e.loadedAt),d=s(e.isLoading),h=s(e.isTransitioning),f=s(e.location),g=s(e.resolvedLocation),p=s(e.statusCode),v=s(e.redirect),m=s([]),S=s([]),C=s([]),I=n(()=>Yt(i,m.get())),y=n(()=>Yt(a,S.get())),R=n(()=>Yt(l,C.get())),b=n(()=>m.get()[0]),_=n(()=>m.get().some(F=>i.get(F)?.get().status==="pending")),M=n(()=>({locationHref:f.get().href,resolvedLocationHref:g.get()?.href,status:u.get()})),P=n(()=>({status:u.get(),loadedAt:c.get(),isLoading:d.get(),isTransitioning:h.get(),matches:I.get(),location:f.get(),resolvedLocation:g.get(),statusCode:p.get(),redirect:v.get()})),E=at(64);function O(F){let L=E.get(F);return L||(L=n(()=>{const B=m.get();for(const N of B){const he=i.get(N);if(he&&he.routeId===F)return he.get()}}),E.set(F,L)),L}const se={status:u,loadedAt:c,isLoading:d,isTransitioning:h,location:f,resolvedLocation:g,statusCode:p,redirect:v,matchesId:m,pendingIds:S,cachedIds:C,matches:I,pendingMatches:y,cachedMatches:R,firstId:b,hasPending:_,matchRouteDeps:M,matchStores:i,pendingMatchStores:a,cachedMatchStores:l,__store:P,getRouteMatchStore:O,setMatches:H,setPending:j,setCached:Z};H(e.matches),o?.(se);function H(F){Zt(F,i,m,s,r)}function j(F){Zt(F,a,S,s,r)}function Z(F){Zt(F,l,C,s,r)}return se}function Yt(e,t){const s=[];for(const n of t){const r=e.get(n);r&&s.push(r.get())}return s}function Zt(e,t,s,n,r){const o=e.map(a=>a.id),i=new Set(o);r(()=>{for(const a of t.keys())i.has(a)||t.delete(a);for(const a of e){const l=t.get(a.id);if(!l){const u=n(a);u.routeId=a.routeId,t.set(a.id,u);continue}l.routeId=a.routeId,l.get()!==a&&l.set(a)}Ci(s.get(),o)||s.set(o)})}var Re="__TSR_index",On="popstate",Ln="beforeunload";function Qi(e){let t=e.getLocation();const s=new Set,n=i=>{t=e.getLocation(),s.forEach(a=>a({location:t,action:i}))},r=i=>{e.notifyOnIndexChange??!0?n(i):t=e.getLocation()},o=async({task:i,navigateOpts:a,...l})=>{if(a?.ignoreBlocker??!1){i();return}const u=e.getBlockers?.()??[],c=l.type==="PUSH"||l.type==="REPLACE";if(typeof document<"u"&&u.length&&c)for(const d of u){const h=Ot(l.path,l.state);if(await d.blockerFn({currentLocation:t,nextLocation:h,action:l.type})){e.onBlocked?.();return}}i()};return{get location(){return t},get length(){return e.getLength()},subscribers:s,subscribe:i=>(s.add(i),()=>{s.delete(i)}),push:(i,a,l)=>{const u=t.state[Re];a=Fn(u+1,a),o({task:()=>{e.pushState(i,a),n({type:"PUSH"})},navigateOpts:l,type:"PUSH",path:i,state:a})},replace:(i,a,l)=>{const u=t.state[Re];a=Fn(u,a),o({task:()=>{e.replaceState(i,a),n({type:"REPLACE"})},navigateOpts:l,type:"REPLACE",path:i,state:a})},go:(i,a)=>{o({task:()=>{e.go(i),r({type:"GO",index:i})},navigateOpts:a,type:"GO"})},back:i=>{o({task:()=>{e.back(i?.ignoreBlocker??!1),r({type:"BACK"})},navigateOpts:i,type:"BACK"})},forward:i=>{o({task:()=>{e.forward(i?.ignoreBlocker??!1),r({type:"FORWARD"})},navigateOpts:i,type:"FORWARD"})},canGoBack:()=>t.state[Re]!==0,createHref:i=>e.createHref(i),block:i=>{if(!e.setBlockers)return()=>{};const a=e.getBlockers?.()??[];return e.setBlockers([...a,i]),()=>{const l=e.getBlockers?.()??[];e.setBlockers?.(l.filter(u=>u!==i))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:n}}function Fn(e,t){t||(t={});const s=js();return{...t,key:s,__TSR_key:s,[Re]:e}}function Ji(e){const t=e?.window??(typeof document<"u"?window:void 0),s=t.history.pushState,n=t.history.replaceState;let r=[];const o=()=>r,i=_=>r=_,a=e?.createHref??(_=>_),l=e?.parseLocation??(()=>Ot(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){const _=js();t.history.replaceState({[Re]:0,key:_,__TSR_key:_},"")}let u=l(),c,d=!1,h=!1,f=!1,g=!1;const p=()=>u;let v,m;const S=()=>{v&&(b._ignoreSubscribers=!0,(v.isPush?t.history.pushState:t.history.replaceState)(v.state,"",v.href),b._ignoreSubscribers=!1,v=void 0,m=void 0,c=void 0)},C=(_,M,P)=>{const E=a(M);m||(c=u),u=Ot(M,P),v={href:E,state:P,isPush:v?.isPush||_==="push"},m||(m=Promise.resolve().then(()=>S()))},I=_=>{u=l(),b.notify({type:_})},y=async()=>{if(h){h=!1;return}const _=l(),M=_.state[Re]-u.state[Re],P=M===1,E=M===-1,O=!P&&!E||d;d=!1;const se=O?"GO":E?"BACK":"FORWARD",H=O?{type:"GO",index:M}:{type:E?"BACK":"FORWARD"};if(f)f=!1;else{const j=o();if(typeof document<"u"&&j.length){for(const Z of j)if(await Z.blockerFn({currentLocation:u,nextLocation:_,action:se})){h=!0,t.history.go(1),b.notify(H);return}}}u=l(),b.notify(H)},R=_=>{if(g){g=!1;return}let M=!1;const P=o();if(typeof document<"u"&&P.length)for(const E of P){const O=E.enableBeforeUnload??!0;if(O===!0){M=!0;break}if(typeof O=="function"&&O()===!0){M=!0;break}}if(M)return _.preventDefault(),_.returnValue=""},b=Qi({getLocation:p,getLength:()=>t.history.length,pushState:(_,M)=>C("push",_,M),replaceState:(_,M)=>C("replace",_,M),back:_=>(_&&(f=!0),g=!0,t.history.back()),forward:_=>{_&&(f=!0),g=!0,t.history.forward()},go:_=>{d=!0,t.history.go(_)},createHref:_=>a(_),flush:S,destroy:()=>{t.history.pushState=s,t.history.replaceState=n,t.removeEventListener(Ln,R,{capture:!0}),t.removeEventListener(On,y)},onBlocked:()=>{c&&u!==c&&(u=c)},getBlockers:o,setBlockers:i,notifyOnIndexChange:!1});return t.addEventListener(Ln,R,{capture:!0}),t.addEventListener(On,y),t.history.pushState=function(..._){const M=s.apply(t.history,_);return b._ignoreSubscribers||I("PUSH"),M},t.history.replaceState=function(..._){const M=n.apply(t.history,_);return b._ignoreSubscribers||I("REPLACE"),M},b}function Xi(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"");return t.startsWith("//")&&(t="/"+t.replace(/^\/+/,"")),t}function Ot(e,t){const s=Xi(e),n=s.indexOf("#"),r=s.indexOf("?"),o=js();return{href:s,pathname:s.substring(0,n>0?r>0?Math.min(n,r):n:r>0?r:s.length),hash:n>-1?s.substring(n):"",search:r>-1?s.slice(r,n===-1?void 0:n):"",state:t||{[Re]:0,key:o,__TSR_key:o}}}function js(){return(Math.random()+1).toString(36).substring(7)}function Ge(e,t){const s=t,n=e;return{fromLocation:s,toLocation:n,pathChanged:s?.pathname!==n.pathname,hrefChanged:s?.href!==n.href,hashChanged:s?.hash!==n.hash}}var Rs=new WeakMap,Yi=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=s=>s(),this.update=s=>{const n=this.options,r=this.basepath??n?.basepath??"/",o=this.basepath===void 0,i=n?.rewrite;if(this.options={...n,...s},this.isServer=this.options.isServer??typeof document>"u",this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=Oi(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=Ji()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost"),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let c;this.resolvePathCache=at(1e3),c=this.buildRouteTree(),this.setRoutes(c)}if(!this.stores&&this.latestLocation){const c=this.getStoreConfig(this);this.batch=c.batch,this.stores=Ki(ea(this.latestLocation),c),da(this)}let a=!1;const l=this.options.basepath??"/",u=this.options.rewrite;if(o||r!==l||i!==u){this.basepath=l;const c=[],d=Lr(l);d&&d!=="/"&&c.push(Wi({basepath:l})),u&&c.push(u),this.rewrite=c.length===0?void 0:c.length===1?c[0]:qi(c),this.history&&this.updateLatestLocation(),a=!0}a&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<"u"&&"CSS"in window&&typeof window.CSS?.supports=="function"&&(this.isViewTransitionTypesSupported=window.CSS.supports("selector(:active-view-transition-type(a))"))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const s=Ei(this.routeTree,this.options.caseSensitive,(n,r)=>{n.init({originalIndex:r})});return this.options.routeMasks&&Ii(this.options.routeMasks,s.processedTree),s},this.subscribe=(s,n)=>{const r={eventType:s,fn:n};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=s=>{this.subscribers.forEach(n=>{n.eventType===s.type&&n.fn(s)})},this.parseLocation=(s,n)=>{const r=({pathname:l,search:u,hash:c,href:d,state:h})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(l)){const m=this.options.parseSearch(u),S=this.options.stringifySearch(m);return{href:l+S+c,publicHref:l+S+c,pathname:Je(l).path,external:!1,searchStr:S,search:_e(n?.search,m),hash:Je(c.slice(1)).path,state:xe(n?.state,h)}}const f=new URL(d,this.origin),g=Cs(this.rewrite,f),p=this.options.parseSearch(g.search),v=this.options.stringifySearch(p);return g.search=v,{href:g.href.replace(g.origin,""),publicHref:d,pathname:Je(g.pathname).path,external:!!this.rewrite&&g.origin!==this.origin,searchStr:v,search:_e(n?.search,p),hash:Je(g.hash.slice(1)).path,state:xe(n?.state,h)}},o=r(s),{__tempLocation:i,__tempKey:a}=o.state;if(i&&(!a||a===this.tempLocationKey)){const l=r(i);return l.state.key=o.state.key,l.state.__TSR_key=o.state.__TSR_key,delete l.state.__tempLocation,{...l,maskedLocation:o}}return o},this.resolvePathWithBase=(s,n)=>Ai({base:s,to:n.includes("//")?Hs(n):n,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(s,n,r)=>typeof s=="string"?this.matchRoutesInternal({pathname:s,search:n},r):this.matchRoutesInternal(s,n),this.getMatchedRoutes=s=>ta({pathname:s,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=s=>{const n=this.getMatch(s);n&&(n.abortController.abort(),clearTimeout(n._nonReactive.pendingTimeout),n._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(s=>{this.cancelMatch(s)}),this.stores.matchesId.get().forEach(s=>{if(this.stores.pendingMatchStores.has(s))return;const n=this.stores.matchStores.get(s)?.get();n&&(n.status==="pending"||n.isFetching==="loader")&&this.cancelMatch(s)})},this.buildLocation=s=>{const n=(o={})=>{const i=o._fromLocation||this.pendingBuiltLocation||this.latestLocation,a=this.matchRoutesLightweight(i);o.from;const l=o.unsafeRelative==="path"?i.pathname:o.from??a.fullPath,u=o.to?`${o.to}`:void 0,c=a.search,d=Object.assign(Object.create(null),a.params),h=u?.charCodeAt(0)===47?"/":this.resolvePathWithBase(l,"."),f=u?this.resolvePathWithBase(h,u):h,g=o.params===!1||o.params===null?Object.create(null):(o.params??!0)===!0?d:Object.assign(d,ue(o.params,d)),p=this.routesByPath[ce(f)];let v;if(p)v=this.getRouteBranch(p);else if(f.includes("$"))v=[];else{const E=this.getMatchedRoutes(f);v=E.matchedRoutes,this.options.notFoundRoute&&(!E.foundRoute||E.foundRoute.path!=="/"&&E.routeParams["**"])&&(v=[...v,this.options.notFoundRoute])}if(v.length&&Tt(g))for(const E of v){const O=E.options.params?.stringify??E.options.stringifyParams;if(O)try{Object.assign(g,O(g))}catch{}}const m=s.leaveParams?f:Je(_n({path:f,params:g,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path;let S=c;if(s._includeValidateSearch&&this.options.search?.strict){const E={};v.forEach(O=>{if(O.options.validateSearch)try{Object.assign(E,_t(O.options.validateSearch,{...E,...S}))}catch{}}),S=E}S=sa({search:S,dest:o,destRoutes:v,_includeValidateSearch:s._includeValidateSearch}),S=_e(c,S);const C=this.options.stringifySearch(S),I=o.hash===!0?i.hash:o.hash?ue(o.hash,i.hash):void 0,y=I?`#${I}`:"";let R=o.state===!0?i.state:o.state?ue(o.state,i.state):{};R=xe(i.state,R);const b=`${m}${C}${y}`;let _,M,P=!1;if(this.rewrite){const E=new URL(b,this.origin),O=$r(this.rewrite,E);_=E.href.replace(E.origin,""),O.origin!==this.origin?(M=O.href,P=!0):M=O.pathname+O.search+O.hash}else _=yi(b),M=_;return{publicHref:M,href:_,pathname:m,search:S,searchStr:C,state:R,hash:I??"",external:P,unmaskOnReload:o.unmaskOnReload}},r=(o={},i)=>{const a=n(o);let l=i?n(i):void 0;if(!l){const u=Object.create(null);if(this.options.routeMasks){const c=wi(a.pathname,this.processedTree);if(c){Object.assign(u,c.rawParams);const{from:d,params:h,...f}=c.route,g=h===!1||h===null?Object.create(null):(h??!0)===!0?u:Object.assign(u,ue(h,u));i={from:s.from,...f,params:g},l=n(i)}}}return l&&(a.maskedLocation=l),a};return s.mask?r(s,{from:s.from,...s.mask}):r(s)},this.commitLocation=async({viewTransition:s,ignoreBlocker:n,...r})=>{let o;const i=()=>{const u=["key","__TSR_key","__TSR_index","__hashScrollIntoViewOptions"];u.forEach(d=>{r.state[d]=this.latestLocation.state[d]});const c=Ce(r.state,this.latestLocation.state);return u.forEach(d=>{delete r.state[d]}),c},a=ce(this.latestLocation.href)===ce(r.href);let l=this.commitLocationPromise;if(this.commitLocationPromise=He(()=>{l?.resolve(),l=void 0}),a&&i())this.load();else{let{maskedLocation:u,hashScrollIntoView:c,...d}=r;u&&(d={...u,state:{...u.state,__tempKey:void 0,__tempLocation:{...d,search:d.searchStr,state:{...d.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(d.unmaskOnReload??this.options.unmaskOnReload??!1)&&(d.state.__tempKey=this.tempLocationKey)),d.state.__hashScrollIntoViewOptions=c??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=s,o=r.replace?"REPLACE":"PUSH",this.history[o==="REPLACE"?"replace":"push"](d.publicHref,d.state,{ignoreBlocker:n})}return this._scroll.next=r.resetScroll??!0,this.history.subscribers.size||this.load(o?{action:{type:o}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:s,resetScroll:n,hashScrollIntoView:r,viewTransition:o,ignoreBlocker:i,href:a,...l}={})=>{if(a){const d=this.history.location.state.__TSR_index,h=Ot(a,{__TSR_index:s?d:d+1}),f=new URL(h.pathname,this.origin);l.to=Cs(this.rewrite,f).pathname,l.search=this.options.parseSearch(h.search),l.hash=h.hash.slice(1)}const u=this.buildLocation({...l,_includeValidateSearch:!0});this.pendingBuiltLocation=u;const c=this.commitLocation({...u,viewTransition:o,replace:s,resetScroll:n,hashScrollIntoView:r,ignoreBlocker:i});return queueMicrotask(()=>{this.pendingBuiltLocation===u&&(this.pendingBuiltLocation=void 0)}),c},this.navigate=async({to:s,reloadDocument:n,href:r,publicHref:o,...i})=>{let a=!1;if(r)try{new URL(`${r}`),a=!0}catch{}if(a&&!n&&(n=!0),n){if(s!==void 0||!r){const u=this.buildLocation({to:s,...i});r=r??u.publicHref,o=o??u.publicHref}const l=!a&&o?o:r;if(Me(l,this.protocolAllowlist))return;if(!i.ignoreBlocker){const u=this.history.getBlockers?.()??[];for(const c of u)if(c?.blockerFn&&await c.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:"PUSH"}))return}i.replace?window.location.replace(l):window.location.href=l;return}return this.buildAndCommitLocation({...i,href:r,to:s,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();const s=this.matchRoutes(this.latestLocation),n=this.stores.cachedMatches.get().filter(r=>!s.some(o=>o.id===r.id));this.batch(()=>{this.stores.status.set("pending"),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(s),this.stores.setCached(n)})},this.load=async s=>{const n=s?.action?.type;let r,o,i;const a=this.stores.resolvedLocation.get()??this.stores.location.get();for(i=new Promise(u=>{this.startTransition(async()=>{try{this.beforeLoad(),n?Rs.set(this.latestLocation,n):Rs.delete(this.latestLocation);const c=this.latestLocation,d=Ge(c,this.stores.resolvedLocation.get());this.stores.redirect.get()||this.emit({type:"onBeforeNavigate",...d}),this.emit({type:"onBeforeLoad",...d}),await Tn({router:this,sync:s?.sync,forceStaleReload:a.href===c.href,matches:this.stores.pendingMatches.get(),location:c,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let h=null,f=null,g=null,p=null;this.batch(()=>{const v=this.stores.pendingMatches.get(),m=v.length,S=this.stores.matches.get();h=m?S.filter(y=>!this.stores.pendingMatchStores.has(y.id)):null;const C=new Set;for(const y of this.stores.pendingMatchStores.values())y.routeId&&C.add(y.routeId);const I=new Set;for(const y of this.stores.matchStores.values())y.routeId&&I.add(y.routeId);f=m?S.filter(y=>!C.has(y.routeId)):null,g=m?v.filter(y=>!I.has(y.routeId)):null,p=m?v.filter(y=>I.has(y.routeId)):S,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),m&&(this.stores.setMatches(v),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...h.filter(y=>y.status!=="error"&&y.status!=="notFound"&&y.status!=="redirected")]),this.clearExpiredCache())});for(const[v,m]of[[f,"onLeave"],[g,"onEnter"],[p,"onStay"]])if(v)for(const S of v)this.looseRoutesById[S.routeId].options[m]?.(S)})})}})}catch(c){Y(c)?(r=c,this.navigate({...r.options,replace:!0,ignoreBlocker:!0})):q(c)&&(o=c);const d=r?r.status:o?404:this.stores.matches.get().some(h=>h.status==="error")?500:200;this.batch(()=>{this.stores.statusCode.set(d),this.stores.redirect.set(r)})}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),u()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let l;this.hasNotFoundMatch()?l=404:this.stores.matches.get().some(u=>u.status==="error")&&(l=500),l!==void 0&&this.stores.statusCode.set(l)},this.startViewTransition=s=>{const n=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,n&&typeof document<"u"&&"startViewTransition"in document&&typeof document.startViewTransition=="function"){let r;if(typeof n=="object"&&this.isViewTransitionTypesSupported){const o=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof n.types=="function"?n.types(Ge(o,i)):n.types;if(a===!1){s();return}r={update:s,types:a}}else r=s;document.startViewTransition(r)}else s()},this.updateMatch=(s,n)=>{this.startTransition(()=>{const r=this.stores.pendingMatchStores.get(s);if(r){r.set(n);return}const o=this.stores.matchStores.get(s);if(o){o.set(n);return}const i=this.stores.cachedMatchStores.get(s);if(i){const a=n(i.get());a.status==="redirected"?this.stores.cachedMatchStores.delete(s)&&this.stores.cachedIds.set(l=>l.filter(u=>u!==s)):i.set(a)}})},this.getMatch=s=>this.stores.cachedMatchStores.get(s)?.get()??this.stores.pendingMatchStores.get(s)?.get()??this.stores.matchStores.get(s)?.get(),this.invalidate=s=>{const n=r=>s?.filter?.(r)??!0?{...r,invalid:!0,...s?.forcePending||r.status==="error"||r.status==="notFound"?{status:"pending",error:void 0}:void 0}:r;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(n)),this.stores.setCached(this.stores.cachedMatches.get().map(n)),this.stores.setPending(this.stores.pendingMatches.get().map(n))}),this.shouldViewTransition=!1,this.load({sync:s?.sync})},this.getParsedLocationHref=s=>s.publicHref||"/",this.resolveRedirect=s=>{const n=s.headers.get("Location");if(!s.options.href||s.options._builtLocation){const r=s.options._builtLocation??this.buildLocation(s.options),o=this.getParsedLocationHref(r);s.options.href=o,s.headers.set("Location",o)}else if(n)try{const r=new URL(n);if(this.origin&&r.origin===this.origin){const o=r.pathname+r.search+r.hash;s.options.href=o,s.headers.set("Location",o)}}catch{}if(s.options.href&&!s.options._builtLocation&&Me(s.options.href,this.protocolAllowlist))throw new Error("Redirect blocked: unsafe protocol");return s.headers.get("Location")||s.headers.set("Location",s.options.href),s},this.clearCache=s=>{const n=s?.filter;n!==void 0?this.stores.setCached(this.stores.cachedMatches.get().filter(r=>!n(r))):this.stores.setCached([])},this.clearExpiredCache=()=>{const s=Date.now(),n=r=>{const o=this.looseRoutesById[r.routeId];if(!o.options.loader)return!0;const i=(r.preload?o.options.preloadGcTime??this.options.defaultPreloadGcTime:o.options.gcTime??this.options.defaultGcTime)??300*1e3;return r.status==="error"?!0:s-r.updatedAt>=i};this.clearCache({filter:n})},this.loadRouteChunk=lt,this.preloadRoute=async s=>{const n=s._builtLocation??this.buildLocation(s);let r=this.matchRoutes(n,{throwOnError:!0,preload:!0,dest:s});const o=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),i=new Set([...o,...this.stores.cachedIds.get()]),a=r.filter(l=>!i.has(l.id));if(a.length){const l=this.stores.cachedMatches.get();this.stores.setCached([...l,...a])}try{return r=await Tn({router:this,matches:r,location:n,preload:!0,updateMatch:(l,u)=>{o.has(l)?r=r.map(c=>c.id===l?u(c):c):this.updateMatch(l,u)}}),r}catch(l){if(Y(l))return l.options.reloadDocument?void 0:await this.preloadRoute({...l.options,_fromLocation:n});q(l)||console.error(l);return}},this.matchRoute=(s,n)=>{const r={...s,to:s.to?this.resolvePathWithBase(s.from||"",s.to):void 0,params:s.params||{},leaveParams:!0},o=this.buildLocation(r);if(n?.pending&&this.stores.status.get()!=="pending")return!1;const i=(n?.pending===void 0?!this.stores.isLoading.get():n.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),a=bi(o.pathname,n?.caseSensitive??!1,n?.fuzzy??!1,i.pathname,this.processedTree);return!a||s.params&&!Ce(a.rawParams,s.params,{partial:!0})?!1:n?.includeSearch??!0?Ce(i.search,o.search,{partial:!0})?a.rawParams:!1:a.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(s=>s.status==="notFound"||s.globalNotFound),this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??"fuzzy",stringifySearch:e.stringifySearch??Di,parseSearch:e.parseSearch??Ni,protocolAllowlist:e.protocolAllowlist??Si}),typeof document<"u"&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:s}){this.routesById=e,this.routesByPath=t,this.processedTree=s;const n=this.options.notFoundRoute;n&&(n.init({originalIndex:99999999999}),this.routesById[n.id]=n)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=Ar(e),this.routeBranchCache.set(e,t)),t}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,t){const s=this.getMatchedRoutes(e.pathname),{foundRoute:n,routeParams:r}=s;let{matchedRoutes:o}=s,i=!1;(n?n.path!=="/"&&r["**"]:ce(e.pathname))&&(this.options.notFoundRoute?o=[...o,this.options.notFoundRoute]:i=!0);const a=i?ra(this.options.notFoundMode,o):void 0,l=new Array(o.length),u=new Map;for(const c of this.stores.matchStores.values())c.routeId&&u.set(c.routeId,c.get());for(let c=0;c<o.length;c++){const d=o[c],h=l[c-1];let f,g,p;{const O=h?.search??e.search,se=h?._strictSearch??void 0;try{const H=_t(d.options.validateSearch,{...O})??void 0;f={...O,...H},g={...se,...H},p=void 0}catch(H){let j=H;if(H instanceof Lt||(j=new Lt(H.message,{cause:H})),t?.throwOnError)throw j;f=O,g={},p=j}}const v=d.options.loaderDeps?.({search:f})??"",m=v?JSON.stringify(v):"",{interpolatedPath:S,usedParams:C}=_n({path:d.fullPath,params:r,decoder:this.pathParamsDecoder,server:this.isServer}),I=d.id+S+m,y=this.getMatch(I),R=u.get(d.id),b=y?._strictParams??C;let _;if(!y)try{Nn(d,b)}catch(O){if(q(O)||Y(O)?_=O:_=new Zi(O.message,{cause:O}),t?.throwOnError)throw _}Object.assign(r,b);const M=R?"stay":"enter";let P;if(y)P={...y,cause:M,params:R?.params??r,_strictParams:b,search:_e(R?R.search:y.search,f),_strictSearch:g};else{const O=d.options.loader||d.options.beforeLoad||d.lazyFn||kr(d)?"pending":"success";P={id:I,ssr:d.options.ssr,index:c,routeId:d.id,params:R?.params??r,_strictParams:b,pathname:S,updatedAt:Date.now(),search:R?_e(R.search,f):f,_strictSearch:g,searchError:void 0,status:O,isFetching:!1,error:void 0,paramsError:_,__routeContext:void 0,_nonReactive:{loadPromise:He()},__beforeLoadContext:void 0,context:{},abortController:new AbortController,fetchCount:0,cause:M,loaderDeps:R?xe(R.loaderDeps,v):v,invalid:!1,preload:!1,links:void 0,scripts:void 0,headScripts:void 0,meta:void 0,staticData:d.options.staticData||{},fullPath:d.fullPath}}t?.preload||(P.globalNotFound=a===d.id),P.searchError=p;const E=this.getParentContext(h);P.context={...E,...P.__routeContext,...P.__beforeLoadContext},l[c]=P}for(let c=0;c<l.length;c++){const d=l[c],h=this.looseRoutesById[d.routeId],f=this.getMatch(d.id),g=u.get(d.routeId);if(d.params=g?_e(g.params,r):r,!f){const p=l[c-1],v=this.getParentContext(p);if(h.options.context){const m={deps:d.loaderDeps,params:d.params,context:v??{},location:e,navigate:S=>this.navigate({...S,_fromLocation:e}),buildLocation:this.buildLocation,cause:d.cause,abortController:d.abortController,preload:!!d.preload,matches:l,routeId:h.id};d.__routeContext=h.options.context(m)??void 0}d.context={...v,...d.__routeContext,...d.__beforeLoadContext}}}return l}matchRoutesLightweight(e){const t=ot(this.stores.matchesId.get()),s=this.lightweightCache.get(e);if(s&&s[0]===t)return s[1];const{matchedRoutes:n,routeParams:r}=this.getMatchedRoutes(e.pathname),o=ot(n),i={...e.search};for(const d of n)try{Object.assign(i,_t(d.options.validateSearch,i))}catch{}const a=t&&this.stores.matchStores.get(t)?.get(),l=a&&a.routeId===o.id&&a.pathname===e.pathname;let u;if(l)u=a.params;else{const d=Object.assign(Object.create(null),r);for(const h of n)try{Nn(h,d)}catch{}u=d}const c={matchedRoutes:n,fullPath:o.fullPath,search:i,params:u};return this.lightweightCache.set(e,[t,c]),c}},Lt=class extends Error{},Zi=class extends Error{};function ea(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:"idle",resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function _t(e,t){if(e==null)return{};if("~standard"in e){const s=e["~standard"].validate(t);if(s instanceof Promise)throw new Lt("Async validation not supported");if(s.issues)throw new Lt(JSON.stringify(s.issues,void 0,2),{cause:s});return s.value}return"parse"in e?e.parse(t):typeof e=="function"?e(t):{}}function ta({pathname:e,routesById:t,processedTree:s}){const n=Object.create(null),r=ce(e);let o;const i=_i(r,s,!0);return i&&(o=i.route,Object.assign(n,i.rawParams)),{matchedRoutes:i?.branch||[t.__root__],routeParams:n,foundRoute:o}}function sa({search:e,dest:t,destRoutes:s,_includeValidateSearch:n}){return na(s)(e,t,n??!1)}function na(e){let t,s;const n=[];for(const o of e){const i=o.options;if("search"in i)i.search?.middlewares&&n.push(...i.search.middlewares);else if(i.preSearchFilters||i.postSearchFilters){const l=({search:u,next:c})=>{const d=c(i.preSearchFilters?i.preSearchFilters.reduce((h,f)=>f(h),u):u);return i.postSearchFilters?i.postSearchFilters.reduce((h,f)=>f(h),d):d};n.push(l)}const a=i.validateSearch;if(a){const l=({search:u,next:c,meta:d})=>{const h=c(u);if(s)try{const f=_t(a,h);if(d&&f)for(const g in f)g in h||(d.defaulted||=new Map).set(g,f[g]);return{...h,...f}}catch{}return h};n.push(l)}}const r=(o,i,a)=>{if(o>=n.length){if(!t.search)return{};if(t.search===!0)return i;const u=ue(t.search,i);return a&&(a.explicit=u),u}const l=(u,c)=>{if(c){const d=a||{};return{search:r(o+1,u,d),meta:d}}return r(o+1,u,a)};return n[o]({search:i,next:l,meta:a})};return function(i,a,l){return t=a,s=l,r(0,i)}}function ra(e,t){if(e!=="root")for(let s=t.length-1;s>=0;s--){const n=t[s];if(n.children)return n.id}return wt}function Nn(e,t){const s=e.options.params?.parse??e.options.parseParams;if(s){const n=s(t);if(n===!1)throw new Error("Route params.parse returned false for a matched route");Object.assign(t,n)}}function oa(){try{return sessionStorage}catch{return}}var ia="tsr-scroll-restoration-v1_3",Br=oa();function aa(){try{return JSON.parse(Br?.getItem("tsr-scroll-restoration-v1_3")||"{}")}catch{return{}}}function la(){try{Br?.setItem(ia,JSON.stringify($e))}catch{}}var $e=aa(),Dn="data-scroll-restoration-id",ua=e=>e.state.__TSR_key||e.href;function ca(e){const t=e.getAttribute(Dn);if(t)return`[${Dn}="${t}"]`;let s="",n=e,r;for(;r=n.parentNode;){let o=1,i=n;for(;i=i.previousElementSibling;)o++;const a=`${n.localName}:nth-child(${o})`;s=s?`${a} > ${s}`:a,n=r}return s}var pt=!1,Be="window";function Is(e){try{return typeof e=="function"?e():document.querySelector(e)}catch{}}function kn(e){const t=[];for(const s of e){if(s===Be)continue;const n=Is(s);n&&t.push(n)}return t}function da(e,t){const s=t??e.options.scrollRestoration,n=e._scroll;s&&(n.restoring=!0);const r=e.options.getScrollRestorationKey||ua,o=new Map,i=(u,c,d)=>{const h=o.get(u)||{};h.scrollX=c,h.scrollY=d,o.set(u,h)},a=u=>{if(!(pt||!n.restoring))if(u.target===document)i(Be,scrollX,scrollY);else{const c=u.target;i(c,c.scrollLeft,c.scrollTop)}},l=u=>{if(!n.restoring)return;const c=$e[u]||={};for(const[d,h]of o)d===Be?c[Be]=h:d.isConnected&&(c[ca(d)]=h)};s&&!n.restoration&&(n.restoration=!0,pt=!1,history.scrollRestoration="manual",document.addEventListener("scroll",a,!0),e.subscribe("onBeforeLoad",u=>{u.fromLocation&&l(r(u.fromLocation)),o.clear()}),addEventListener("pagehide",()=>{l(r(e.stores.resolvedLocation.get()??e.stores.location.get())),la()})),!n.reset&&(n.reset=!0,e.subscribe("onRendered",u=>{const c=e.options.scrollRestorationBehavior,d=e.options.scrollToTopSelectors,h=n.next;let f;if(o.clear(),h||(n.next=!0),typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation}))return;const g=r(u.toLocation),p=u.fromLocation&&r(u.fromLocation);if(n.restoring&&p&&p!==g){const v=$e[p];if(v){let m=$e[g];for(const S in v){if(S===Be){if(h)continue}else{const C=Is(S);if(!C||h&&d&&(f??=kn(d),f.includes(C)))continue}m||(m=$e[g]={}),m[S]??=v[S]}}}pt=!0;try{const v=u.toLocation.hash,m=u.toLocation.state.__hashScrollIntoViewOptions??!0;let S=!1;if(h){const C=Rs.get(u.toLocation),I=v&&m&&(C==="PUSH"||C==="REPLACE"),y=n.restoring?$e[g]:void 0;if(y)for(const R in y){const{scrollX:b,scrollY:_}=y[R];if(R===Be){if(I)continue;scrollTo({top:_,left:b,behavior:c}),S=!0}else{const M=Is(R);M&&(M.scrollLeft=b,M.scrollTop=_)}}if(!S&&!v){const R={top:0,left:0,behavior:c};if(scrollTo(R),d){f??=kn(d);for(const b of f)b.scrollTo(R)}}}!S&&v&&m&&document.getElementById(v)?.scrollIntoView(m)}finally{pt=!1}}))}var ha="Error preloading route! ☝️",Ur=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=t=>{this.originalIndex=t.originalIndex;const s=this.options,n=!s?.path&&!s?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=wt:this.parentRoute||de();let r=n?wt:s?.path;r&&r!=="/"&&(r=Or(r));const o=s?.id||r;let i=n?wt:It([this.parentRoute.id==="__root__"?"":this.parentRoute.id,o]);r==="__root__"&&(r="/"),i!=="__root__"&&(i=It(["/",i]));const a=i==="__root__"?"/":It([this.parentRoute.fullPath,r]);this._path=r,this._id=i,this._fullPath=a,this._to=ce(a)},this.addChildren=t=>this._addFileChildren(t),this._addFileChildren=t=>(Array.isArray(t)&&(this.children=t),typeof t=="object"&&t!==null&&(this.children=Object.values(t)),this),this._addFileTypes=()=>this,this.updateLoader=t=>(Object.assign(this.options,t),this),this.update=t=>(Object.assign(this.options,t),this),this.lazy=t=>(this.lazyFn=t,this),this.redirect=t=>Bi({from:this.fullPath,...t}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw new Error("Route cannot have both an 'id' and a 'path' option.")}},fa=class extends Ur{constructor(e){super(e)}};function zs(e){const t=e.errorComponent??qs;return(0,x.jsx)(ga,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:s,reset:n})=>s?w.createElement(t,{error:s,reset:n}):e.children})}var ga=class extends w.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,t){const s=e.getResetKey();return t.error&&t.resetKey!==s?{resetKey:s,error:null}:{resetKey:s}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,t){this.props.onCatch&&this.props.onCatch(e,t)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function qs({error:e}){const[t,s]=w.useState(!1);return(0,x.jsxs)("div",{style:{padding:".5rem",maxWidth:"100%"},children:[(0,x.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:".5rem"},children:[(0,x.jsx)("strong",{style:{fontSize:"1rem"},children:"Something went wrong!"}),(0,x.jsx)("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:()=>s(n=>!n),children:t?"Hide Error":"Show Error"})]}),(0,x.jsx)("div",{style:{height:".25rem"}}),t?(0,x.jsx)("div",{children:(0,x.jsx)("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"},children:e.message?(0,x.jsx)("code",{children:e.message}):null})}):null]})}function pa({children:e,fallback:t=null}){return Vr()?(0,x.jsx)(w.Fragment,{children:e}):(0,x.jsx)(w.Fragment,{children:t})}function Vr(){return w.useSyncExternalStore(ma,()=>!0,()=>!1)}function ma(){return()=>{}}var Gr=w.createContext(null);function re(e){return w.useContext(Gr)}var $t=w.createContext(void 0),va=w.createContext(void 0),$=(e=>(e[e.None=0]="None",e[e.Mutable=1]="Mutable",e[e.Watching=2]="Watching",e[e.RecursedCheck=4]="RecursedCheck",e[e.Recursed=8]="Recursed",e[e.Dirty=16]="Dirty",e[e.Pending=32]="Pending",e))($||{});function Sa({update:e,notify:t,unwatched:s}){return{link:n,unlink:r,propagate:o,checkDirty:i,shallowPropagate:a};function n(u,c,d){const h=c.depsTail;if(h!==void 0&&h.dep===u)return;const f=h!==void 0?h.nextDep:c.deps;if(f!==void 0&&f.dep===u){f.version=d,c.depsTail=f;return}const g=u.subsTail;if(g!==void 0&&g.version===d&&g.sub===c)return;const p=c.depsTail=u.subsTail={version:d,dep:u,sub:c,prevDep:h,nextDep:f,prevSub:g,nextSub:void 0};f!==void 0&&(f.prevDep=p),h!==void 0?h.nextDep=p:c.deps=p,g!==void 0?g.nextSub=p:u.subs=p}function r(u,c=u.sub){const d=u.dep,h=u.prevDep,f=u.nextDep,g=u.nextSub,p=u.prevSub;return f!==void 0?f.prevDep=h:c.depsTail=h,h!==void 0?h.nextDep=f:c.deps=f,g!==void 0?g.prevSub=p:d.subsTail=p,p!==void 0?p.nextSub=g:(d.subs=g)===void 0&&s(d),f}function o(u){let c=u.nextSub,d;e:do{const h=u.sub;let f=h.flags;if(f&60?f&12?f&4?!(f&48)&&l(u,h)?(h.flags=f|40,f&=1):f=0:h.flags=f&-9|32:f=0:h.flags=f|32,f&2&&t(h),f&1){const g=h.subs;if(g!==void 0){const p=(u=g).nextSub;p!==void 0&&(d={value:c,prev:d},c=p);continue}}if((u=c)!==void 0){c=u.nextSub;continue}for(;d!==void 0;)if(u=d.value,d=d.prev,u!==void 0){c=u.nextSub;continue e}break}while(!0)}function i(u,c){let d,h=0,f=!1;e:do{const g=u.dep,p=g.flags;if(c.flags&16)f=!0;else if((p&17)===17){if(e(g)){const v=g.subs;v.nextSub!==void 0&&a(v),f=!0}}else if((p&33)===33){(u.nextSub!==void 0||u.prevSub!==void 0)&&(d={value:u,prev:d}),u=g.deps,c=g,++h;continue}if(!f){const v=u.nextDep;if(v!==void 0){u=v;continue}}for(;h--;){const v=c.subs,m=v.nextSub!==void 0;if(m?(u=d.value,d=d.prev):u=v,f){if(e(c)){m&&a(v),c=u.sub;continue}f=!1}else c.flags&=-33;c=u.sub;const S=u.nextDep;if(S!==void 0){u=S;continue e}}return f}while(!0)}function a(u){do{const c=u.sub,d=c.flags;(d&48)===32&&(c.flags=d|16,(d&6)===2&&t(c))}while((u=u.nextSub)!==void 0)}function l(u,c){let d=c.depsTail;for(;d!==void 0;){if(d===u)return!0;d=d.prevDep}return!1}}function ya(e,t,s){const n=typeof e=="object",r=n?e:void 0;return{next:(n?e.next:e)?.bind(r),error:(n?e.error:t)?.bind(r),complete:(n?e.complete:s)?.bind(r)}}var ws=[],Mt=0,{link:$n,unlink:Ca,propagate:Ra,checkDirty:Hr,shallowPropagate:Bn}=Sa({update(e){return e._update()},notify(e){ws[bs++]=e,e.flags&=~$.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=$.Mutable|$.Dirty,Ft(e))}}),mt=0,bs=0,ae,_s=0;function jr(e){try{++_s,e()}finally{--_s||zr()}}function Ft(e){const t=e.depsTail;let s=t!==void 0?t.nextDep:e.deps;for(;s!==void 0;)s=Ca(s,e)}function zr(){if(!(_s>0)){for(;mt<bs;){const e=ws[mt];ws[mt++]=void 0,e.notify()}mt=0,bs=0}}function Un(e,t){const s=typeof e=="function",n=e,r={_snapshot:s?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:s?$.None:$.Mutable,get(){return ae!==void 0&&$n(r,ae,Mt),r._snapshot},subscribe(o){const i=ya(o),a={current:!1},l=Ia(()=>{r.get(),a.current?i.next?.(r._snapshot):a.current=!0});return{unsubscribe:()=>{l.stop()}}},_update(o){const i=ae,a=t?.compare??Object.is;if(s)ae=r,++Mt,r.depsTail=void 0;else if(o===void 0)return!1;s&&(r.flags=$.Mutable|$.RecursedCheck);try{const l=r._snapshot,u=typeof o=="function"?o(l):o===void 0&&s?n(l):o;return l===void 0||!a(l,u)?(r._snapshot=u,!0):!1}finally{ae=i,s&&(r.flags&=~$.RecursedCheck),Ft(r)}}};return s?(r.flags=$.Mutable|$.Dirty,r.get=function(){const o=r.flags;if(o&$.Dirty||o&$.Pending&&Hr(r.deps,r)){if(r._update()){const i=r.subs;i!==void 0&&Bn(i)}}else o&$.Pending&&(r.flags=o&~$.Pending);return ae!==void 0&&$n(r,ae,Mt),r._snapshot}):r.set=function(o){if(r._update(o)){const i=r.subs;i!==void 0&&(Ra(i),Bn(i),zr())}},r}function Ia(e){const t=()=>{const n=ae;ae=s,++Mt,s.depsTail=void 0,s.flags=$.Watching|$.RecursedCheck;try{return e()}finally{ae=n,s.flags&=~$.RecursedCheck,Ft(s)}},s={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:$.Watching|$.RecursedCheck,notify(){const n=this.flags;n&$.Dirty||n&$.Pending&&Hr(this.deps,this)?t():this.flags=$.Watching},stop(){this.flags=$.None,this.depsTail=void 0,Ft(this)}};return t(),s}var wa=je((e=>{var t=Ds();function s(h,f){return h===f&&(h!==0||1/h===1/f)||h!==h&&f!==f}var n=typeof Object.is=="function"?Object.is:s,r=t.useState,o=t.useEffect,i=t.useLayoutEffect,a=t.useDebugValue;function l(h,f){var g=f(),p=r({inst:{value:g,getSnapshot:f}}),v=p[0].inst,m=p[1];return i(function(){v.value=g,v.getSnapshot=f,u(v)&&m({inst:v})},[h,g,f]),o(function(){return u(v)&&m({inst:v}),h(function(){u(v)&&m({inst:v})})},[h]),a(g),g}function u(h){var f=h.getSnapshot;h=h.value;try{var g=f();return!n(h,g)}catch{return!0}}function c(h,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:l;e.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d})),ba=je(((e,t)=>{t.exports=wa()})),_a=je((e=>{var t=Ds(),s=ba();function n(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=s.useSyncExternalStore,i=t.useRef,a=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(c,d,h,f,g){var p=i(null);if(p.current===null){var v={hasValue:!1,value:null};p.current=v}else v=p.current;p=l(function(){function S(b){if(!C){if(C=!0,I=b,b=f(b),g!==void 0&&v.hasValue){var _=v.value;if(g(_,b))return y=_}return y=b}if(_=y,r(I,b))return _;var M=f(b);return g!==void 0&&g(_,M)?(I=b,_):(I=b,y=M)}var C=!1,I,y,R=h===void 0?null:h;return[function(){return S(d())},R===null?void 0:function(){return S(R())}]},[d,h,f,g]);var m=o(c,p[0],p[1]);return a(function(){v.hasValue=!0,v.value=m},[m]),u(m),m}})),Ma=je(((e,t)=>{t.exports=_a()})),Ea=Ma();function xa(e,t){return e===t}function Q(e,t,s=xa){const n=(0,w.useCallback)(o=>{if(!e)return()=>{};const{unsubscribe:i}=e.subscribe(o);return i},[e]),r=(0,w.useCallback)(()=>e?.get(),[e]);return(0,Ea.useSyncExternalStoreWithSelector)(n,r,r,t,s)}var es={get(){},subscribe(){return{unsubscribe(){}}}};function qr(e,t){const s=w.useRef();return n=>{const r=e?.select?e.select(n):n;return e?.structuralSharing??t.options.defaultStructuralSharing?s.current=xe(s.current,r):r}}function Oe(e){const t=re(),s=w.useContext(e.from?va:$t),n=e.from?t.stores.getRouteMatchStore(e.from):t.stores.matchStores.get(s),r=qr(e,t),o=Q(n??es,i=>i?r(i):es);if(o!==es)return o;(e.shouldThrow??!0)&&de()}function Wr(e){return Oe({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function Kr(e){const{select:t,...s}=e;return Oe({...s,select:n=>t?t(n.loaderDeps):n.loaderDeps})}function Qr(e){return Oe({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const s=e.strict===!1?t.params:t._strictParams;return e.select?e.select(s):s}})}function Jr(e){return Oe({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function Xr(e){const t=re();return w.useCallback(s=>t.navigate({...s,from:s.from??e?.from}),[e?.from,t])}function Yr(e){return Oe({...e,select:t=>e.select?e.select(t.context):t.context})}var Zr=pr(Eo(),1);function Pa(e,t){const s=re(),n=hi(t),r=!1,{activeProps:o,inactiveProps:i,activeOptions:a,to:l,preload:u,preloadDelay:c,preloadIntentProximity:d,hashScrollIntoView:h,replace:f,startTransition:g,resetScroll:p,viewTransition:v,children:m,target:S,disabled:C,style:I,className:y,onClick:R,onBlur:b,onFocus:_,onMouseEnter:M,onMouseLeave:P,onTouchStart:E,ignoreBlocker:O,params:se,search:H,hash:j,state:Z,mask:F,reloadDocument:L,unsafeRelative:B,from:N,_fromLocation:he,...fe}=e;if(r){const k=zn(l);if(typeof l=="string"&&!k&&l.indexOf(":")>-1)try{return new URL(l),Me(l,s.protocolAllowlist)?{...fe,ref:n,href:void 0,...m&&{children:m},...S&&{target:S},...C&&{disabled:C},...I&&{style:I},...y&&{className:y}}:{...fe,ref:n,href:l,...m&&{children:m},...S&&{target:S},...C&&{disabled:C},...I&&{style:I},...y&&{className:y}}}catch{}const D=s.buildLocation({...e,from:e.from}),ne=jn(D.maskedLocation?D.maskedLocation.publicHref:D.publicHref,D.maskedLocation?D.maskedLocation.external:D.external,s.history,C),Qe=(()=>{if(ne?.external)return Me(ne.href,s.protocolAllowlist)?void 0:ne.href;if(!k&&typeof l=="string"&&l.indexOf(":")>-1)try{return new URL(l),Me(l,s.protocolAllowlist)?void 0:l}catch{}})(),jt=(()=>{if(Qe)return!1;const V=s.stores.location.get(),J=a?.exact??!1;if(J){if(!bn(V.pathname,D.pathname,s.basepath))return!1}else{const G=Ve(V.pathname,s.basepath),X=Ve(D.pathname,s.basepath);if(!(G.startsWith(X)&&(G.length===X.length||G[X.length]==="/")))return!1}if((a?.includeSearch??!0)&&V.search!==D.search){const G=!V.search||typeof V.search=="object"&&!Tt(V.search),X=!D.search||typeof D.search=="object"&&!Tt(D.search);if(!(G&&X)&&!Ce(V.search,D.search,{partial:!J,ignoreUndefined:!a?.explicitUndefined}))return!1}return!a?.includeHash})();if(Qe)return{...fe,ref:n,href:Qe,...m&&{children:m},...S&&{target:S},...C&&{disabled:C},...I&&{style:I},...y&&{className:y}};const zt=jt?ue(o,{})??Vn:Fe,qt=jt?Fe:ue(i,{})??Fe,rn=(()=>{const V=I,J=zt.style,G=qt.style;if(!(!V&&!J&&!G))return V&&!J&&!G?V:!V&&J&&!G?J:!V&&!J&&G?G:{...V,...J,...G}})(),on=(()=>{const V=y,J=zt.className,G=qt.className;if(!V&&!J&&!G)return"";let X="";return V&&(X=V),J&&(X=X?`${X} ${J}`:J),G&&(X=X?`${X} ${G}`:G),X})();return{...fe,...zt,...qt,href:ne?.href,ref:n,disabled:!!C,target:S,...rn&&{style:rn},...on&&{className:on},...C&&Gn,...jt&&Hn}}const Vt=Vr(),qe=w.useMemo(()=>e,[s,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),we=Q(s.stores.location,k=>k,(k,D)=>k.href===D.href),W=w.useMemo(()=>{const k={_fromLocation:we,...qe};return s.buildLocation(k)},[s,we,qe]),Js=W.maskedLocation?W.maskedLocation.publicHref:W.publicHref,Xs=W.maskedLocation?W.maskedLocation.external:W.external,We=w.useMemo(()=>jn(Js,Xs,s.history,C),[C,Xs,Js,s.history]),Ke=w.useMemo(()=>{if(We?.external)return Me(We.href,s.protocolAllowlist)?void 0:We.href;if(!zn(l)&&!(typeof l!="string"||l.indexOf(":")===-1))try{return new URL(l),Me(l,s.protocolAllowlist)?void 0:l}catch{}},[l,We,s.protocolAllowlist]),Gt=w.useMemo(()=>{if(Ke)return!1;if(a?.exact){if(!bn(we.pathname,W.pathname,s.basepath))return!1}else{const k=Ve(we.pathname,s.basepath),D=Ve(W.pathname,s.basepath);if(!(k.startsWith(D)&&(k.length===D.length||k[D.length]==="/")))return!1}return(a?.includeSearch??!0)&&!Ce(we.search,W.search,{partial:!a?.exact,ignoreUndefined:!a?.explicitUndefined})?!1:a?.includeHash?Vt&&we.hash===W.hash:!0},[a?.exact,a?.explicitUndefined,a?.includeHash,a?.includeSearch,we,Ke,Vt,W.hash,W.pathname,W.search,s.basepath]),ct=Gt?ue(o,{})??Vn:Fe,dt=Gt?Fe:ue(i,{})??Fe,Ys=[y,ct.className,dt.className].filter(Boolean).join(" "),Zs=(I||ct.style||dt.style)&&{...I,...ct.style,...dt.style},[bo,en]=w.useState(!1),tn=w.useRef(!1),Le=e.reloadDocument||Ke?!1:u??s.options.defaultPreload,Ht=c??s.options.defaultPreloadDelay??0,be=w.useCallback(()=>{s.preloadRoute({...qe,_builtLocation:W}).catch(k=>{console.warn(k),console.warn(ha)})},[s,qe,W]);di(n,w.useCallback(k=>{k?.isIntersecting&&be()},[be]),Aa,{disabled:!!C||Le!=="viewport"}),w.useEffect(()=>{tn.current||!C&&Le==="render"&&(be(),tn.current=!0)},[C,be,Le]);const _o=k=>{const D=k.currentTarget.getAttribute("target"),ne=S!==void 0?S:D;if(!C&&!Oa(k)&&!k.defaultPrevented&&(!ne||ne==="_self")&&k.button===0){k.preventDefault(),(0,Zr.flushSync)(()=>{en(!0)});const Qe=s.subscribe("onResolved",()=>{Qe(),en(!1)});s.navigate({...qe,replace:f,resetScroll:p,hashScrollIntoView:h,startTransition:g,viewTransition:v,ignoreBlocker:O})}};if(Ke)return{...fe,ref:n,href:Ke,...m&&{children:m},...S&&{target:S},...C&&{disabled:C},...I&&{style:I},...y&&{className:y},...R&&{onClick:R},...b&&{onBlur:b},..._&&{onFocus:_},...M&&{onMouseEnter:M},...P&&{onMouseLeave:P},...E&&{onTouchStart:E}};const sn=k=>{if(C||Le!=="intent")return;if(!Ht){be();return}const D=k.currentTarget;if(Ye.has(D))return;const ne=setTimeout(()=>{Ye.delete(D),be()},Ht);Ye.set(D,ne)},Mo=k=>{C||Le!=="intent"||be()},nn=k=>{if(C||!Le||!Ht)return;const D=k.currentTarget,ne=Ye.get(D);ne&&(clearTimeout(ne),Ye.delete(D))};return{...fe,...ct,...dt,href:We?.href,ref:n,onClick:Ne([R,_o]),onBlur:Ne([b,nn]),onFocus:Ne([_,sn]),onMouseEnter:Ne([M,sn]),onMouseLeave:Ne([P,nn]),onTouchStart:Ne([E,Mo]),disabled:!!C,target:S,...Zs&&{style:Zs},...Ys&&{className:Ys},...C&&Gn,...Gt&&Hn,...Vt&&bo&&Ta}}var Fe={},Vn={className:"active"},Gn={role:"link","aria-disabled":!0},Hn={"data-status":"active","aria-current":"page"},Ta={"data-transitioning":"transitioning"},Ye=new WeakMap,Aa={rootMargin:"100px"},Ne=e=>t=>{for(const s of e)if(s){if(t.defaultPrevented)return;s(t)}};function jn(e,t,s,n){if(!n)return t?{href:e,external:!0}:{href:s.createHref(e)||"/",external:!1}}function zn(e){if(typeof e!="string")return!1;const t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var eo=w.forwardRef((e,t)=>{const{_asChild:s,...n}=e,{type:r,...o}=Pa(n,t),i=typeof n.children=="function"?n.children({isActive:o["data-status"]==="active"}):n.children;if(!s){const{disabled:a,...l}=o;return w.createElement("a",l,i)}return w.createElement(s,o,i)});function Oa(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var La=class extends Ur{constructor(e){super(e),this.useMatch=t=>Oe({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>Yr({...t,from:this.id}),this.useSearch=t=>Jr({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>Qr({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>Kr({...t,from:this.id}),this.useLoaderData=t=>Wr({...t,from:this.id}),this.useNavigate=()=>Xr({from:this.fullPath}),this.Link=w.forwardRef((t,s)=>(0,x.jsx)(eo,{ref:s,from:this.fullPath,...t}))}};function Fa(e){return new La(e)}var Na=class extends fa{constructor(e){super(e),this.useMatch=t=>Oe({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>Yr({...t,from:this.id}),this.useSearch=t=>Jr({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>Qr({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>Kr({...t,from:this.id}),this.useLoaderData=t=>Wr({...t,from:this.id}),this.useNavigate=()=>Xr({from:this.fullPath}),this.Link=w.forwardRef((t,s)=>(0,x.jsx)(eo,{ref:s,from:this.fullPath,...t}))}};function Cc(e){return new Na(e)}function Rc(e){return new Da(e,{silent:!0}).createRoute}var Da=class{constructor(e,t){this.path=e,this.createRoute=s=>{const n=Fa(s);return n.isRoot=!1,n},this.silent=t?.silent}};function Ic(e,t){let s,n,r,o;const i=()=>(s||(s=e().then(l=>{s=void 0,n=l[t??"default"]}).catch(l=>{if(r=l,pi(r)&&r instanceof Error&&typeof window<"u"&&typeof sessionStorage<"u"){const u=`tanstack_router_reload:${r.message}`;sessionStorage.getItem(u)||(sessionStorage.setItem(u,"1"),o=!0)}})),s),a=function(u){if(o)throw window.location.reload(),new Promise(()=>{});if(r)throw r;if(!n)if(vn)vn(i());else throw i();return w.createElement(n,u)};return a.preload=i,a}function ka(e){const t=re(),s=`not-found-${Q(t.stores.location,n=>n.pathname)}-${Q(t.stores.status,n=>n)}`;return(0,x.jsx)(zs,{getResetKey:()=>s,onCatch:(n,r)=>{if(q(n))e.onCatch?.(n,r);else throw n},errorComponent:({error:n})=>{if(q(n))return e.fallback?.(n);throw n},children:e.children})}function $a(){return(0,x.jsx)("p",{children:"Not Found"})}function Ue(e){return(0,x.jsx)(x.Fragment,{children:e.children})}function to(e,t,s){return t.options.notFoundComponent?(0,x.jsx)(t.options.notFoundComponent,{...s}):e.options.defaultNotFoundComponent?(0,x.jsx)(e.options.defaultNotFoundComponent,{...s}):(0,x.jsx)($a,{})}var Ba=(e,t)=>e.routeId===t.routeId&&e._displayPending===t._displayPending,Ua=(e,t)=>e[0]===t[0]&&e[1]===t[1],so=w.memo(function({matchId:t}){const s=re(),n=s.stores.matchStores.get(t);n||de();const r=Q(s.stores.loadedAt,i=>i),o=Q(n,i=>i,Ba);return(0,x.jsx)(Va,{router:s,matchId:t,resetKey:r,matchState:w.useMemo(()=>{const i=o.routeId,a=s.routesById[i].parentRoute?.id;return{routeId:i,ssr:o.ssr,_displayPending:o._displayPending,parentRouteId:a}},[o._displayPending,o.routeId,o.ssr,s.routesById])})});function Va({router:e,matchId:t,resetKey:s,matchState:n}){const r=e.routesById[n.routeId],o=r.options.pendingComponent??e.options.defaultPendingComponent,i=o?(0,x.jsx)(o,{}):null,a=r.options.errorComponent??e.options.defaultErrorComponent,l=r.options.onCatch??e.options.defaultOnCatch,u=r.isRoot?r.options.notFoundComponent??e.options.notFoundRoute?.options.component:r.options.notFoundComponent,c=n.ssr===!1||n.ssr==="data-only",d=(!r.isRoot||r.options.wrapInSuspense||c)&&(r.options.wrapInSuspense??o??(r.options.errorComponent?.preload||c))?w.Suspense:Ue,h=a?zs:Ue,f=u?ka:Ue;return(0,x.jsxs)(r.isRoot?r.options.shellComponent??Ue:Ue,{children:[(0,x.jsx)($t.Provider,{value:t,children:(0,x.jsx)(d,{fallback:i,children:(0,x.jsx)(h,{getResetKey:()=>s,errorComponent:a||qs,onCatch:(g,p)=>{if(q(g))throw g.routeId??=n.routeId,g;l?.(g,p)},children:(0,x.jsx)(f,{fallback:g=>{if(g.routeId??=n.routeId,!u||g.routeId&&g.routeId!==n.routeId||!g.routeId&&!r.isRoot)throw g;return w.createElement(u,g)},children:c||n._displayPending?(0,x.jsx)(pa,{fallback:i,children:(0,x.jsx)(qn,{matchId:t})}):(0,x.jsx)(qn,{matchId:t})})})})}),n.parentRouteId==="__root__"?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Ga,{}),(e.options.scrollRestoration,null)]}):null]})}function Ga(){const e=re(),t=w.useRef();return et(()=>{const s=e.stores.resolvedLocation.get(),n=t.current;s&&(!n||n.href!==s.href)&&e.emit({type:"onRendered",...Ge(e.stores.location.get(),n??s)}),t.current=s},[Q(e.stores.resolvedLocation,s=>s?.state.__TSR_key),e]),null}var qn=w.memo(function({matchId:t}){const s=re(),n=(c,d)=>s.getMatch(c.id)?._nonReactive[d]??c._nonReactive[d],r=s.stores.matchStores.get(t);r||de();const o=Q(r,c=>c),i=o.routeId,a=s.routesById[i],l=w.useMemo(()=>{const c=(s.routesById[i].options.remountDeps??s.options.defaultRemountDeps)?.({routeId:i,loaderDeps:o.loaderDeps,params:o._strictParams,search:o._strictSearch});return c?JSON.stringify(c):void 0},[i,o.loaderDeps,o._strictParams,o._strictSearch,s.options.defaultRemountDeps,s.routesById]),u=w.useMemo(()=>{const c=a.options.component??s.options.defaultComponent;return c?(0,x.jsx)(c,{},l):(0,x.jsx)(Ha,{})},[l,a.options.component,s.options.defaultComponent]);if(o._displayPending)throw n(o,"displayPendingPromise");if(o._forcePending)throw n(o,"minPendingPromise");if(o.status==="pending"){const c=a.options.pendingMinMs??s.options.defaultPendingMinMs;if(c){const d=s.getMatch(o.id);if(d&&!d._nonReactive.minPendingPromise){const h=He();d._nonReactive.minPendingPromise=h,setTimeout(()=>{h.resolve(),d._nonReactive.minPendingPromise=void 0},c)}}throw n(o,"loadPromise")}if(o.status==="notFound")return q(o.error)||de(),to(s,a,o.error);if(o.status==="redirected")throw Y(o.error)||de(),n(o,"loadPromise");if(o.status==="error")throw o.error;return u}),Ha=w.memo(function(){const t=re(),s=w.useContext($t);let n,r=!1,o;{const u=s?t.stores.matchStores.get(s):void 0;[n,r]=Q(u,c=>[c?.routeId,c?.globalNotFound??!1],Ua),o=Q(t.stores.matchesId,c=>c[c.findIndex(d=>d===s)+1])}const i=n?t.routesById[n]:void 0,a=t.options.defaultPendingComponent?(0,x.jsx)(t.options.defaultPendingComponent,{}):null;if(r)return i||de(),to(t,i,void 0);if(!o)return null;const l=(0,x.jsx)(so,{matchId:o});return n==="__root__"?(0,x.jsx)(w.Suspense,{fallback:a,children:l}):l});function ja(){const e=re(),t=w.useRef({router:e,mounted:!1}),[s,n]=w.useState(!1),r=Q(e.stores.isLoading,d=>d),o=Q(e.stores.hasPending,d=>d),i=Wt(r),a=r||s||o,l=Wt(a),u=r||o,c=Wt(u);return e.startTransition=d=>{n(!0),w.startTransition(()=>{d(),n(!1)})},w.useEffect(()=>{const d=e.history.subscribe(e.load),h=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return ce(e.latestLocation.publicHref)!==ce(h.publicHref)&&e.commitLocation({...h,replace:!0}),()=>{d()}},[e,e.history]),et(()=>{if(typeof window<"u"&&e.ssr||t.current.router===e&&t.current.mounted)return;t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(h){console.error(h)}})()},[e]),et(()=>{i&&!r&&e.emit({type:"onLoad",...Ge(e.stores.location.get(),e.stores.resolvedLocation.get())})},[i,e,r]),et(()=>{c&&!u&&e.emit({type:"onBeforeRouteMount",...Ge(e.stores.location.get(),e.stores.resolvedLocation.get())})},[u,c,e]),et(()=>{if(l&&!a){const d=Ge(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:"onResolved",...d}),jr(()=>{e.stores.status.set("idle"),e.stores.resolvedLocation.set(e.stores.location.get())})}},[a,l,e]),null}function za(){const e=re(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,s=t?(0,x.jsx)(t,{}):null,n=(0,x.jsxs)(typeof document<"u"&&e.ssr?Ue:w.Suspense,{fallback:s,children:[(0,x.jsx)(ja,{}),(0,x.jsx)(qa,{})]});return e.options.InnerWrap?(0,x.jsx)(e.options.InnerWrap,{children:n}):n}function qa(){const e=re(),t=!1,s=t?e.stores.firstId.get():Q(e.stores.firstId,o=>o),n=t?e.stores.loadedAt.get():Q(e.stores.loadedAt,o=>o),r=s?(0,x.jsx)(so,{matchId:s}):null;return(0,x.jsx)($t.Provider,{value:s,children:e.options.disableGlobalCatchBoundary?r:(0,x.jsx)(zs,{getResetKey:()=>n,errorComponent:qs,onCatch:void 0,children:r})})}var Wa=e=>({createMutableStore:Un,createReadonlyStore:Un,batch:jr}),wc=e=>new Ka(e),Ka=class extends Yi{constructor(e){super(e,Wa)}};function Qa({router:e,children:t,...s}){Tt(s)&&e.update({...e.options,...s,context:{...e.options.context,...s.context}});const n=(0,x.jsx)(Gr.Provider,{value:e,children:t});return e.options.Wrap?(0,x.jsx)(e.options.Wrap,{children:n}):n}function bc({router:e,...t}){return(0,x.jsx)(Qa,{router:e,...t,children:(0,x.jsx)(za,{})})}function _c(e){const t=re();return Q(t.stores.location,qr(e,t))}function ve(e,t){return typeof e=="function"?e(t):e}function te(e,t){return s=>{t.setState(n=>({...n,[e]:ve(s,n[e])}))}}function Bt(e){return e instanceof Function}function Ja(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Xa(e,t){const s=[],n=r=>{r.forEach(o=>{s.push(o);const i=t(o);i!=null&&i.length&&n(i)})};return n(e),s}function T(e,t,s){let n=[],r;return o=>{let i;s.key&&s.debug&&(i=Date.now());const a=e(o);if(!(a.length!==n.length||a.some((u,c)=>n[c]!==u)))return r;n=a;let l;if(s.key&&s.debug&&(l=Date.now()),r=t(...a),s==null||s.onChange==null||s.onChange(r),s.key&&s.debug&&s!=null&&s.debug()){const u=Math.round((Date.now()-i)*100)/100,c=Math.round((Date.now()-l)*100)/100,d=c/16,h=(f,g)=>{for(f=String(f);f.length<g;)f=" "+f;return f};console.info(`%c⏱ ${h(c,5)} /${h(u,5)} ms`,`
|
|
2
2
|
font-size: .6rem;
|
|
3
3
|
font-weight: bold;
|
|
4
|
-
color: hsl(${Math.max(0,Math.min(120-120*c,120))}deg 100% 31%);`,s?.key)}return r}}function A(e,t,s,n){return{debug:()=>{var r;return(r=e?.debugAll)!=null?r:e[t]},key:!1,onChange:n}}function Ya(e,t,s,n){const r=()=>{var o;return(o=i.getValue())!=null?o:e.options.renderFallbackValue},i={id:`${t.id}_${s.id}`,row:t,column:s,getValue:()=>t.getValue(n),renderValue:r,getContext:T(()=>[e,s,t,i],(o,a,l,u)=>({table:o,column:a,row:l,cell:u,getValue:u.getValue,renderValue:u.renderValue}),A(e.options,"debugCells","cell.getContext"))};return e._features.forEach(o=>{o.createCell==null||o.createCell(i,s,t,e)},{}),i}function Za(e,t,s,n){var r,i;const o={...e._getDefaultColumnDef(),...t},a=o.accessorKey;let l=(r=(i=o.id)!=null?i:a?typeof String.prototype.replaceAll=="function"?a.replaceAll(".","_"):a.replace(/\./g,"_"):void 0)!=null?r:typeof o.header=="string"?o.header:void 0,u;if(o.accessorFn?u=o.accessorFn:a&&(a.includes(".")?u=c=>{let h=c;for(const g of a.split(".")){var f;h=(f=h)==null?void 0:f[g]}return h}:u=c=>c[o.accessorKey]),!l)throw new Error;let d={id:`${String(l)}`,accessorFn:u,parent:n,depth:s,columnDef:o,columns:[],getFlatColumns:T(()=>[!0],()=>{var c;return[d,...(c=d.columns)==null?void 0:c.flatMap(h=>h.getFlatColumns())]},A(e.options,"debugColumns","column.getFlatColumns")),getLeafColumns:T(()=>[e._getOrderColumnsFn()],c=>{var h;return(h=d.columns)!=null&&h.length?c(d.columns.flatMap(f=>f.getLeafColumns())):[d]},A(e.options,"debugColumns","column.getLeafColumns"))};for(const c of e._features)c.createColumn==null||c.createColumn(d,e);return d}var z="debugHeaders";function Wn(e,t,s){var n;let r={id:(n=s.id)!=null?n:t.id,column:t,index:s.index,isPlaceholder:!!s.isPlaceholder,placeholderId:s.placeholderId,depth:s.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],o=a=>{a.subHeaders&&a.subHeaders.length&&a.subHeaders.map(o),i.push(a)};return o(r),i},getContext:()=>({table:e,header:r,column:t})};return e._features.forEach(i=>{i.createHeader==null||i.createHeader(r,e)}),r}var el={createTable:e=>{e.getHeaderGroups=T(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n,r)=>{var i,o;const a=(i=n?.map(d=>s.find(c=>c.id===d)).filter(Boolean))!=null?i:[],l=(o=r?.map(d=>s.find(c=>c.id===d)).filter(Boolean))!=null?o:[],u=s.filter(d=>!(n!=null&&n.includes(d.id))&&!(r!=null&&r.includes(d.id)));return vt(t,[...a,...u,...l],e)},A(e.options,z,"getHeaderGroups")),e.getCenterHeaderGroups=T(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n,r)=>(s=s.filter(i=>!(n!=null&&n.includes(i.id))&&!(r!=null&&r.includes(i.id))),vt(t,s,e,"center")),A(e.options,z,"getCenterHeaderGroups")),e.getLeftHeaderGroups=T(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,s,n)=>{var r;return vt(t,(r=n?.map(i=>s.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"left")},A(e.options,z,"getLeftHeaderGroups")),e.getRightHeaderGroups=T(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,s,n)=>{var r;return vt(t,(r=n?.map(i=>s.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"right")},A(e.options,z,"getRightHeaderGroups")),e.getFooterGroups=T(()=>[e.getHeaderGroups()],t=>[...t].reverse(),A(e.options,z,"getFooterGroups")),e.getLeftFooterGroups=T(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),A(e.options,z,"getLeftFooterGroups")),e.getCenterFooterGroups=T(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),A(e.options,z,"getCenterFooterGroups")),e.getRightFooterGroups=T(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),A(e.options,z,"getRightFooterGroups")),e.getFlatHeaders=T(()=>[e.getHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,z,"getFlatHeaders")),e.getLeftFlatHeaders=T(()=>[e.getLeftHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,z,"getLeftFlatHeaders")),e.getCenterFlatHeaders=T(()=>[e.getCenterHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,z,"getCenterFlatHeaders")),e.getRightFlatHeaders=T(()=>[e.getRightHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,z,"getRightFlatHeaders")),e.getCenterLeafHeaders=T(()=>[e.getCenterFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),A(e.options,z,"getCenterLeafHeaders")),e.getLeftLeafHeaders=T(()=>[e.getLeftFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),A(e.options,z,"getLeftLeafHeaders")),e.getRightLeafHeaders=T(()=>[e.getRightFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),A(e.options,z,"getRightLeafHeaders")),e.getLeafHeaders=T(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,s,n)=>{var r,i,o,a,l,u;return[...(r=(i=t[0])==null?void 0:i.headers)!=null?r:[],...(o=(a=s[0])==null?void 0:a.headers)!=null?o:[],...(l=(u=n[0])==null?void 0:u.headers)!=null?l:[]].map(d=>d.getLeafHeaders()).flat()},A(e.options,z,"getLeafHeaders"))}};function vt(e,t,s,n){var r,i;let o=0;const a=function(c,h){h===void 0&&(h=1),o=Math.max(o,h),c.filter(f=>f.getIsVisible()).forEach(f=>{var g;(g=f.columns)!=null&&g.length&&a(f.columns,h+1)},0)};a(e);let l=[];const u=(c,h)=>{const f={depth:h,id:[n,`${h}`].filter(Boolean).join("_"),headers:[]},g=[];c.forEach(p=>{const v=[...g].reverse()[0],m=p.column.depth===f.depth;let S,C=!1;if(m&&p.column.parent?S=p.column.parent:(S=p.column,C=!0),v&&v?.column===S)v.subHeaders.push(p);else{const I=Wn(s,S,{id:[n,h,S.id,p?.id].filter(Boolean).join("_"),isPlaceholder:C,placeholderId:C?`${g.filter(y=>y.column===S).length}`:void 0,depth:h,index:g.length});I.subHeaders.push(p),g.push(I)}f.headers.push(p),p.headerGroup=f}),l.push(f),h>0&&u(g,h-1)};u(t.map((c,h)=>Wn(s,c,{depth:o,index:h})),o-1),l.reverse();const d=c=>c.filter(h=>h.column.getIsVisible()).map(h=>{let f=0,g=0,p=[0];h.subHeaders&&h.subHeaders.length?(p=[],d(h.subHeaders).forEach(m=>{let{colSpan:S,rowSpan:C}=m;f+=S,p.push(C)})):f=1;const v=Math.min(...p);return g=g+v,h.colSpan=f,h.rowSpan=g,{colSpan:f,rowSpan:g}});return d((r=(i=l[0])==null?void 0:i.headers)!=null?r:[]),l}var tl=(e,t,s,n,r,i,o)=>{let a={id:t,index:n,original:s,depth:r,parentId:o,_valuesCache:{},_uniqueValuesCache:{},getValue:l=>{if(a._valuesCache.hasOwnProperty(l))return a._valuesCache[l];const u=e.getColumn(l);if(u!=null&&u.accessorFn)return a._valuesCache[l]=u.accessorFn(a.original,n),a._valuesCache[l]},getUniqueValues:l=>{if(a._uniqueValuesCache.hasOwnProperty(l))return a._uniqueValuesCache[l];const u=e.getColumn(l);if(u!=null&&u.accessorFn)return u.columnDef.getUniqueValues?(a._uniqueValuesCache[l]=u.columnDef.getUniqueValues(a.original,n),a._uniqueValuesCache[l]):(a._uniqueValuesCache[l]=[a.getValue(l)],a._uniqueValuesCache[l])},renderValue:l=>{var u;return(u=a.getValue(l))!=null?u:e.options.renderFallbackValue},subRows:i??[],getLeafRows:()=>Xa(a.subRows,l=>l.subRows),getParentRow:()=>a.parentId?e.getRow(a.parentId,!0):void 0,getParentRows:()=>{let l=[],u=a;for(;;){const d=u.getParentRow();if(!d)break;l.push(d),u=d}return l.reverse()},getAllCells:T(()=>[e.getAllLeafColumns()],l=>l.map(u=>Ya(e,a,u,u.id)),A(e.options,"debugRows","getAllCells")),_getAllCellsByColumnId:T(()=>[a.getAllCells()],l=>l.reduce((u,d)=>(u[d.column.id]=d,u),{}),A(e.options,"debugRows","getAllCellsByColumnId"))};for(let l=0;l<e._features.length;l++){const u=e._features[l];u==null||u.createRow==null||u.createRow(a,e)}return a},sl={createColumn:(e,t)=>{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},ni=(e,t,s)=>{var n,r;const i=s==null||(n=s.toString())==null?void 0:n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(i))};ni.autoRemove=e=>ie(e);var ri=(e,t,s)=>{var n;return!!(!((n=e.getValue(t))==null||(n=n.toString())==null)&&n.includes(s))};ri.autoRemove=e=>ie(e);var ii=(e,t,s)=>{var n;return((n=e.getValue(t))==null||(n=n.toString())==null?void 0:n.toLowerCase())===s?.toLowerCase()};ii.autoRemove=e=>ie(e);var oi=(e,t,s)=>{var n;return(n=e.getValue(t))==null?void 0:n.includes(s)};oi.autoRemove=e=>ie(e);var ai=(e,t,s)=>!s.some(n=>{var r;return!((r=e.getValue(t))!=null&&r.includes(n))});ai.autoRemove=e=>ie(e)||!(e!=null&&e.length);var li=(e,t,s)=>s.some(n=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)});li.autoRemove=e=>ie(e)||!(e!=null&&e.length);var ui=(e,t,s)=>e.getValue(t)===s;ui.autoRemove=e=>ie(e);var ci=(e,t,s)=>e.getValue(t)==s;ci.autoRemove=e=>ie(e);var Ws=(e,t,s)=>{let[n,r]=s;const i=e.getValue(t);return i>=n&&i<=r};Ws.resolveFilterValue=e=>{let[t,s]=e,n=typeof t!="number"?parseFloat(t):t,r=typeof s!="number"?parseFloat(s):s,i=t===null||Number.isNaN(n)?-1/0:n,o=s===null||Number.isNaN(r)?1/0:r;if(i>o){const a=i;i=o,o=a}return[i,o]};Ws.autoRemove=e=>ie(e)||ie(e[0])&&ie(e[1]);var le={includesString:ni,includesStringSensitive:ri,equalsString:ii,arrIncludes:oi,arrIncludesAll:ai,arrIncludesSome:li,equals:ui,weakEquals:ci,inNumberRange:Ws};function ie(e){return e==null||e===""}var nl={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:te("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const s=t.getCoreRowModel().flatRows[0],n=s?.getValue(e.id);return typeof n=="string"?le.includesString:typeof n=="number"?le.inNumberRange:typeof n=="boolean"||n!==null&&typeof n=="object"?le.equals:Array.isArray(n)?le.arrIncludes:le.weakEquals},e.getFilterFn=()=>{var s,n;return Bt(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(s=(n=t.options.filterFns)==null?void 0:n[e.columnDef.filterFn])!=null?s:le[e.columnDef.filterFn]},e.getCanFilter=()=>{var s,n,r;return((s=e.columnDef.enableColumnFilter)!=null?s:!0)&&((n=t.options.enableColumnFilters)!=null?n:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var s;return(s=t.getState().columnFilters)==null||(s=s.find(n=>n.id===e.id))==null?void 0:s.value},e.getFilterIndex=()=>{var s,n;return(s=(n=t.getState().columnFilters)==null?void 0:n.findIndex(r=>r.id===e.id))!=null?s:-1},e.setFilterValue=s=>{t.setColumnFilters(n=>{const r=e.getFilterFn(),i=n?.find(d=>d.id===e.id),o=ve(s,i?i.value:void 0);if(Kn(r,o,e)){var a;return(a=n?.filter(d=>d.id!==e.id))!=null?a:[]}const l={id:e.id,value:o};if(i){var u;return(u=n?.map(d=>d.id===e.id?l:d))!=null?u:[]}return n!=null&&n.length?[...n,l]:[l]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const s=e.getAllLeafColumns(),n=r=>{var i;return(i=ve(t,r))==null?void 0:i.filter(o=>{const a=s.find(l=>l.id===o.id);return!(a&&Kn(a.getFilterFn(),o.value,a))})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(n)},e.resetColumnFilters=t=>{var s,n;e.setColumnFilters(t?[]:(s=(n=e.initialState)==null?void 0:n.columnFilters)!=null?s:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function Kn(e,t,s){return(e&&e.autoRemove?e.autoRemove(t,s):!1)||typeof t>"u"||typeof t=="string"&&!t}var rl=(e,t,s)=>s.reduce((n,r)=>{const i=r.getValue(e);return n+(typeof i=="number"?i:0)},0),il=(e,t,s)=>{let n;return s.forEach(r=>{const i=r.getValue(e);i!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}),n},ol=(e,t,s)=>{let n;return s.forEach(r=>{const i=r.getValue(e);i!=null&&(n<i||n===void 0&&i>=i)&&(n=i)}),n},al=(e,t,s)=>{let n,r;return s.forEach(i=>{const o=i.getValue(e);o!=null&&(n===void 0?o>=o&&(n=r=o):(n>o&&(n=o),r<o&&(r=o)))}),[n,r]},ll=(e,t)=>{let s=0,n=0;if(t.forEach(r=>{let i=r.getValue(e);i!=null&&(i=+i)>=i&&(++s,n+=i)}),s)return n/s},ul=(e,t)=>{if(!t.length)return;const s=t.map(i=>i.getValue(e));if(!Ja(s))return;if(s.length===1)return s[0];const n=Math.floor(s.length/2),r=s.sort((i,o)=>i-o);return s.length%2!==0?r[n]:(r[n-1]+r[n])/2},cl=(e,t)=>Array.from(new Set(t.map(s=>s.getValue(e))).values()),dl=(e,t)=>new Set(t.map(s=>s.getValue(e))).size,hl=(e,t)=>t.length,ts={sum:rl,min:il,max:ol,extent:al,mean:ll,median:ul,unique:cl,uniqueCount:dl,count:hl},fl={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,s;return(t=(s=e.getValue())==null||s.toString==null?void 0:s.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:te("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(s=>s!=null&&s.includes(e.id)?s.filter(n=>n!==e.id):[...s??[],e.id])},e.getCanGroup=()=>{var s,n;return((s=e.columnDef.enableGrouping)!=null?s:!0)&&((n=t.options.enableGrouping)!=null?n:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var s;return(s=t.getState().grouping)==null?void 0:s.includes(e.id)},e.getGroupedIndex=()=>{var s;return(s=t.getState().grouping)==null?void 0:s.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const s=e.getCanGroup();return()=>{s&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const s=t.getCoreRowModel().flatRows[0],n=s?.getValue(e.id);if(typeof n=="number")return ts.sum;if(Object.prototype.toString.call(n)==="[object Date]")return ts.extent},e.getAggregationFn=()=>{var s,n;if(!e)throw new Error;return Bt(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(s=(n=t.options.aggregationFns)==null?void 0:n[e.columnDef.aggregationFn])!=null?s:ts[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var s,n;e.setGrouping(t?[]:(s=(n=e.initialState)==null?void 0:n.grouping)!=null?s:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=s=>{if(e._groupingValuesCache.hasOwnProperty(s))return e._groupingValuesCache[s];const n=t.getColumn(s);return n!=null&&n.columnDef.getGroupingValue?(e._groupingValuesCache[s]=n.columnDef.getGroupingValue(e.original),e._groupingValuesCache[s]):e.getValue(s)},e._groupingValuesCache={}},createCell:(e,t,s,n)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===s.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var r;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((r=s.subRows)!=null&&r.length)}}};function gl(e,t,s){if(!(t!=null&&t.length)||!s)return e;const n=e.filter(r=>!t.includes(r.id));return s==="remove"?n:[...t.map(r=>e.find(i=>i.id===r)).filter(Boolean),...n]}var pl={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:te("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=T(s=>[tt(t,s)],s=>s.findIndex(n=>n.id===e.id),A(t.options,"debugColumns","getIndex")),e.getIsFirstColumn=s=>{var n;return((n=tt(t,s)[0])==null?void 0:n.id)===e.id},e.getIsLastColumn=s=>{var n;const r=tt(t,s);return((n=r[r.length-1])==null?void 0:n.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var s;e.setColumnOrder(t?[]:(s=e.initialState.columnOrder)!=null?s:[])},e._getOrderColumnsFn=T(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,s,n)=>r=>{let i=[];if(!(t!=null&&t.length))i=r;else{const o=[...t],a=[...r];for(;a.length&&o.length;){const l=o.shift(),u=a.findIndex(d=>d.id===l);u>-1&&i.push(a.splice(u,1)[0])}i=[...i,...a]}return gl(i,s,n)},A(e.options,"debugTable","_getOrderColumnsFn"))}},ss=()=>({left:[],right:[]}),ml={getInitialState:e=>({columnPinning:ss(),...e}),getDefaultOptions:e=>({onColumnPinningChange:te("columnPinning",e)}),createColumn:(e,t)=>{e.pin=s=>{const n=e.getLeafColumns().map(r=>r.id).filter(Boolean);t.setColumnPinning(r=>{var i,o;if(s==="right"){var a,l;return{left:((a=r?.left)!=null?a:[]).filter(c=>!(n!=null&&n.includes(c))),right:[...((l=r?.right)!=null?l:[]).filter(c=>!(n!=null&&n.includes(c))),...n]}}if(s==="left"){var u,d;return{left:[...((u=r?.left)!=null?u:[]).filter(c=>!(n!=null&&n.includes(c))),...n],right:((d=r?.right)!=null?d:[]).filter(c=>!(n!=null&&n.includes(c)))}}return{left:((i=r?.left)!=null?i:[]).filter(c=>!(n!=null&&n.includes(c))),right:((o=r?.right)!=null?o:[]).filter(c=>!(n!=null&&n.includes(c)))}})},e.getCanPin=()=>e.getLeafColumns().some(s=>{var n,r,i;return((n=s.columnDef.enablePinning)!=null?n:!0)&&((r=(i=t.options.enableColumnPinning)!=null?i:t.options.enablePinning)!=null?r:!0)}),e.getIsPinned=()=>{const s=e.getLeafColumns().map(a=>a.id),{left:n,right:r}=t.getState().columnPinning,i=s.some(a=>n?.includes(a)),o=s.some(a=>r?.includes(a));return i?"left":o?"right":!1},e.getPinnedIndex=()=>{var s,n;const r=e.getIsPinned();return r?(s=(n=t.getState().columnPinning)==null||(n=n[r])==null?void 0:n.indexOf(e.id))!=null?s:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=T(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(s,n,r)=>{const i=[...n??[],...r??[]];return s.filter(o=>!i.includes(o.column.id))},A(t.options,"debugRows","getCenterVisibleCells")),e.getLeftVisibleCells=T(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(s,n)=>(n??[]).map(r=>s.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"left"})),A(t.options,"debugRows","getLeftVisibleCells")),e.getRightVisibleCells=T(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(s,n)=>(n??[]).map(r=>s.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"right"})),A(t.options,"debugRows","getRightVisibleCells"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var s,n;return e.setColumnPinning(t?ss():(s=(n=e.initialState)==null?void 0:n.columnPinning)!=null?s:ss())},e.getIsSomeColumnsPinned=t=>{var s;const n=e.getState().columnPinning;if(!t){var r,i;return!!((r=n.left)!=null&&r.length||(i=n.right)!=null&&i.length)}return!!((s=n[t])!=null&&s.length)},e.getLeftLeafColumns=T(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,s)=>(s??[]).map(n=>t.find(r=>r.id===n)).filter(Boolean),A(e.options,"debugColumns","getLeftLeafColumns")),e.getRightLeafColumns=T(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,s)=>(s??[]).map(n=>t.find(r=>r.id===n)).filter(Boolean),A(e.options,"debugColumns","getRightLeafColumns")),e.getCenterLeafColumns=T(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n)=>{const r=[...s??[],...n??[]];return t.filter(i=>!r.includes(i.id))},A(e.options,"debugColumns","getCenterLeafColumns"))}};function vl(e){return e||(typeof document<"u"?document:null)}var St={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ns=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),Sl={getDefaultColumnDef:()=>St,getInitialState:e=>({columnSizing:{},columnSizingInfo:ns(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:te("columnSizing",e),onColumnSizingInfoChange:te("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var s,n,r;const i=t.getState().columnSizing[e.id];return Math.min(Math.max((s=e.columnDef.minSize)!=null?s:St.minSize,(n=i??e.columnDef.size)!=null?n:St.size),(r=e.columnDef.maxSize)!=null?r:St.maxSize)},e.getStart=T(s=>[s,tt(t,s),t.getState().columnSizing],(s,n)=>n.slice(0,e.getIndex(s)).reduce((r,i)=>r+i.getSize(),0),A(t.options,"debugColumns","getStart")),e.getAfter=T(s=>[s,tt(t,s),t.getState().columnSizing],(s,n)=>n.slice(e.getIndex(s)+1).reduce((r,i)=>r+i.getSize(),0),A(t.options,"debugColumns","getAfter")),e.resetSize=()=>{t.setColumnSizing(s=>{let{[e.id]:n,...r}=s;return r})},e.getCanResize=()=>{var s,n;return((s=e.columnDef.enableResizing)!=null?s:!0)&&((n=t.options.enableColumnResizing)!=null?n:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let s=0;const n=r=>{if(r.subHeaders.length)r.subHeaders.forEach(n);else{var i;s+=(i=r.column.getSize())!=null?i:0}};return n(e),s},e.getStart=()=>{if(e.index>0){const s=e.headerGroup.headers[e.index-1];return s.getStart()+s.getSize()}return 0},e.getResizeHandler=s=>{const n=t.getColumn(e.column.id),r=n?.getCanResize();return i=>{if(!n||!r||(i.persist==null||i.persist(),rs(i)&&i.touches&&i.touches.length>1))return;const o=e.getSize(),a=e?e.getLeafHeaders().map(m=>[m.column.id,m.column.getSize()]):[[n.id,n.getSize()]],l=rs(i)?Math.round(i.touches[0].clientX):i.clientX,u={},d=(m,S)=>{typeof S=="number"&&(t.setColumnSizingInfo(C=>{var I,y;const R=t.options.columnResizeDirection==="rtl"?-1:1,b=(S-((I=C?.startOffset)!=null?I:0))*R,_=Math.max(b/((y=C?.startSize)!=null?y:0),-.999999);return C.columnSizingStart.forEach(M=>{let[P,E]=M;u[P]=Math.round(Math.max(E+E*_,0)*100)/100}),{...C,deltaOffset:b,deltaPercentage:_}}),(t.options.columnResizeMode==="onChange"||m==="end")&&t.setColumnSizing(C=>({...C,...u})))},c=m=>d("move",m),h=m=>{d("end",m),t.setColumnSizingInfo(S=>({...S,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},f=vl(s),g={moveHandler:m=>c(m.clientX),upHandler:m=>{f?.removeEventListener("mousemove",g.moveHandler),f?.removeEventListener("mouseup",g.upHandler),h(m.clientX)}},p={moveHandler:m=>(m.cancelable&&(m.preventDefault(),m.stopPropagation()),c(m.touches[0].clientX),!1),upHandler:m=>{var S;f?.removeEventListener("touchmove",p.moveHandler),f?.removeEventListener("touchend",p.upHandler),m.cancelable&&(m.preventDefault(),m.stopPropagation()),h((S=m.touches[0])==null?void 0:S.clientX)}},v=yl()?{passive:!1}:!1;rs(i)?(f?.addEventListener("touchmove",p.moveHandler,v),f?.addEventListener("touchend",p.upHandler,v)):(f?.addEventListener("mousemove",g.moveHandler,v),f?.addEventListener("mouseup",g.upHandler,v)),t.setColumnSizingInfo(m=>({...m,startOffset:l,startSize:o,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:n.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var s;e.setColumnSizing(t?{}:(s=e.initialState.columnSizing)!=null?s:{})},e.resetHeaderSizeInfo=t=>{var s;e.setColumnSizingInfo(t?ns():(s=e.initialState.columnSizingInfo)!=null?s:ns())},e.getTotalSize=()=>{var t,s;return(t=(s=e.getHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,s;return(t=(s=e.getLeftHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,s;return(t=(s=e.getCenterHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,s;return(t=(s=e.getRightHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0}}},yt=null;function yl(){if(typeof yt=="boolean")return yt;let e=!1;try{const t={get passive(){return e=!0,!1}},s=()=>{};window.addEventListener("test",s,t),window.removeEventListener("test",s)}catch{e=!1}return yt=e,yt}function rs(e){return e.type==="touchstart"}var Cl={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:te("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=s=>{e.getCanHide()&&t.setColumnVisibility(n=>({...n,[e.id]:s??!e.getIsVisible()}))},e.getIsVisible=()=>{var s,n;const r=e.columns;return(s=r.length?r.some(i=>i.getIsVisible()):(n=t.getState().columnVisibility)==null?void 0:n[e.id])!=null?s:!0},e.getCanHide=()=>{var s,n;return((s=e.columnDef.enableHiding)!=null?s:!0)&&((n=t.options.enableHiding)!=null?n:!0)},e.getToggleVisibilityHandler=()=>s=>{e.toggleVisibility==null||e.toggleVisibility(s.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=T(()=>[e.getAllCells(),t.getState().columnVisibility],s=>s.filter(n=>n.column.getIsVisible()),A(t.options,"debugRows","_getAllVisibleCells")),e.getVisibleCells=T(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(s,n,r)=>[...s,...n,...r],A(t.options,"debugRows","getVisibleCells"))},createTable:e=>{const t=(s,n)=>T(()=>[n(),n().filter(r=>r.getIsVisible()).map(r=>r.id).join("_")],r=>r.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),A(e.options,"debugColumns",s));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=s=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(s),e.resetColumnVisibility=s=>{var n;e.setColumnVisibility(s?{}:(n=e.initialState.columnVisibility)!=null?n:{})},e.toggleAllColumnsVisible=s=>{var n;s=(n=s)!=null?n:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((r,i)=>({...r,[i.id]:s||!(i.getCanHide!=null&&i.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(s=>!(s.getIsVisible!=null&&s.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(s=>s.getIsVisible==null?void 0:s.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>s=>{var n;e.toggleAllColumnsVisible((n=s.target)==null?void 0:n.checked)}}};function tt(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}var Rl={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},Il={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:te("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var s;const n=(s=e.getCoreRowModel().flatRows[0])==null||(s=s._getAllCellsByColumnId()[t.id])==null?void 0:s.getValue();return typeof n=="string"||typeof n=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var s,n,r,i;return((s=e.columnDef.enableGlobalFilter)!=null?s:!0)&&((n=t.options.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&((i=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?i:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>le.includesString,e.getGlobalFilterFn=()=>{var t,s;const{globalFilterFn:n}=e.options;return Bt(n)?n:n==="auto"?e.getGlobalAutoFilterFn():(t=(s=e.options.filterFns)==null?void 0:s[n])!=null?t:le[n]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},wl={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:te("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,s=!1;e._autoResetExpanded=()=>{var n,r;if(!t){e._queue(()=>{t=!0});return}if((n=(r=e.options.autoResetAll)!=null?r:e.options.autoResetExpanded)!=null?n:!e.options.manualExpanding){if(s)return;s=!0,e._queue(()=>{e.resetExpanded(),s=!1})}},e.setExpanded=n=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(n),e.toggleAllRowsExpanded=n=>{n??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=n=>{var r,i;e.setExpanded(n?{}:(r=(i=e.initialState)==null?void 0:i.expanded)!=null?r:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(n=>n.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>n=>{n.persist==null||n.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const n=e.getState().expanded;return n===!0||Object.values(n).some(Boolean)},e.getIsAllRowsExpanded=()=>{const n=e.getState().expanded;return typeof n=="boolean"?n===!0:!(!Object.keys(n).length||e.getRowModel().flatRows.some(r=>!r.getIsExpanded()))},e.getExpandedDepth=()=>{let n=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(r=>{const i=r.split(".");n=Math.max(n,i.length)}),n},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=s=>{t.setExpanded(n=>{var r;const i=n===!0?!0:!!(n!=null&&n[e.id]);let o={};if(n===!0?Object.keys(t.getRowModel().rowsById).forEach(a=>{o[a]=!0}):o=n,s=(r=s)!=null?r:!i,!i&&s)return{...o,[e.id]:!0};if(i&&!s){const{[e.id]:a,...l}=o;return l}return n})},e.getIsExpanded=()=>{var s;const n=t.getState().expanded;return!!((s=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?s:n===!0||n?.[e.id])},e.getCanExpand=()=>{var s,n,r;return(s=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?s:((n=t.options.enableExpanding)!=null?n:!0)&&!!((r=e.subRows)!=null&&r.length)},e.getIsAllParentsExpanded=()=>{let s=!0,n=e;for(;s&&n.parentId;)n=t.getRow(n.parentId,!0),s=n.getIsExpanded();return s},e.getToggleExpandedHandler=()=>{const s=e.getCanExpand();return()=>{s&&e.toggleExpanded()}}}},Ms=0,Es=10,is=()=>({pageIndex:Ms,pageSize:Es}),bl={getInitialState:e=>({...e,pagination:{...is(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:te("pagination",e)}),createTable:e=>{let t=!1,s=!1;e._autoResetPageIndex=()=>{var n,r;if(!t){e._queue(()=>{t=!0});return}if((n=(r=e.options.autoResetAll)!=null?r:e.options.autoResetPageIndex)!=null?n:!e.options.manualPagination){if(s)return;s=!0,e._queue(()=>{e.resetPageIndex(),s=!1})}},e.setPagination=n=>{const r=i=>ve(n,i);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(r)},e.resetPagination=n=>{var r;e.setPagination(n?is():(r=e.initialState.pagination)!=null?r:is())},e.setPageIndex=n=>{e.setPagination(r=>{let i=ve(n,r.pageIndex);const o=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return i=Math.max(0,Math.min(i,o)),{...r,pageIndex:i}})},e.resetPageIndex=n=>{var r,i;e.setPageIndex(n?Ms:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageIndex)!=null?r:Ms)},e.resetPageSize=n=>{var r,i;e.setPageSize(n?Es:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageSize)!=null?r:Es)},e.setPageSize=n=>{e.setPagination(r=>{const i=Math.max(1,ve(n,r.pageSize)),o=r.pageSize*r.pageIndex,a=Math.floor(o/i);return{...r,pageIndex:a,pageSize:i}})},e.setPageCount=n=>e.setPagination(r=>{var i;let o=ve(n,(i=e.options.pageCount)!=null?i:-1);return typeof o=="number"&&(o=Math.max(-1,o)),{...r,pageCount:o}}),e.getPageOptions=T(()=>[e.getPageCount()],n=>{let r=[];return n&&n>0&&(r=[...new Array(n)].fill(null).map((i,o)=>o)),r},A(e.options,"debugTable","getPageOptions")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:n}=e.getState().pagination,r=e.getPageCount();return r===-1?!0:r===0?!1:n<r-1},e.previousPage=()=>e.setPageIndex(n=>n-1),e.nextPage=()=>e.setPageIndex(n=>n+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var n;return(n=e.options.pageCount)!=null?n:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var n;return(n=e.options.rowCount)!=null?n:e.getPrePaginationRowModel().rows.length}}},os=()=>({top:[],bottom:[]}),_l={getInitialState:e=>({rowPinning:os(),...e}),getDefaultOptions:e=>({onRowPinningChange:te("rowPinning",e)}),createRow:(e,t)=>{e.pin=(s,n,r)=>{const i=n?e.getLeafRows().map(l=>{let{id:u}=l;return u}):[],o=r?e.getParentRows().map(l=>{let{id:u}=l;return u}):[],a=new Set([...o,e.id,...i]);t.setRowPinning(l=>{var u,d;if(s==="bottom"){var c,h;return{top:((c=l?.top)!=null?c:[]).filter(p=>!(a!=null&&a.has(p))),bottom:[...((h=l?.bottom)!=null?h:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)]}}if(s==="top"){var f,g;return{top:[...((f=l?.top)!=null?f:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)],bottom:((g=l?.bottom)!=null?g:[]).filter(p=>!(a!=null&&a.has(p)))}}return{top:((u=l?.top)!=null?u:[]).filter(p=>!(a!=null&&a.has(p))),bottom:((d=l?.bottom)!=null?d:[]).filter(p=>!(a!=null&&a.has(p)))}})},e.getCanPin=()=>{var s;const{enableRowPinning:n,enablePinning:r}=t.options;return typeof n=="function"?n(e):(s=n??r)!=null?s:!0},e.getIsPinned=()=>{const s=[e.id],{top:n,bottom:r}=t.getState().rowPinning,i=s.some(a=>n?.includes(a)),o=s.some(a=>r?.includes(a));return i?"top":o?"bottom":!1},e.getPinnedIndex=()=>{var s,n;const r=e.getIsPinned();if(!r)return-1;const i=(s=r==="top"?t.getTopRows():t.getBottomRows())==null?void 0:s.map(o=>{let{id:a}=o;return a});return(n=i?.indexOf(e.id))!=null?n:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var s,n;return e.setRowPinning(t?os():(s=(n=e.initialState)==null?void 0:n.rowPinning)!=null?s:os())},e.getIsSomeRowsPinned=t=>{var s;const n=e.getState().rowPinning;if(!t){var r,i;return!!((r=n.top)!=null&&r.length||(i=n.bottom)!=null&&i.length)}return!!((s=n[t])!=null&&s.length)},e._getPinnedRows=(t,s,n)=>{var r;return((r=e.options.keepPinnedRows)==null||r?(s??[]).map(i=>{const o=e.getRow(i,!0);return o.getIsAllParentsExpanded()?o:null}):(s??[]).map(i=>t.find(o=>o.id===i))).filter(Boolean).map(i=>({...i,position:n}))},e.getTopRows=T(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,s)=>e._getPinnedRows(t,s,"top"),A(e.options,"debugRows","getTopRows")),e.getBottomRows=T(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,s)=>e._getPinnedRows(t,s,"bottom"),A(e.options,"debugRows","getBottomRows")),e.getCenterRows=T(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,s,n)=>{const r=new Set([...s??[],...n??[]]);return t.filter(i=>!r.has(i.id))},A(e.options,"debugRows","getCenterRows"))}},Ml={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:te("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var s;return e.setRowSelection(t?{}:(s=e.initialState.rowSelection)!=null?s:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(s=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const n={...s},r=e.getPreGroupedRowModel().flatRows;return t?r.forEach(i=>{i.getCanSelect()&&(n[i.id]=!0)}):r.forEach(i=>{delete n[i.id]}),n})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(s=>{const n=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),r={...s};return e.getRowModel().rows.forEach(i=>{xs(r,i.id,n,!0,e)}),r}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=T(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,s)=>Object.keys(t).length?as(e,s):{rows:[],flatRows:[],rowsById:{}},A(e.options,"debugTable","getSelectedRowModel")),e.getFilteredSelectedRowModel=T(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,s)=>Object.keys(t).length?as(e,s):{rows:[],flatRows:[],rowsById:{}},A(e.options,"debugTable","getFilteredSelectedRowModel")),e.getGroupedSelectedRowModel=T(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,s)=>Object.keys(t).length?as(e,s):{rows:[],flatRows:[],rowsById:{}},A(e.options,"debugTable","getGroupedSelectedRowModel")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:s}=e.getState();let n=!!(t.length&&Object.keys(s).length);return n&&t.some(r=>r.getCanSelect()&&!s[r.id])&&(n=!1),n},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(r=>r.getCanSelect()),{rowSelection:s}=e.getState();let n=!!t.length;return n&&t.some(r=>!s[r.id])&&(n=!1),n},e.getIsSomeRowsSelected=()=>{var t;const s=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return s>0&&s<e.getFilteredRowModel().flatRows.length},e.getIsSomePageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(s=>s.getCanSelect()).some(s=>s.getIsSelected()||s.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(s,n)=>{const r=e.getIsSelected();t.setRowSelection(i=>{var o;if(s=typeof s<"u"?s:!r,e.getCanSelect()&&r===s)return i;const a={...i};return xs(a,e.id,s,(o=n?.selectChildren)!=null?o:!0,t),a})},e.getIsSelected=()=>{const{rowSelection:s}=t.getState();return Ks(e,s)},e.getIsSomeSelected=()=>{const{rowSelection:s}=t.getState();return Ps(e,s)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:s}=t.getState();return Ps(e,s)==="all"},e.getCanSelect=()=>{var s;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(s=t.options.enableRowSelection)!=null?s:!0},e.getCanSelectSubRows=()=>{var s;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(s=t.options.enableSubRowSelection)!=null?s:!0},e.getCanMultiSelect=()=>{var s;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(s=t.options.enableMultiRowSelection)!=null?s:!0},e.getToggleSelectedHandler=()=>{const s=e.getCanSelect();return n=>{var r;s&&e.toggleSelected((r=n.target)==null?void 0:r.checked)}}}},xs=(e,t,s,n,r)=>{var i;const o=r.getRow(t,!0);s?(o.getCanMultiSelect()||Object.keys(e).forEach(a=>delete e[a]),o.getCanSelect()&&(e[t]=!0)):delete e[t],n&&(i=o.subRows)!=null&&i.length&&o.getCanSelectSubRows()&&o.subRows.forEach(a=>xs(e,a.id,s,n,r))};function as(e,t){const s=e.getState().rowSelection,n=[],r={},i=function(o,a){return o.map(l=>{var u;const d=Ks(l,s);if(d&&(n.push(l),r[l.id]=l),(u=l.subRows)!=null&&u.length&&(l={...l,subRows:i(l.subRows)}),d)return l}).filter(Boolean)};return{rows:i(t.rows),flatRows:n,rowsById:r}}function Ks(e,t){var s;return(s=t[e.id])!=null?s:!1}function Ps(e,t,s){var n;if(!((n=e.subRows)!=null&&n.length))return!1;let r=!0,i=!1;return e.subRows.forEach(o=>{if(!(i&&!r)&&(o.getCanSelect()&&(Ks(o,t)?i=!0:r=!1),o.subRows&&o.subRows.length)){const a=Ps(o,t);a==="all"?i=!0:(a==="some"&&(i=!0),r=!1)}}),r?"all":i?"some":!1}var Ts=/([0-9]+)/gm,El=(e,t,s)=>di(Ie(e.getValue(s)).toLowerCase(),Ie(t.getValue(s)).toLowerCase()),xl=(e,t,s)=>di(Ie(e.getValue(s)),Ie(t.getValue(s))),Pl=(e,t,s)=>Qs(Ie(e.getValue(s)).toLowerCase(),Ie(t.getValue(s)).toLowerCase()),Tl=(e,t,s)=>Qs(Ie(e.getValue(s)),Ie(t.getValue(s))),Al=(e,t,s)=>{const n=e.getValue(s),r=t.getValue(s);return n>r?1:n<r?-1:0},Ol=(e,t,s)=>Qs(e.getValue(s),t.getValue(s));function Qs(e,t){return e===t?0:e>t?1:-1}function Ie(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function di(e,t){const s=e.split(Ts).filter(Boolean),n=t.split(Ts).filter(Boolean);for(;s.length&&n.length;){const r=s.shift(),i=n.shift(),o=parseInt(r,10),a=parseInt(i,10),l=[o,a].sort();if(isNaN(l[0])){if(r>i)return 1;if(i>r)return-1;continue}if(isNaN(l[1]))return isNaN(o)?-1:1;if(o>a)return 1;if(a>o)return-1}return s.length-n.length}var Ze={alphanumeric:El,alphanumericCaseSensitive:xl,text:Pl,textCaseSensitive:Tl,datetime:Al,basic:Ol},Ll={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:te("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const s=t.getFilteredRowModel().flatRows.slice(10);let n=!1;for(const r of s){const i=r?.getValue(e.id);if(Object.prototype.toString.call(i)==="[object Date]")return Ze.datetime;if(typeof i=="string"&&(n=!0,i.split(Ts).length>1))return Ze.alphanumeric}return n?Ze.text:Ze.basic},e.getAutoSortDir=()=>{const s=t.getFilteredRowModel().flatRows[0];return typeof s?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var s,n;if(!e)throw new Error;return Bt(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(s=(n=t.options.sortingFns)==null?void 0:n[e.columnDef.sortingFn])!=null?s:Ze[e.columnDef.sortingFn]},e.toggleSorting=(s,n)=>{const r=e.getNextSortingOrder(),i=typeof s<"u"&&s!==null;t.setSorting(o=>{const a=o?.find(f=>f.id===e.id),l=o?.findIndex(f=>f.id===e.id);let u=[],d,c=i?s:r==="desc";if(o!=null&&o.length&&e.getCanMultiSort()&&n?a?d="toggle":d="add":o!=null&&o.length&&l!==o.length-1?d="replace":a?d="toggle":d="replace",d==="toggle"&&(i||r||(d="remove")),d==="add"){var h;u=[...o,{id:e.id,desc:c}],u.splice(0,u.length-((h=t.options.maxMultiSortColCount)!=null?h:Number.MAX_SAFE_INTEGER))}else d==="toggle"?u=o.map(f=>f.id===e.id?{...f,desc:c}:f):d==="remove"?u=o.filter(f=>f.id!==e.id):u=[{id:e.id,desc:c}];return u})},e.getFirstSortDir=()=>{var s,n;return((s=(n=e.columnDef.sortDescFirst)!=null?n:t.options.sortDescFirst)!=null?s:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=s=>{var n,r;const i=e.getFirstSortDir(),o=e.getIsSorted();return o?o!==i&&((n=t.options.enableSortingRemoval)==null||n)&&(!(s&&(r=t.options.enableMultiRemove)!=null)||r)?!1:o==="desc"?"asc":"desc":i},e.getCanSort=()=>{var s,n;return((s=e.columnDef.enableSorting)!=null?s:!0)&&((n=t.options.enableSorting)!=null?n:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var s,n;return(s=(n=e.columnDef.enableMultiSort)!=null?n:t.options.enableMultiSort)!=null?s:!!e.accessorFn},e.getIsSorted=()=>{var s;const n=(s=t.getState().sorting)==null?void 0:s.find(r=>r.id===e.id);return n?n.desc?"desc":"asc":!1},e.getSortIndex=()=>{var s,n;return(s=(n=t.getState().sorting)==null?void 0:n.findIndex(r=>r.id===e.id))!=null?s:-1},e.clearSorting=()=>{t.setSorting(s=>s!=null&&s.length?s.filter(n=>n.id!==e.id):[])},e.getToggleSortingHandler=()=>{const s=e.getCanSort();return n=>{s&&(n.persist==null||n.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(n):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var s,n;e.setSorting(t?[]:(s=(n=e.initialState)==null?void 0:n.sorting)!=null?s:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Fl=[el,Cl,pl,ml,sl,nl,Rl,Il,Ll,fl,wl,bl,_l,Ml,Sl];function Nl(e){var t,s;const n=[...Fl,...(t=e._features)!=null?t:[]];let r={_features:n};const i=r._features.reduce((c,h)=>Object.assign(c,h.getDefaultOptions==null?void 0:h.getDefaultOptions(r)),{}),o=c=>r.options.mergeOptions?r.options.mergeOptions(i,c):{...i,...c};let a={...(s=e.initialState)!=null?s:{}};r._features.forEach(c=>{var h;a=(h=c.getInitialState==null?void 0:c.getInitialState(a))!=null?h:a});const l=[];let u=!1;const d={_features:n,options:{...i,...e},initialState:a,_queue:c=>{l.push(c),u||(u=!0,Promise.resolve().then(()=>{for(;l.length;)l.shift()();u=!1}).catch(h=>setTimeout(()=>{throw h})))},reset:()=>{r.setState(r.initialState)},setOptions:c=>{const h=ve(c,r.options);r.options=o(h)},getState:()=>r.options.state,setState:c=>{r.options.onStateChange==null||r.options.onStateChange(c)},_getRowId:(c,h,f)=>{var g;return(g=r.options.getRowId==null?void 0:r.options.getRowId(c,h,f))!=null?g:`${f?[f.id,h].join("."):h}`},getCoreRowModel:()=>(r._getCoreRowModel||(r._getCoreRowModel=r.options.getCoreRowModel(r)),r._getCoreRowModel()),getRowModel:()=>r.getPaginationRowModel(),getRow:(c,h)=>{let f=(h?r.getPrePaginationRowModel():r.getRowModel()).rowsById[c];if(!f&&(f=r.getCoreRowModel().rowsById[c],!f))throw new Error;return f},_getDefaultColumnDef:T(()=>[r.options.defaultColumn],c=>{var h;return c=(h=c)!=null?h:{},{header:f=>{const g=f.header.column.columnDef;return g.accessorKey?g.accessorKey:g.accessorFn?g.id:null},cell:f=>{var g,p;return(g=(p=f.renderValue())==null||p.toString==null?void 0:p.toString())!=null?g:null},...r._features.reduce((f,g)=>Object.assign(f,g.getDefaultColumnDef==null?void 0:g.getDefaultColumnDef()),{}),...c}},A(e,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>r.options.columns,getAllColumns:T(()=>[r._getColumnDefs()],c=>{const h=function(f,g,p){return p===void 0&&(p=0),f.map(v=>{const m=Za(r,v,p,g),S=v;return m.columns=S.columns?h(S.columns,m,p+1):[],m})};return h(c)},A(e,"debugColumns","getAllColumns")),getAllFlatColumns:T(()=>[r.getAllColumns()],c=>c.flatMap(h=>h.getFlatColumns()),A(e,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:T(()=>[r.getAllFlatColumns()],c=>c.reduce((h,f)=>(h[f.id]=f,h),{}),A(e,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:T(()=>[r.getAllColumns(),r._getOrderColumnsFn()],(c,h)=>h(c.flatMap(f=>f.getLeafColumns())),A(e,"debugColumns","getAllLeafColumns")),getColumn:c=>r._getAllFlatColumnsById()[c]};Object.assign(r,d);for(let c=0;c<r._features.length;c++){const h=r._features[c];h==null||h.createTable==null||h.createTable(r)}return r}function bc(){return e=>T(()=>[e.options.data],t=>{const s={rows:[],flatRows:[],rowsById:{}},n=function(r,i,o){i===void 0&&(i=0);const a=[];for(let u=0;u<r.length;u++){const d=tl(e,e._getRowId(r[u],u,o),r[u],u,i,void 0,o?.id);if(s.flatRows.push(d),s.rowsById[d.id]=d,a.push(d),e.options.getSubRows){var l;d.originalSubRows=e.options.getSubRows(r[u],u),(l=d.originalSubRows)!=null&&l.length&&(d.subRows=n(d.originalSubRows,i+1,d))}}return a};return s.rows=n(t),s},A(e.options,"debugTable","getRowModel",()=>e._autoResetPageIndex()))}function _c(){return e=>T(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,s)=>{if(!s.rows.length||!(t!=null&&t.length))return s;const n=e.getState().sorting,r=[],i=n.filter(l=>{var u;return(u=e.getColumn(l.id))==null?void 0:u.getCanSort()}),o={};i.forEach(l=>{const u=e.getColumn(l.id);u&&(o[l.id]={sortUndefined:u.columnDef.sortUndefined,invertSorting:u.columnDef.invertSorting,sortingFn:u.getSortingFn()})});const a=l=>{const u=l.map(d=>({...d}));return u.sort((d,c)=>{for(let f=0;f<i.length;f+=1){var h;const g=i[f],p=o[g.id],v=p.sortUndefined,m=(h=g?.desc)!=null?h:!1;let S=0;if(v){const C=d.getValue(g.id),I=c.getValue(g.id),y=C===void 0,R=I===void 0;if(y||R){if(v==="first")return y?-1:1;if(v==="last")return y?1:-1;S=y&&R?0:y?v:-v}}if(S===0&&(S=p.sortingFn(d,c,g.id)),S!==0)return m&&(S*=-1),p.invertSorting&&(S*=-1),S}return d.index-c.index}),u.forEach(d=>{var c;r.push(d),(c=d.subRows)!=null&&c.length&&(d.subRows=a(d.subRows))}),u};return{rows:a(s.rows),flatRows:r,rowsById:s.rowsById}},A(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function Mc(e,t){return e?Dl(e)?w.createElement(e,t):e:null}function Dl(e){return kl(e)||typeof e=="function"||$l(e)}function kl(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function $l(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Ec(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[s]=w.useState(()=>({current:Nl(t)})),[n,r]=w.useState(()=>s.current.initialState);return s.current.setOptions(i=>({...i,...e,state:{...n,...e.state},onStateChange:o=>{r(o),e.onStateChange==null||e.onStateChange(o)}})),s.current}function De(e,t,s){let n=s.initialDeps??[],r,i=!0;function o(){var a,l,u;let d;s.key&&((a=s.debug)!=null&&a.call(s))&&(d=Date.now());const c=e();if(!(c.length!==n.length||c.some((f,g)=>n[g]!==f)))return r;n=c;let h;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(h=Date.now()),r=t(...c),s.key&&((u=s.debug)!=null&&u.call(s))){const f=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-h)*100)/100,p=g/16,v=(m,S)=>{for(m=String(m);m.length<S;)m=" "+m;return m};console.info(`%c⏱ ${v(g,5)} /${v(f,5)} ms`,`
|
|
4
|
+
color: hsl(${Math.max(0,Math.min(120-120*d,120))}deg 100% 31%);`,s?.key)}return r}}function A(e,t,s,n){return{debug:()=>{var r;return(r=e?.debugAll)!=null?r:e[t]},key:!1,onChange:n}}function Ya(e,t,s,n){const r=()=>{var i;return(i=o.getValue())!=null?i:e.options.renderFallbackValue},o={id:`${t.id}_${s.id}`,row:t,column:s,getValue:()=>t.getValue(n),renderValue:r,getContext:T(()=>[e,s,t,o],(i,a,l,u)=>({table:i,column:a,row:l,cell:u,getValue:u.getValue,renderValue:u.renderValue}),A(e.options,"debugCells","cell.getContext"))};return e._features.forEach(i=>{i.createCell==null||i.createCell(o,s,t,e)},{}),o}function Za(e,t,s,n){var r,o;const i={...e._getDefaultColumnDef(),...t},a=i.accessorKey;let l=(r=(o=i.id)!=null?o:a?typeof String.prototype.replaceAll=="function"?a.replaceAll(".","_"):a.replace(/\./g,"_"):void 0)!=null?r:typeof i.header=="string"?i.header:void 0,u;if(i.accessorFn?u=i.accessorFn:a&&(a.includes(".")?u=d=>{let h=d;for(const g of a.split(".")){var f;h=(f=h)==null?void 0:f[g]}return h}:u=d=>d[i.accessorKey]),!l)throw new Error;let c={id:`${String(l)}`,accessorFn:u,parent:n,depth:s,columnDef:i,columns:[],getFlatColumns:T(()=>[!0],()=>{var d;return[c,...(d=c.columns)==null?void 0:d.flatMap(h=>h.getFlatColumns())]},A(e.options,"debugColumns","column.getFlatColumns")),getLeafColumns:T(()=>[e._getOrderColumnsFn()],d=>{var h;return(h=c.columns)!=null&&h.length?d(c.columns.flatMap(f=>f.getLeafColumns())):[c]},A(e.options,"debugColumns","column.getLeafColumns"))};for(const d of e._features)d.createColumn==null||d.createColumn(c,e);return c}var z="debugHeaders";function Wn(e,t,s){var n;let r={id:(n=s.id)!=null?n:t.id,column:t,index:s.index,isPlaceholder:!!s.isPlaceholder,placeholderId:s.placeholderId,depth:s.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const o=[],i=a=>{a.subHeaders&&a.subHeaders.length&&a.subHeaders.map(i),o.push(a)};return i(r),o},getContext:()=>({table:e,header:r,column:t})};return e._features.forEach(o=>{o.createHeader==null||o.createHeader(r,e)}),r}var el={createTable:e=>{e.getHeaderGroups=T(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n,r)=>{var o,i;const a=(o=n?.map(c=>s.find(d=>d.id===c)).filter(Boolean))!=null?o:[],l=(i=r?.map(c=>s.find(d=>d.id===c)).filter(Boolean))!=null?i:[],u=s.filter(c=>!(n!=null&&n.includes(c.id))&&!(r!=null&&r.includes(c.id)));return vt(t,[...a,...u,...l],e)},A(e.options,z,"getHeaderGroups")),e.getCenterHeaderGroups=T(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n,r)=>(s=s.filter(o=>!(n!=null&&n.includes(o.id))&&!(r!=null&&r.includes(o.id))),vt(t,s,e,"center")),A(e.options,z,"getCenterHeaderGroups")),e.getLeftHeaderGroups=T(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,s,n)=>{var r;return vt(t,(r=n?.map(o=>s.find(i=>i.id===o)).filter(Boolean))!=null?r:[],e,"left")},A(e.options,z,"getLeftHeaderGroups")),e.getRightHeaderGroups=T(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,s,n)=>{var r;return vt(t,(r=n?.map(o=>s.find(i=>i.id===o)).filter(Boolean))!=null?r:[],e,"right")},A(e.options,z,"getRightHeaderGroups")),e.getFooterGroups=T(()=>[e.getHeaderGroups()],t=>[...t].reverse(),A(e.options,z,"getFooterGroups")),e.getLeftFooterGroups=T(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),A(e.options,z,"getLeftFooterGroups")),e.getCenterFooterGroups=T(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),A(e.options,z,"getCenterFooterGroups")),e.getRightFooterGroups=T(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),A(e.options,z,"getRightFooterGroups")),e.getFlatHeaders=T(()=>[e.getHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,z,"getFlatHeaders")),e.getLeftFlatHeaders=T(()=>[e.getLeftHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,z,"getLeftFlatHeaders")),e.getCenterFlatHeaders=T(()=>[e.getCenterHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,z,"getCenterFlatHeaders")),e.getRightFlatHeaders=T(()=>[e.getRightHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,z,"getRightFlatHeaders")),e.getCenterLeafHeaders=T(()=>[e.getCenterFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),A(e.options,z,"getCenterLeafHeaders")),e.getLeftLeafHeaders=T(()=>[e.getLeftFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),A(e.options,z,"getLeftLeafHeaders")),e.getRightLeafHeaders=T(()=>[e.getRightFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),A(e.options,z,"getRightLeafHeaders")),e.getLeafHeaders=T(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,s,n)=>{var r,o,i,a,l,u;return[...(r=(o=t[0])==null?void 0:o.headers)!=null?r:[],...(i=(a=s[0])==null?void 0:a.headers)!=null?i:[],...(l=(u=n[0])==null?void 0:u.headers)!=null?l:[]].map(c=>c.getLeafHeaders()).flat()},A(e.options,z,"getLeafHeaders"))}};function vt(e,t,s,n){var r,o;let i=0;const a=function(d,h){h===void 0&&(h=1),i=Math.max(i,h),d.filter(f=>f.getIsVisible()).forEach(f=>{var g;(g=f.columns)!=null&&g.length&&a(f.columns,h+1)},0)};a(e);let l=[];const u=(d,h)=>{const f={depth:h,id:[n,`${h}`].filter(Boolean).join("_"),headers:[]},g=[];d.forEach(p=>{const v=[...g].reverse()[0],m=p.column.depth===f.depth;let S,C=!1;if(m&&p.column.parent?S=p.column.parent:(S=p.column,C=!0),v&&v?.column===S)v.subHeaders.push(p);else{const I=Wn(s,S,{id:[n,h,S.id,p?.id].filter(Boolean).join("_"),isPlaceholder:C,placeholderId:C?`${g.filter(y=>y.column===S).length}`:void 0,depth:h,index:g.length});I.subHeaders.push(p),g.push(I)}f.headers.push(p),p.headerGroup=f}),l.push(f),h>0&&u(g,h-1)};u(t.map((d,h)=>Wn(s,d,{depth:i,index:h})),i-1),l.reverse();const c=d=>d.filter(h=>h.column.getIsVisible()).map(h=>{let f=0,g=0,p=[0];h.subHeaders&&h.subHeaders.length?(p=[],c(h.subHeaders).forEach(m=>{let{colSpan:S,rowSpan:C}=m;f+=S,p.push(C)})):f=1;const v=Math.min(...p);return g=g+v,h.colSpan=f,h.rowSpan=g,{colSpan:f,rowSpan:g}});return c((r=(o=l[0])==null?void 0:o.headers)!=null?r:[]),l}var tl=(e,t,s,n,r,o,i)=>{let a={id:t,index:n,original:s,depth:r,parentId:i,_valuesCache:{},_uniqueValuesCache:{},getValue:l=>{if(a._valuesCache.hasOwnProperty(l))return a._valuesCache[l];const u=e.getColumn(l);if(u!=null&&u.accessorFn)return a._valuesCache[l]=u.accessorFn(a.original,n),a._valuesCache[l]},getUniqueValues:l=>{if(a._uniqueValuesCache.hasOwnProperty(l))return a._uniqueValuesCache[l];const u=e.getColumn(l);if(u!=null&&u.accessorFn)return u.columnDef.getUniqueValues?(a._uniqueValuesCache[l]=u.columnDef.getUniqueValues(a.original,n),a._uniqueValuesCache[l]):(a._uniqueValuesCache[l]=[a.getValue(l)],a._uniqueValuesCache[l])},renderValue:l=>{var u;return(u=a.getValue(l))!=null?u:e.options.renderFallbackValue},subRows:o??[],getLeafRows:()=>Xa(a.subRows,l=>l.subRows),getParentRow:()=>a.parentId?e.getRow(a.parentId,!0):void 0,getParentRows:()=>{let l=[],u=a;for(;;){const c=u.getParentRow();if(!c)break;l.push(c),u=c}return l.reverse()},getAllCells:T(()=>[e.getAllLeafColumns()],l=>l.map(u=>Ya(e,a,u,u.id)),A(e.options,"debugRows","getAllCells")),_getAllCellsByColumnId:T(()=>[a.getAllCells()],l=>l.reduce((u,c)=>(u[c.column.id]=c,u),{}),A(e.options,"debugRows","getAllCellsByColumnId"))};for(let l=0;l<e._features.length;l++){const u=e._features[l];u==null||u.createRow==null||u.createRow(a,e)}return a},sl={createColumn:(e,t)=>{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},no=(e,t,s)=>{var n,r;const o=s==null||(n=s.toString())==null?void 0:n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(o))};no.autoRemove=e=>oe(e);var ro=(e,t,s)=>{var n;return!!(!((n=e.getValue(t))==null||(n=n.toString())==null)&&n.includes(s))};ro.autoRemove=e=>oe(e);var oo=(e,t,s)=>{var n;return((n=e.getValue(t))==null||(n=n.toString())==null?void 0:n.toLowerCase())===s?.toLowerCase()};oo.autoRemove=e=>oe(e);var io=(e,t,s)=>{var n;return(n=e.getValue(t))==null?void 0:n.includes(s)};io.autoRemove=e=>oe(e);var ao=(e,t,s)=>!s.some(n=>{var r;return!((r=e.getValue(t))!=null&&r.includes(n))});ao.autoRemove=e=>oe(e)||!(e!=null&&e.length);var lo=(e,t,s)=>s.some(n=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)});lo.autoRemove=e=>oe(e)||!(e!=null&&e.length);var uo=(e,t,s)=>e.getValue(t)===s;uo.autoRemove=e=>oe(e);var co=(e,t,s)=>e.getValue(t)==s;co.autoRemove=e=>oe(e);var Ws=(e,t,s)=>{let[n,r]=s;const o=e.getValue(t);return o>=n&&o<=r};Ws.resolveFilterValue=e=>{let[t,s]=e,n=typeof t!="number"?parseFloat(t):t,r=typeof s!="number"?parseFloat(s):s,o=t===null||Number.isNaN(n)?-1/0:n,i=s===null||Number.isNaN(r)?1/0:r;if(o>i){const a=o;o=i,i=a}return[o,i]};Ws.autoRemove=e=>oe(e)||oe(e[0])&&oe(e[1]);var le={includesString:no,includesStringSensitive:ro,equalsString:oo,arrIncludes:io,arrIncludesAll:ao,arrIncludesSome:lo,equals:uo,weakEquals:co,inNumberRange:Ws};function oe(e){return e==null||e===""}var nl={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:te("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const s=t.getCoreRowModel().flatRows[0],n=s?.getValue(e.id);return typeof n=="string"?le.includesString:typeof n=="number"?le.inNumberRange:typeof n=="boolean"||n!==null&&typeof n=="object"?le.equals:Array.isArray(n)?le.arrIncludes:le.weakEquals},e.getFilterFn=()=>{var s,n;return Bt(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(s=(n=t.options.filterFns)==null?void 0:n[e.columnDef.filterFn])!=null?s:le[e.columnDef.filterFn]},e.getCanFilter=()=>{var s,n,r;return((s=e.columnDef.enableColumnFilter)!=null?s:!0)&&((n=t.options.enableColumnFilters)!=null?n:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var s;return(s=t.getState().columnFilters)==null||(s=s.find(n=>n.id===e.id))==null?void 0:s.value},e.getFilterIndex=()=>{var s,n;return(s=(n=t.getState().columnFilters)==null?void 0:n.findIndex(r=>r.id===e.id))!=null?s:-1},e.setFilterValue=s=>{t.setColumnFilters(n=>{const r=e.getFilterFn(),o=n?.find(c=>c.id===e.id),i=ve(s,o?o.value:void 0);if(Kn(r,i,e)){var a;return(a=n?.filter(c=>c.id!==e.id))!=null?a:[]}const l={id:e.id,value:i};if(o){var u;return(u=n?.map(c=>c.id===e.id?l:c))!=null?u:[]}return n!=null&&n.length?[...n,l]:[l]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const s=e.getAllLeafColumns(),n=r=>{var o;return(o=ve(t,r))==null?void 0:o.filter(i=>{const a=s.find(l=>l.id===i.id);return!(a&&Kn(a.getFilterFn(),i.value,a))})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(n)},e.resetColumnFilters=t=>{var s,n;e.setColumnFilters(t?[]:(s=(n=e.initialState)==null?void 0:n.columnFilters)!=null?s:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function Kn(e,t,s){return(e&&e.autoRemove?e.autoRemove(t,s):!1)||typeof t>"u"||typeof t=="string"&&!t}var rl=(e,t,s)=>s.reduce((n,r)=>{const o=r.getValue(e);return n+(typeof o=="number"?o:0)},0),ol=(e,t,s)=>{let n;return s.forEach(r=>{const o=r.getValue(e);o!=null&&(n>o||n===void 0&&o>=o)&&(n=o)}),n},il=(e,t,s)=>{let n;return s.forEach(r=>{const o=r.getValue(e);o!=null&&(n<o||n===void 0&&o>=o)&&(n=o)}),n},al=(e,t,s)=>{let n,r;return s.forEach(o=>{const i=o.getValue(e);i!=null&&(n===void 0?i>=i&&(n=r=i):(n>i&&(n=i),r<i&&(r=i)))}),[n,r]},ll=(e,t)=>{let s=0,n=0;if(t.forEach(r=>{let o=r.getValue(e);o!=null&&(o=+o)>=o&&(++s,n+=o)}),s)return n/s},ul=(e,t)=>{if(!t.length)return;const s=t.map(o=>o.getValue(e));if(!Ja(s))return;if(s.length===1)return s[0];const n=Math.floor(s.length/2),r=s.sort((o,i)=>o-i);return s.length%2!==0?r[n]:(r[n-1]+r[n])/2},cl=(e,t)=>Array.from(new Set(t.map(s=>s.getValue(e))).values()),dl=(e,t)=>new Set(t.map(s=>s.getValue(e))).size,hl=(e,t)=>t.length,ts={sum:rl,min:ol,max:il,extent:al,mean:ll,median:ul,unique:cl,uniqueCount:dl,count:hl},fl={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,s;return(t=(s=e.getValue())==null||s.toString==null?void 0:s.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:te("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(s=>s!=null&&s.includes(e.id)?s.filter(n=>n!==e.id):[...s??[],e.id])},e.getCanGroup=()=>{var s,n;return((s=e.columnDef.enableGrouping)!=null?s:!0)&&((n=t.options.enableGrouping)!=null?n:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var s;return(s=t.getState().grouping)==null?void 0:s.includes(e.id)},e.getGroupedIndex=()=>{var s;return(s=t.getState().grouping)==null?void 0:s.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const s=e.getCanGroup();return()=>{s&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const s=t.getCoreRowModel().flatRows[0],n=s?.getValue(e.id);if(typeof n=="number")return ts.sum;if(Object.prototype.toString.call(n)==="[object Date]")return ts.extent},e.getAggregationFn=()=>{var s,n;if(!e)throw new Error;return Bt(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(s=(n=t.options.aggregationFns)==null?void 0:n[e.columnDef.aggregationFn])!=null?s:ts[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var s,n;e.setGrouping(t?[]:(s=(n=e.initialState)==null?void 0:n.grouping)!=null?s:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=s=>{if(e._groupingValuesCache.hasOwnProperty(s))return e._groupingValuesCache[s];const n=t.getColumn(s);return n!=null&&n.columnDef.getGroupingValue?(e._groupingValuesCache[s]=n.columnDef.getGroupingValue(e.original),e._groupingValuesCache[s]):e.getValue(s)},e._groupingValuesCache={}},createCell:(e,t,s,n)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===s.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var r;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((r=s.subRows)!=null&&r.length)}}};function gl(e,t,s){if(!(t!=null&&t.length)||!s)return e;const n=e.filter(r=>!t.includes(r.id));return s==="remove"?n:[...t.map(r=>e.find(o=>o.id===r)).filter(Boolean),...n]}var pl={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:te("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=T(s=>[tt(t,s)],s=>s.findIndex(n=>n.id===e.id),A(t.options,"debugColumns","getIndex")),e.getIsFirstColumn=s=>{var n;return((n=tt(t,s)[0])==null?void 0:n.id)===e.id},e.getIsLastColumn=s=>{var n;const r=tt(t,s);return((n=r[r.length-1])==null?void 0:n.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var s;e.setColumnOrder(t?[]:(s=e.initialState.columnOrder)!=null?s:[])},e._getOrderColumnsFn=T(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,s,n)=>r=>{let o=[];if(!(t!=null&&t.length))o=r;else{const i=[...t],a=[...r];for(;a.length&&i.length;){const l=i.shift(),u=a.findIndex(c=>c.id===l);u>-1&&o.push(a.splice(u,1)[0])}o=[...o,...a]}return gl(o,s,n)},A(e.options,"debugTable","_getOrderColumnsFn"))}},ss=()=>({left:[],right:[]}),ml={getInitialState:e=>({columnPinning:ss(),...e}),getDefaultOptions:e=>({onColumnPinningChange:te("columnPinning",e)}),createColumn:(e,t)=>{e.pin=s=>{const n=e.getLeafColumns().map(r=>r.id).filter(Boolean);t.setColumnPinning(r=>{var o,i;if(s==="right"){var a,l;return{left:((a=r?.left)!=null?a:[]).filter(d=>!(n!=null&&n.includes(d))),right:[...((l=r?.right)!=null?l:[]).filter(d=>!(n!=null&&n.includes(d))),...n]}}if(s==="left"){var u,c;return{left:[...((u=r?.left)!=null?u:[]).filter(d=>!(n!=null&&n.includes(d))),...n],right:((c=r?.right)!=null?c:[]).filter(d=>!(n!=null&&n.includes(d)))}}return{left:((o=r?.left)!=null?o:[]).filter(d=>!(n!=null&&n.includes(d))),right:((i=r?.right)!=null?i:[]).filter(d=>!(n!=null&&n.includes(d)))}})},e.getCanPin=()=>e.getLeafColumns().some(s=>{var n,r,o;return((n=s.columnDef.enablePinning)!=null?n:!0)&&((r=(o=t.options.enableColumnPinning)!=null?o:t.options.enablePinning)!=null?r:!0)}),e.getIsPinned=()=>{const s=e.getLeafColumns().map(a=>a.id),{left:n,right:r}=t.getState().columnPinning,o=s.some(a=>n?.includes(a)),i=s.some(a=>r?.includes(a));return o?"left":i?"right":!1},e.getPinnedIndex=()=>{var s,n;const r=e.getIsPinned();return r?(s=(n=t.getState().columnPinning)==null||(n=n[r])==null?void 0:n.indexOf(e.id))!=null?s:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=T(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(s,n,r)=>{const o=[...n??[],...r??[]];return s.filter(i=>!o.includes(i.column.id))},A(t.options,"debugRows","getCenterVisibleCells")),e.getLeftVisibleCells=T(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(s,n)=>(n??[]).map(r=>s.find(o=>o.column.id===r)).filter(Boolean).map(r=>({...r,position:"left"})),A(t.options,"debugRows","getLeftVisibleCells")),e.getRightVisibleCells=T(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(s,n)=>(n??[]).map(r=>s.find(o=>o.column.id===r)).filter(Boolean).map(r=>({...r,position:"right"})),A(t.options,"debugRows","getRightVisibleCells"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var s,n;return e.setColumnPinning(t?ss():(s=(n=e.initialState)==null?void 0:n.columnPinning)!=null?s:ss())},e.getIsSomeColumnsPinned=t=>{var s;const n=e.getState().columnPinning;if(!t){var r,o;return!!((r=n.left)!=null&&r.length||(o=n.right)!=null&&o.length)}return!!((s=n[t])!=null&&s.length)},e.getLeftLeafColumns=T(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,s)=>(s??[]).map(n=>t.find(r=>r.id===n)).filter(Boolean),A(e.options,"debugColumns","getLeftLeafColumns")),e.getRightLeafColumns=T(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,s)=>(s??[]).map(n=>t.find(r=>r.id===n)).filter(Boolean),A(e.options,"debugColumns","getRightLeafColumns")),e.getCenterLeafColumns=T(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n)=>{const r=[...s??[],...n??[]];return t.filter(o=>!r.includes(o.id))},A(e.options,"debugColumns","getCenterLeafColumns"))}};function vl(e){return e||(typeof document<"u"?document:null)}var St={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ns=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),Sl={getDefaultColumnDef:()=>St,getInitialState:e=>({columnSizing:{},columnSizingInfo:ns(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:te("columnSizing",e),onColumnSizingInfoChange:te("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var s,n,r;const o=t.getState().columnSizing[e.id];return Math.min(Math.max((s=e.columnDef.minSize)!=null?s:St.minSize,(n=o??e.columnDef.size)!=null?n:St.size),(r=e.columnDef.maxSize)!=null?r:St.maxSize)},e.getStart=T(s=>[s,tt(t,s),t.getState().columnSizing],(s,n)=>n.slice(0,e.getIndex(s)).reduce((r,o)=>r+o.getSize(),0),A(t.options,"debugColumns","getStart")),e.getAfter=T(s=>[s,tt(t,s),t.getState().columnSizing],(s,n)=>n.slice(e.getIndex(s)+1).reduce((r,o)=>r+o.getSize(),0),A(t.options,"debugColumns","getAfter")),e.resetSize=()=>{t.setColumnSizing(s=>{let{[e.id]:n,...r}=s;return r})},e.getCanResize=()=>{var s,n;return((s=e.columnDef.enableResizing)!=null?s:!0)&&((n=t.options.enableColumnResizing)!=null?n:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let s=0;const n=r=>{if(r.subHeaders.length)r.subHeaders.forEach(n);else{var o;s+=(o=r.column.getSize())!=null?o:0}};return n(e),s},e.getStart=()=>{if(e.index>0){const s=e.headerGroup.headers[e.index-1];return s.getStart()+s.getSize()}return 0},e.getResizeHandler=s=>{const n=t.getColumn(e.column.id),r=n?.getCanResize();return o=>{if(!n||!r||(o.persist==null||o.persist(),rs(o)&&o.touches&&o.touches.length>1))return;const i=e.getSize(),a=e?e.getLeafHeaders().map(m=>[m.column.id,m.column.getSize()]):[[n.id,n.getSize()]],l=rs(o)?Math.round(o.touches[0].clientX):o.clientX,u={},c=(m,S)=>{typeof S=="number"&&(t.setColumnSizingInfo(C=>{var I,y;const R=t.options.columnResizeDirection==="rtl"?-1:1,b=(S-((I=C?.startOffset)!=null?I:0))*R,_=Math.max(b/((y=C?.startSize)!=null?y:0),-.999999);return C.columnSizingStart.forEach(M=>{let[P,E]=M;u[P]=Math.round(Math.max(E+E*_,0)*100)/100}),{...C,deltaOffset:b,deltaPercentage:_}}),(t.options.columnResizeMode==="onChange"||m==="end")&&t.setColumnSizing(C=>({...C,...u})))},d=m=>c("move",m),h=m=>{c("end",m),t.setColumnSizingInfo(S=>({...S,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},f=vl(s),g={moveHandler:m=>d(m.clientX),upHandler:m=>{f?.removeEventListener("mousemove",g.moveHandler),f?.removeEventListener("mouseup",g.upHandler),h(m.clientX)}},p={moveHandler:m=>(m.cancelable&&(m.preventDefault(),m.stopPropagation()),d(m.touches[0].clientX),!1),upHandler:m=>{var S;f?.removeEventListener("touchmove",p.moveHandler),f?.removeEventListener("touchend",p.upHandler),m.cancelable&&(m.preventDefault(),m.stopPropagation()),h((S=m.touches[0])==null?void 0:S.clientX)}},v=yl()?{passive:!1}:!1;rs(o)?(f?.addEventListener("touchmove",p.moveHandler,v),f?.addEventListener("touchend",p.upHandler,v)):(f?.addEventListener("mousemove",g.moveHandler,v),f?.addEventListener("mouseup",g.upHandler,v)),t.setColumnSizingInfo(m=>({...m,startOffset:l,startSize:i,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:n.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var s;e.setColumnSizing(t?{}:(s=e.initialState.columnSizing)!=null?s:{})},e.resetHeaderSizeInfo=t=>{var s;e.setColumnSizingInfo(t?ns():(s=e.initialState.columnSizingInfo)!=null?s:ns())},e.getTotalSize=()=>{var t,s;return(t=(s=e.getHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,s;return(t=(s=e.getLeftHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,s;return(t=(s=e.getCenterHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,s;return(t=(s=e.getRightHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0}}},yt=null;function yl(){if(typeof yt=="boolean")return yt;let e=!1;try{const t={get passive(){return e=!0,!1}},s=()=>{};window.addEventListener("test",s,t),window.removeEventListener("test",s)}catch{e=!1}return yt=e,yt}function rs(e){return e.type==="touchstart"}var Cl={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:te("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=s=>{e.getCanHide()&&t.setColumnVisibility(n=>({...n,[e.id]:s??!e.getIsVisible()}))},e.getIsVisible=()=>{var s,n;const r=e.columns;return(s=r.length?r.some(o=>o.getIsVisible()):(n=t.getState().columnVisibility)==null?void 0:n[e.id])!=null?s:!0},e.getCanHide=()=>{var s,n;return((s=e.columnDef.enableHiding)!=null?s:!0)&&((n=t.options.enableHiding)!=null?n:!0)},e.getToggleVisibilityHandler=()=>s=>{e.toggleVisibility==null||e.toggleVisibility(s.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=T(()=>[e.getAllCells(),t.getState().columnVisibility],s=>s.filter(n=>n.column.getIsVisible()),A(t.options,"debugRows","_getAllVisibleCells")),e.getVisibleCells=T(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(s,n,r)=>[...s,...n,...r],A(t.options,"debugRows","getVisibleCells"))},createTable:e=>{const t=(s,n)=>T(()=>[n(),n().filter(r=>r.getIsVisible()).map(r=>r.id).join("_")],r=>r.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),A(e.options,"debugColumns",s));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=s=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(s),e.resetColumnVisibility=s=>{var n;e.setColumnVisibility(s?{}:(n=e.initialState.columnVisibility)!=null?n:{})},e.toggleAllColumnsVisible=s=>{var n;s=(n=s)!=null?n:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((r,o)=>({...r,[o.id]:s||!(o.getCanHide!=null&&o.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(s=>!(s.getIsVisible!=null&&s.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(s=>s.getIsVisible==null?void 0:s.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>s=>{var n;e.toggleAllColumnsVisible((n=s.target)==null?void 0:n.checked)}}};function tt(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}var Rl={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},Il={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:te("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var s;const n=(s=e.getCoreRowModel().flatRows[0])==null||(s=s._getAllCellsByColumnId()[t.id])==null?void 0:s.getValue();return typeof n=="string"||typeof n=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var s,n,r,o;return((s=e.columnDef.enableGlobalFilter)!=null?s:!0)&&((n=t.options.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&((o=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?o:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>le.includesString,e.getGlobalFilterFn=()=>{var t,s;const{globalFilterFn:n}=e.options;return Bt(n)?n:n==="auto"?e.getGlobalAutoFilterFn():(t=(s=e.options.filterFns)==null?void 0:s[n])!=null?t:le[n]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},wl={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:te("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,s=!1;e._autoResetExpanded=()=>{var n,r;if(!t){e._queue(()=>{t=!0});return}if((n=(r=e.options.autoResetAll)!=null?r:e.options.autoResetExpanded)!=null?n:!e.options.manualExpanding){if(s)return;s=!0,e._queue(()=>{e.resetExpanded(),s=!1})}},e.setExpanded=n=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(n),e.toggleAllRowsExpanded=n=>{n??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=n=>{var r,o;e.setExpanded(n?{}:(r=(o=e.initialState)==null?void 0:o.expanded)!=null?r:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(n=>n.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>n=>{n.persist==null||n.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const n=e.getState().expanded;return n===!0||Object.values(n).some(Boolean)},e.getIsAllRowsExpanded=()=>{const n=e.getState().expanded;return typeof n=="boolean"?n===!0:!(!Object.keys(n).length||e.getRowModel().flatRows.some(r=>!r.getIsExpanded()))},e.getExpandedDepth=()=>{let n=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(r=>{const o=r.split(".");n=Math.max(n,o.length)}),n},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=s=>{t.setExpanded(n=>{var r;const o=n===!0?!0:!!(n!=null&&n[e.id]);let i={};if(n===!0?Object.keys(t.getRowModel().rowsById).forEach(a=>{i[a]=!0}):i=n,s=(r=s)!=null?r:!o,!o&&s)return{...i,[e.id]:!0};if(o&&!s){const{[e.id]:a,...l}=i;return l}return n})},e.getIsExpanded=()=>{var s;const n=t.getState().expanded;return!!((s=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?s:n===!0||n?.[e.id])},e.getCanExpand=()=>{var s,n,r;return(s=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?s:((n=t.options.enableExpanding)!=null?n:!0)&&!!((r=e.subRows)!=null&&r.length)},e.getIsAllParentsExpanded=()=>{let s=!0,n=e;for(;s&&n.parentId;)n=t.getRow(n.parentId,!0),s=n.getIsExpanded();return s},e.getToggleExpandedHandler=()=>{const s=e.getCanExpand();return()=>{s&&e.toggleExpanded()}}}},Ms=0,Es=10,os=()=>({pageIndex:Ms,pageSize:Es}),bl={getInitialState:e=>({...e,pagination:{...os(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:te("pagination",e)}),createTable:e=>{let t=!1,s=!1;e._autoResetPageIndex=()=>{var n,r;if(!t){e._queue(()=>{t=!0});return}if((n=(r=e.options.autoResetAll)!=null?r:e.options.autoResetPageIndex)!=null?n:!e.options.manualPagination){if(s)return;s=!0,e._queue(()=>{e.resetPageIndex(),s=!1})}},e.setPagination=n=>{const r=o=>ve(n,o);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(r)},e.resetPagination=n=>{var r;e.setPagination(n?os():(r=e.initialState.pagination)!=null?r:os())},e.setPageIndex=n=>{e.setPagination(r=>{let o=ve(n,r.pageIndex);const i=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return o=Math.max(0,Math.min(o,i)),{...r,pageIndex:o}})},e.resetPageIndex=n=>{var r,o;e.setPageIndex(n?Ms:(r=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?r:Ms)},e.resetPageSize=n=>{var r,o;e.setPageSize(n?Es:(r=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?r:Es)},e.setPageSize=n=>{e.setPagination(r=>{const o=Math.max(1,ve(n,r.pageSize)),i=r.pageSize*r.pageIndex,a=Math.floor(i/o);return{...r,pageIndex:a,pageSize:o}})},e.setPageCount=n=>e.setPagination(r=>{var o;let i=ve(n,(o=e.options.pageCount)!=null?o:-1);return typeof i=="number"&&(i=Math.max(-1,i)),{...r,pageCount:i}}),e.getPageOptions=T(()=>[e.getPageCount()],n=>{let r=[];return n&&n>0&&(r=[...new Array(n)].fill(null).map((o,i)=>i)),r},A(e.options,"debugTable","getPageOptions")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:n}=e.getState().pagination,r=e.getPageCount();return r===-1?!0:r===0?!1:n<r-1},e.previousPage=()=>e.setPageIndex(n=>n-1),e.nextPage=()=>e.setPageIndex(n=>n+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var n;return(n=e.options.pageCount)!=null?n:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var n;return(n=e.options.rowCount)!=null?n:e.getPrePaginationRowModel().rows.length}}},is=()=>({top:[],bottom:[]}),_l={getInitialState:e=>({rowPinning:is(),...e}),getDefaultOptions:e=>({onRowPinningChange:te("rowPinning",e)}),createRow:(e,t)=>{e.pin=(s,n,r)=>{const o=n?e.getLeafRows().map(l=>{let{id:u}=l;return u}):[],i=r?e.getParentRows().map(l=>{let{id:u}=l;return u}):[],a=new Set([...i,e.id,...o]);t.setRowPinning(l=>{var u,c;if(s==="bottom"){var d,h;return{top:((d=l?.top)!=null?d:[]).filter(p=>!(a!=null&&a.has(p))),bottom:[...((h=l?.bottom)!=null?h:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)]}}if(s==="top"){var f,g;return{top:[...((f=l?.top)!=null?f:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)],bottom:((g=l?.bottom)!=null?g:[]).filter(p=>!(a!=null&&a.has(p)))}}return{top:((u=l?.top)!=null?u:[]).filter(p=>!(a!=null&&a.has(p))),bottom:((c=l?.bottom)!=null?c:[]).filter(p=>!(a!=null&&a.has(p)))}})},e.getCanPin=()=>{var s;const{enableRowPinning:n,enablePinning:r}=t.options;return typeof n=="function"?n(e):(s=n??r)!=null?s:!0},e.getIsPinned=()=>{const s=[e.id],{top:n,bottom:r}=t.getState().rowPinning,o=s.some(a=>n?.includes(a)),i=s.some(a=>r?.includes(a));return o?"top":i?"bottom":!1},e.getPinnedIndex=()=>{var s,n;const r=e.getIsPinned();if(!r)return-1;const o=(s=r==="top"?t.getTopRows():t.getBottomRows())==null?void 0:s.map(i=>{let{id:a}=i;return a});return(n=o?.indexOf(e.id))!=null?n:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var s,n;return e.setRowPinning(t?is():(s=(n=e.initialState)==null?void 0:n.rowPinning)!=null?s:is())},e.getIsSomeRowsPinned=t=>{var s;const n=e.getState().rowPinning;if(!t){var r,o;return!!((r=n.top)!=null&&r.length||(o=n.bottom)!=null&&o.length)}return!!((s=n[t])!=null&&s.length)},e._getPinnedRows=(t,s,n)=>{var r;return((r=e.options.keepPinnedRows)==null||r?(s??[]).map(o=>{const i=e.getRow(o,!0);return i.getIsAllParentsExpanded()?i:null}):(s??[]).map(o=>t.find(i=>i.id===o))).filter(Boolean).map(o=>({...o,position:n}))},e.getTopRows=T(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,s)=>e._getPinnedRows(t,s,"top"),A(e.options,"debugRows","getTopRows")),e.getBottomRows=T(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,s)=>e._getPinnedRows(t,s,"bottom"),A(e.options,"debugRows","getBottomRows")),e.getCenterRows=T(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,s,n)=>{const r=new Set([...s??[],...n??[]]);return t.filter(o=>!r.has(o.id))},A(e.options,"debugRows","getCenterRows"))}},Ml={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:te("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var s;return e.setRowSelection(t?{}:(s=e.initialState.rowSelection)!=null?s:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(s=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const n={...s},r=e.getPreGroupedRowModel().flatRows;return t?r.forEach(o=>{o.getCanSelect()&&(n[o.id]=!0)}):r.forEach(o=>{delete n[o.id]}),n})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(s=>{const n=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),r={...s};return e.getRowModel().rows.forEach(o=>{xs(r,o.id,n,!0,e)}),r}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=T(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,s)=>Object.keys(t).length?as(e,s):{rows:[],flatRows:[],rowsById:{}},A(e.options,"debugTable","getSelectedRowModel")),e.getFilteredSelectedRowModel=T(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,s)=>Object.keys(t).length?as(e,s):{rows:[],flatRows:[],rowsById:{}},A(e.options,"debugTable","getFilteredSelectedRowModel")),e.getGroupedSelectedRowModel=T(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,s)=>Object.keys(t).length?as(e,s):{rows:[],flatRows:[],rowsById:{}},A(e.options,"debugTable","getGroupedSelectedRowModel")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:s}=e.getState();let n=!!(t.length&&Object.keys(s).length);return n&&t.some(r=>r.getCanSelect()&&!s[r.id])&&(n=!1),n},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(r=>r.getCanSelect()),{rowSelection:s}=e.getState();let n=!!t.length;return n&&t.some(r=>!s[r.id])&&(n=!1),n},e.getIsSomeRowsSelected=()=>{var t;const s=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return s>0&&s<e.getFilteredRowModel().flatRows.length},e.getIsSomePageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(s=>s.getCanSelect()).some(s=>s.getIsSelected()||s.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(s,n)=>{const r=e.getIsSelected();t.setRowSelection(o=>{var i;if(s=typeof s<"u"?s:!r,e.getCanSelect()&&r===s)return o;const a={...o};return xs(a,e.id,s,(i=n?.selectChildren)!=null?i:!0,t),a})},e.getIsSelected=()=>{const{rowSelection:s}=t.getState();return Ks(e,s)},e.getIsSomeSelected=()=>{const{rowSelection:s}=t.getState();return Ps(e,s)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:s}=t.getState();return Ps(e,s)==="all"},e.getCanSelect=()=>{var s;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(s=t.options.enableRowSelection)!=null?s:!0},e.getCanSelectSubRows=()=>{var s;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(s=t.options.enableSubRowSelection)!=null?s:!0},e.getCanMultiSelect=()=>{var s;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(s=t.options.enableMultiRowSelection)!=null?s:!0},e.getToggleSelectedHandler=()=>{const s=e.getCanSelect();return n=>{var r;s&&e.toggleSelected((r=n.target)==null?void 0:r.checked)}}}},xs=(e,t,s,n,r)=>{var o;const i=r.getRow(t,!0);s?(i.getCanMultiSelect()||Object.keys(e).forEach(a=>delete e[a]),i.getCanSelect()&&(e[t]=!0)):delete e[t],n&&(o=i.subRows)!=null&&o.length&&i.getCanSelectSubRows()&&i.subRows.forEach(a=>xs(e,a.id,s,n,r))};function as(e,t){const s=e.getState().rowSelection,n=[],r={},o=function(i,a){return i.map(l=>{var u;const c=Ks(l,s);if(c&&(n.push(l),r[l.id]=l),(u=l.subRows)!=null&&u.length&&(l={...l,subRows:o(l.subRows)}),c)return l}).filter(Boolean)};return{rows:o(t.rows),flatRows:n,rowsById:r}}function Ks(e,t){var s;return(s=t[e.id])!=null?s:!1}function Ps(e,t,s){var n;if(!((n=e.subRows)!=null&&n.length))return!1;let r=!0,o=!1;return e.subRows.forEach(i=>{if(!(o&&!r)&&(i.getCanSelect()&&(Ks(i,t)?o=!0:r=!1),i.subRows&&i.subRows.length)){const a=Ps(i,t);a==="all"?o=!0:(a==="some"&&(o=!0),r=!1)}}),r?"all":o?"some":!1}var Ts=/([0-9]+)/gm,El=(e,t,s)=>ho(Ie(e.getValue(s)).toLowerCase(),Ie(t.getValue(s)).toLowerCase()),xl=(e,t,s)=>ho(Ie(e.getValue(s)),Ie(t.getValue(s))),Pl=(e,t,s)=>Qs(Ie(e.getValue(s)).toLowerCase(),Ie(t.getValue(s)).toLowerCase()),Tl=(e,t,s)=>Qs(Ie(e.getValue(s)),Ie(t.getValue(s))),Al=(e,t,s)=>{const n=e.getValue(s),r=t.getValue(s);return n>r?1:n<r?-1:0},Ol=(e,t,s)=>Qs(e.getValue(s),t.getValue(s));function Qs(e,t){return e===t?0:e>t?1:-1}function Ie(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function ho(e,t){const s=e.split(Ts).filter(Boolean),n=t.split(Ts).filter(Boolean);for(;s.length&&n.length;){const r=s.shift(),o=n.shift(),i=parseInt(r,10),a=parseInt(o,10),l=[i,a].sort();if(isNaN(l[0])){if(r>o)return 1;if(o>r)return-1;continue}if(isNaN(l[1]))return isNaN(i)?-1:1;if(i>a)return 1;if(a>i)return-1}return s.length-n.length}var Ze={alphanumeric:El,alphanumericCaseSensitive:xl,text:Pl,textCaseSensitive:Tl,datetime:Al,basic:Ol},Ll={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:te("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const s=t.getFilteredRowModel().flatRows.slice(10);let n=!1;for(const r of s){const o=r?.getValue(e.id);if(Object.prototype.toString.call(o)==="[object Date]")return Ze.datetime;if(typeof o=="string"&&(n=!0,o.split(Ts).length>1))return Ze.alphanumeric}return n?Ze.text:Ze.basic},e.getAutoSortDir=()=>{const s=t.getFilteredRowModel().flatRows[0];return typeof s?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var s,n;if(!e)throw new Error;return Bt(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(s=(n=t.options.sortingFns)==null?void 0:n[e.columnDef.sortingFn])!=null?s:Ze[e.columnDef.sortingFn]},e.toggleSorting=(s,n)=>{const r=e.getNextSortingOrder(),o=typeof s<"u"&&s!==null;t.setSorting(i=>{const a=i?.find(f=>f.id===e.id),l=i?.findIndex(f=>f.id===e.id);let u=[],c,d=o?s:r==="desc";if(i!=null&&i.length&&e.getCanMultiSort()&&n?a?c="toggle":c="add":i!=null&&i.length&&l!==i.length-1?c="replace":a?c="toggle":c="replace",c==="toggle"&&(o||r||(c="remove")),c==="add"){var h;u=[...i,{id:e.id,desc:d}],u.splice(0,u.length-((h=t.options.maxMultiSortColCount)!=null?h:Number.MAX_SAFE_INTEGER))}else c==="toggle"?u=i.map(f=>f.id===e.id?{...f,desc:d}:f):c==="remove"?u=i.filter(f=>f.id!==e.id):u=[{id:e.id,desc:d}];return u})},e.getFirstSortDir=()=>{var s,n;return((s=(n=e.columnDef.sortDescFirst)!=null?n:t.options.sortDescFirst)!=null?s:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=s=>{var n,r;const o=e.getFirstSortDir(),i=e.getIsSorted();return i?i!==o&&((n=t.options.enableSortingRemoval)==null||n)&&(!(s&&(r=t.options.enableMultiRemove)!=null)||r)?!1:i==="desc"?"asc":"desc":o},e.getCanSort=()=>{var s,n;return((s=e.columnDef.enableSorting)!=null?s:!0)&&((n=t.options.enableSorting)!=null?n:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var s,n;return(s=(n=e.columnDef.enableMultiSort)!=null?n:t.options.enableMultiSort)!=null?s:!!e.accessorFn},e.getIsSorted=()=>{var s;const n=(s=t.getState().sorting)==null?void 0:s.find(r=>r.id===e.id);return n?n.desc?"desc":"asc":!1},e.getSortIndex=()=>{var s,n;return(s=(n=t.getState().sorting)==null?void 0:n.findIndex(r=>r.id===e.id))!=null?s:-1},e.clearSorting=()=>{t.setSorting(s=>s!=null&&s.length?s.filter(n=>n.id!==e.id):[])},e.getToggleSortingHandler=()=>{const s=e.getCanSort();return n=>{s&&(n.persist==null||n.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(n):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var s,n;e.setSorting(t?[]:(s=(n=e.initialState)==null?void 0:n.sorting)!=null?s:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Fl=[el,Cl,pl,ml,sl,nl,Rl,Il,Ll,fl,wl,bl,_l,Ml,Sl];function Nl(e){var t,s;const n=[...Fl,...(t=e._features)!=null?t:[]];let r={_features:n};const o=r._features.reduce((d,h)=>Object.assign(d,h.getDefaultOptions==null?void 0:h.getDefaultOptions(r)),{}),i=d=>r.options.mergeOptions?r.options.mergeOptions(o,d):{...o,...d};let a={...(s=e.initialState)!=null?s:{}};r._features.forEach(d=>{var h;a=(h=d.getInitialState==null?void 0:d.getInitialState(a))!=null?h:a});const l=[];let u=!1;const c={_features:n,options:{...o,...e},initialState:a,_queue:d=>{l.push(d),u||(u=!0,Promise.resolve().then(()=>{for(;l.length;)l.shift()();u=!1}).catch(h=>setTimeout(()=>{throw h})))},reset:()=>{r.setState(r.initialState)},setOptions:d=>{const h=ve(d,r.options);r.options=i(h)},getState:()=>r.options.state,setState:d=>{r.options.onStateChange==null||r.options.onStateChange(d)},_getRowId:(d,h,f)=>{var g;return(g=r.options.getRowId==null?void 0:r.options.getRowId(d,h,f))!=null?g:`${f?[f.id,h].join("."):h}`},getCoreRowModel:()=>(r._getCoreRowModel||(r._getCoreRowModel=r.options.getCoreRowModel(r)),r._getCoreRowModel()),getRowModel:()=>r.getPaginationRowModel(),getRow:(d,h)=>{let f=(h?r.getPrePaginationRowModel():r.getRowModel()).rowsById[d];if(!f&&(f=r.getCoreRowModel().rowsById[d],!f))throw new Error;return f},_getDefaultColumnDef:T(()=>[r.options.defaultColumn],d=>{var h;return d=(h=d)!=null?h:{},{header:f=>{const g=f.header.column.columnDef;return g.accessorKey?g.accessorKey:g.accessorFn?g.id:null},cell:f=>{var g,p;return(g=(p=f.renderValue())==null||p.toString==null?void 0:p.toString())!=null?g:null},...r._features.reduce((f,g)=>Object.assign(f,g.getDefaultColumnDef==null?void 0:g.getDefaultColumnDef()),{}),...d}},A(e,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>r.options.columns,getAllColumns:T(()=>[r._getColumnDefs()],d=>{const h=function(f,g,p){return p===void 0&&(p=0),f.map(v=>{const m=Za(r,v,p,g),S=v;return m.columns=S.columns?h(S.columns,m,p+1):[],m})};return h(d)},A(e,"debugColumns","getAllColumns")),getAllFlatColumns:T(()=>[r.getAllColumns()],d=>d.flatMap(h=>h.getFlatColumns()),A(e,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:T(()=>[r.getAllFlatColumns()],d=>d.reduce((h,f)=>(h[f.id]=f,h),{}),A(e,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:T(()=>[r.getAllColumns(),r._getOrderColumnsFn()],(d,h)=>h(d.flatMap(f=>f.getLeafColumns())),A(e,"debugColumns","getAllLeafColumns")),getColumn:d=>r._getAllFlatColumnsById()[d]};Object.assign(r,c);for(let d=0;d<r._features.length;d++){const h=r._features[d];h==null||h.createTable==null||h.createTable(r)}return r}function Mc(){return e=>T(()=>[e.options.data],t=>{const s={rows:[],flatRows:[],rowsById:{}},n=function(r,o,i){o===void 0&&(o=0);const a=[];for(let u=0;u<r.length;u++){const c=tl(e,e._getRowId(r[u],u,i),r[u],u,o,void 0,i?.id);if(s.flatRows.push(c),s.rowsById[c.id]=c,a.push(c),e.options.getSubRows){var l;c.originalSubRows=e.options.getSubRows(r[u],u),(l=c.originalSubRows)!=null&&l.length&&(c.subRows=n(c.originalSubRows,o+1,c))}}return a};return s.rows=n(t),s},A(e.options,"debugTable","getRowModel",()=>e._autoResetPageIndex()))}function Ec(){return e=>T(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,s)=>{if(!s.rows.length||!(t!=null&&t.length))return s;const n=e.getState().sorting,r=[],o=n.filter(l=>{var u;return(u=e.getColumn(l.id))==null?void 0:u.getCanSort()}),i={};o.forEach(l=>{const u=e.getColumn(l.id);u&&(i[l.id]={sortUndefined:u.columnDef.sortUndefined,invertSorting:u.columnDef.invertSorting,sortingFn:u.getSortingFn()})});const a=l=>{const u=l.map(c=>({...c}));return u.sort((c,d)=>{for(let f=0;f<o.length;f+=1){var h;const g=o[f],p=i[g.id],v=p.sortUndefined,m=(h=g?.desc)!=null?h:!1;let S=0;if(v){const C=c.getValue(g.id),I=d.getValue(g.id),y=C===void 0,R=I===void 0;if(y||R){if(v==="first")return y?-1:1;if(v==="last")return y?1:-1;S=y&&R?0:y?v:-v}}if(S===0&&(S=p.sortingFn(c,d,g.id)),S!==0)return m&&(S*=-1),p.invertSorting&&(S*=-1),S}return c.index-d.index}),u.forEach(c=>{var d;r.push(c),(d=c.subRows)!=null&&d.length&&(c.subRows=a(c.subRows))}),u};return{rows:a(s.rows),flatRows:r,rowsById:s.rowsById}},A(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function xc(e,t){return e?Dl(e)?w.createElement(e,t):e:null}function Dl(e){return kl(e)||typeof e=="function"||$l(e)}function kl(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function $l(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Pc(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[s]=w.useState(()=>({current:Nl(t)})),[n,r]=w.useState(()=>s.current.initialState);return s.current.setOptions(o=>({...o,...e,state:{...n,...e.state},onStateChange:i=>{r(i),e.onStateChange==null||e.onStateChange(i)}})),s.current}function De(e,t,s){let n=s.initialDeps??[],r,o=!0;function i(){var a,l,u;let c;s.key&&((a=s.debug)!=null&&a.call(s))&&(c=Date.now());const d=e();if(!(d.length!==n.length||d.some((f,g)=>n[g]!==f)))return r;n=d;let h;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(h=Date.now()),r=t(...d),s.key&&((u=s.debug)!=null&&u.call(s))){const f=Math.round((Date.now()-c)*100)/100,g=Math.round((Date.now()-h)*100)/100,p=g/16,v=(m,S)=>{for(m=String(m);m.length<S;)m=" "+m;return m};console.info(`%c⏱ ${v(g,5)} /${v(f,5)} ms`,`
|
|
5
5
|
font-size: .6rem;
|
|
6
6
|
font-weight: bold;
|
|
7
|
-
color: hsl(${Math.max(0,Math.min(120-120*p,120))}deg 100% 31%);`,s?.key)}return s?.onChange&&!(i&&s.skipInitialOnChange)&&s.onChange(r),i=!1,r}return o.updateDeps=a=>{n=a},o}function Qn(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var Bl=(e,t)=>Math.abs(e-t)<1.01,Ul=(e,t,s)=>{let n;return function(...r){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,r),s)}},Jn=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},Vl=e=>e,Gl=e=>{const t=Math.max(e.startIndex-e.overscan,0),s=Math.min(e.endIndex+e.overscan,e.count-1),n=[];for(let r=t;r<=s;r++)n.push(r);return n},Hl=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const r=o=>{const{width:a,height:l}=o;t({width:Math.round(a),height:Math.round(l)})};if(r(Jn(s)),!n.ResizeObserver)return()=>{};const i=new n.ResizeObserver(o=>{const a=()=>{const l=o[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){r({width:u.inlineSize,height:u.blockSize});return}}r(Jn(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(s,{box:"border-box"}),()=>{i.unobserve(s)}},Xn={passive:!0},Yn=typeof window>"u"?!0:"onscrollend"in window,jl=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let r=0;const i=e.options.useScrollendEvent&&Yn?()=>{}:Ul(n,()=>{t(r,!1)},e.options.isScrollingResetDelay),o=d=>()=>{const{horizontal:c,isRtl:h}=e.options;r=c?s.scrollLeft*(h&&-1||1):s.scrollTop,i(),t(r,d)},a=o(!0),l=o(!1);s.addEventListener("scroll",a,Xn);const u=e.options.useScrollendEvent&&Yn;return u&&s.addEventListener("scrollend",l,Xn),()=>{s.removeEventListener("scroll",a),u&&s.removeEventListener("scrollend",l)}},zl=(e,t,s)=>{if(t?.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},ql=(e,{adjustments:t=0,behavior:s},n)=>{var r,i;const o=e+t;(i=(r=n.scrollElement)==null?void 0:r.scrollTo)==null||i.call(r,{[n.options.horizontal?"left":"top"]:o,behavior:s})},Wl=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,s,n;return((n=(s=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:s.now)==null?void 0:n.call(s))??Date.now()},this.observer=(()=>{let t=null;const s=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(n=>{n.forEach(r=>{const i=()=>{const o=r.target,a=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(a)&&this.resizeItem(a,this.options.measureElement(o,r,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var n;(n=s())==null||n.disconnect(),t=null},observe:n=>{var r;return(r=s())==null?void 0:r.observe(n,{box:"border-box"})},unobserve:n=>{var r;return(r=s())==null?void 0:r.unobserve(n)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([s,n])=>{typeof n>"u"&&delete t[s]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Vl,rangeExtractor:Gl,onChange:()=>{},measureElement:zl,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var s,n;(n=(s=this.options).onChange)==null||n.call(s,this,t)},this.maybeNotify=De(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const s=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==s){if(this.cleanup(),!s){this.maybeNotify();return}this.scrollElement=s,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(n=>{this.observer.observe(n)}),this.unsubs.push(this.options.observeElementRect(this,n=>{this.scrollRect=n,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(n,r)=>{this.scrollAdjustments=0,this.scrollDirection=r?this.getScrollOffset()<n?"forward":"backward":null,this.scrollOffset=n,this.isScrolling=r,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,s)=>{const n=new Map,r=new Map;for(let i=s-1;i>=0;i--){const o=t[i];if(n.has(o.lane))continue;const a=r.get(o.lane);if(a==null||o.end>a.end?r.set(o.lane,o):o.end<a.end&&n.set(o.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((i,o)=>i.end===o.end?i.index-o.index:i.end-o.end)[0]:void 0},this.getMeasurementOptions=De(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,s,n,r,i,o,a)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:s,scrollMargin:n,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a}),{key:!1}),this.getMeasurements=De(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:s,scrollMargin:n,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a},l)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const h of this.laneAssignments.keys())h>=t&&this.laneAssignments.delete(h);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(h=>{this.itemSizeCache.set(h.key,h.size)}));const u=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const d=this.measurementsCache.slice(0,u),c=new Array(o).fill(void 0);for(let h=0;h<u;h++){const f=d[h];f&&(c[f.lane]=h)}for(let h=u;h<t;h++){const f=r(h),g=this.laneAssignments.get(h);let p,v;const m=a==="estimate"||l.has(f);if(g!==void 0&&this.options.lanes>1){p=g;const y=c[p],R=y!==void 0?d[y]:void 0;v=R?R.end+this.options.gap:s+n}else{const y=this.options.lanes===1?d[h-1]:this.getFurthestMeasurement(d,h);v=y?y.end+this.options.gap:s+n,p=y?y.lane:h%this.options.lanes,this.options.lanes>1&&m&&this.laneAssignments.set(h,p)}const S=l.get(f),C=typeof S=="number"?S:this.options.estimateSize(h),I=v+C;d[h]={index:h,start:v,size:C,end:I,key:f,lane:p},c[p]=h}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=De(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,s,n,r)=>this.range=t.length>0&&s>0?Kl({measurements:t,outerSize:s,scrollOffset:n,lanes:r}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=De(()=>{let t=null,s=null;const n=this.calculateRange();return n&&(t=n.startIndex,s=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,s]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,s]},(t,s,n,r,i)=>r===null||i===null?[]:t({startIndex:r,endIndex:i,overscan:s,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const s=this.options.indexAttribute,n=t.getAttribute(s);return n?parseInt(n,10):(console.warn(`Missing attribute name '${s}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var s;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const n=this.scrollState.index??((s=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:s.index);if(n!==void 0&&this.range){const r=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,n-r),o=Math.min(this.options.count-1,n+r);return t>=i&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((i,o)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(o))});return}const s=this.indexFromElement(t),n=this.options.getItemKey(s),r=this.elementsCache.get(n);r!==t&&(r&&this.observer.unobserve(r),this.observer.observe(t),this.elementsCache.set(n,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(s)&&this.resizeItem(s,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,s)=>{var n;const r=this.measurementsCache[t];if(!r)return;const i=s-(this.itemSizeCache.get(r.key)??r.size);i!==0&&(((n=this.scrollState)==null?void 0:n.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,i,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,s)),this.notify(!1))},this.getVirtualItems=De(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,s)=>{const n=[];for(let r=0,i=t.length;r<i;r++){const o=s[t[r]];n.push(o)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const s=this.getMeasurements();if(s.length!==0)return Qn(s[hi(0,s.length-1,n=>Qn(s[n]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,s,n=0)=>{if(!this.scrollElement)return 0;const r=this.getSize(),i=this.getScrollOffset();s==="auto"&&(s=t>=i+r?"end":"start"),s==="center"?t+=(n-r)/2:s==="end"&&(t-=r);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,s="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[t];if(!i)return;if(s==="auto")if(i.end>=r+n-this.options.scrollPaddingEnd)s="end";else if(i.start<=r+this.options.scrollPaddingStart)s="start";else return[r,s];if(s==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),s];const o=s==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,s,i.size),s]},this.scrollToOffset=(t,{align:s="start",behavior:n="auto"}={})=>{const r=this.getOffsetForAlignment(t,s),i=this.now();this.scrollState={index:null,align:s,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:s="auto",behavior:n="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const r=this.getOffsetForIndex(t,s);if(!r)return;const[i,o]=r,a=this.now();this.scrollState={index:t,align:o,behavior:n,startedAt:a,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:s="auto"}={})=>{const n=this.getScrollOffset()+t,r=this.now();this.scrollState={index:null,align:"start",behavior:s,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const s=this.getMeasurements();let n;if(s.length===0)n=this.options.paddingStart;else if(this.options.lanes===1)n=((t=s[s.length-1])==null?void 0:t.end)??0;else{const r=Array(this.options.lanes).fill(null);let i=s.length-1;for(;i>=0&&r.some(o=>o===null);){const o=s[i];r[o.lane]===null&&(r[o.lane]=o.end),i--}n=Math.max(...r.filter(o=>o!==null))}return Math.max(n-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:s,behavior:n})=>{this.options.scrollToFn(t,{behavior:n,adjustments:s},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const e=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,t=e?e[0]:this.scrollState.lastTargetOffset,s=1,n=t!==this.scrollState.lastTargetOffset;if(!n&&Bl(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=s){this.scrollState=null;return}}else this.scrollState.stableFrames=0,n&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior="auto",this._scrollToOffset(t,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}},hi=(e,t,s,n)=>{for(;e<=t;){const r=(e+t)/2|0,i=s(r);if(i<n)e=r+1;else if(i>n)t=r-1;else return r}return e>0?e-1:0};function Kl({measurements:e,outerSize:t,scrollOffset:s,lanes:n}){const r=e.length-1,i=l=>e[l].start;if(e.length<=n)return{startIndex:0,endIndex:r};let o=hi(0,r,i,s),a=o;if(n===1)for(;a<r&&e[a].end<s+t;)a++;else if(n>1){const l=Array(n).fill(0);for(;a<r&&l.some(d=>d<s+t);){const d=e[a];l[d.lane]=d.end,a++}const u=Array(n).fill(s+t);for(;o>=0&&u.some(d=>d>=s);){const d=e[o];u[d.lane]=d.start,o--}o=Math.max(0,o-o%n),a=Math.min(r,a+(n-1-a%n))}return{startIndex:o,endIndex:a}}var Zn=typeof document<"u"?w.useLayoutEffect:w.useEffect;function Ql({useFlushSync:e=!0,...t}){const s=w.useReducer(()=>({}),{})[1],n={...t,onChange:(i,o)=>{var a;e&&o?(0,Zr.flushSync)(s):s(),(a=t.onChange)==null||a.call(t,i,o)}},[r]=w.useState(()=>new Wl(n));return r.setOptions(n),Zn(()=>r._didMount(),[]),Zn(()=>r._willUpdate()),r}function xc(e){return Ql({observeElementRect:Hl,observeElementOffset:jl,scrollToFn:ql,...e})}function er(e){const t={};for(const[s,n]of Object.entries(e))s!=="$schema"&&(t[s]=n);return t}function fi(e){return(typeof e=="object"||typeof e=="function")&&e!==null}function gi(e){if(!fi(e)||!("~standard"in e))return!1;const t=e["~standard"];return typeof t!="object"||t===null||!("version"in t)||t.version!==1||!("jsonSchema"in t)||typeof t.jsonSchema!="object"||t.jsonSchema===null||!("input"in t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function Ut(e){return fi(e)&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"version"in e["~standard"]&&e["~standard"].version===1&&"validate"in e["~standard"]&&typeof e["~standard"].validate=="function"}function Jl(e){return Object.keys(e).length>0?e:void 0}function Et(e,t=[]){const s={...e},n={};if(s.type==="object"&&s.properties){const r={...s.properties},i=Object.keys(r),o={};for(const a of i){const l=r[a];if(!l)continue;const u=!t.includes(a);let d=!1,c;if(l.type==="object"&&l.properties){const h=Et(l,l.required||[]);r[a]=u?{...h.schema,type:["object","null"]}:h.schema,d=u,c=h.nullWidening}else if(l.type==="array"&&l.items){const h=Array.isArray(l.items)?l.items[0]:l.items,f=h?Et(h,h.required||[]):void 0;r[a]={...l,items:f?f.schema:l.items,...u?{type:["array","null"]}:{}},d=u,c=f?.nullWidening?{items:f.nullWidening}:void 0}else u&&(l.type&&!Array.isArray(l.type)?(r[a]={...l,type:[l.type,"null"]},d=!0):Array.isArray(l.type)&&!l.type.includes("null")&&(r[a]={...l,type:[...l.type,"null"]},d=!0));(d||c)&&(o[a]={...c??{},...d?{widened:!0}:{}})}s.properties=r,s.required=i,s.additionalProperties=!1,Object.keys(o).length>0&&(n.properties=o)}if(s.type==="array"&&s.items){const r=Array.isArray(s.items)?s.items[0]:s.items;if(r){const i=Et(r,r.required||[]);s.items=i.schema,i.nullWidening&&(n.items=i.nullWidening)}}return{schema:s,nullWidening:Jl(n)}}function Xl(e){if(gi(e)){const t=er(e["~standard"].jsonSchema.input({target:"draft-07"}));return"properties"in t&&!t.type&&(t.type="object"),t.type==="object"&&!("properties"in t)&&(t.properties={}),t.type==="object"&&!("required"in t)&&(t.required=[]),t}if(Ut(e))throw new Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e!="object"?e:er(e)}function As(e,t={}){if(!e)return;const{forStructuredOutput:s=!1}=t;if(!s&&!gi(e)&&!Ut(e))return e;const n=Xl(e);return!n||typeof n!="object"||!s?n:Et(n,n.required||[]).schema}var Yl=class extends Error{name="StandardSchemaValidationError";issues;constructor(e){super(`Validation failed: ${e.map(t=>t.message||"Validation failed").join(", ")}`),this.issues=e}};function Zl(e,t){if(!Ut(e))return t;const s=e["~standard"].validate(t);if(s instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!s.issues)return s.value;throw new Yl(s.issues)}var eu=new Set(["text","image","audio","video","document"]);function tu(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.type!="string"||!eu.has(t.type))return!1;if(t.type==="text")return typeof t.content=="string";const s=t.source;if(typeof s!="object"||s===null)return!1;const n=s;return typeof n.value!="string"?!1:n.type==="data"?typeof n.mimeType=="string":n.type==="url"}function su(e){return Array.isArray(e)&&e.length>0&&e.every(tu)}function pi(e){return typeof e=="string"||su(e)?e:JSON.stringify(e)}function nu(e){return e.type==="text"||e.type==="image"||e.type==="audio"||e.type==="video"||e.type==="document"}function ru(e){try{return JSON.stringify(e)}catch{return""}}function mi(e){return e.length===0?null:e.every(t=>t.type==="text")?e.map(t=>t.content).join("")||null:e}function tr(e){return e===null?"":typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.content).join("")}function iu(e){return e.role==="system"?[]:e.role!=="assistant"?[ou(e)]:lu(e)}function ou(e){const t=[];for(const s of e.parts)nu(s)&&t.push(s);return{role:e.role,content:mi(t)}}function sr(){return{contentParts:[],toolCalls:[]}}function au(e){return e.state==="input-complete"||e.state==="complete"||e.state==="approval-responded"||e.state==="error"||e.output!==void 0}function lu(e){const t=[];let s=sr(),n=[];const r=new Set;function i(){const o=mi(s.contentParts),a=o!==null,l=s.toolCalls.length>0;(a||l)&&(t.push({role:"assistant",content:o,...l&&{toolCalls:s.toolCalls},...n.length>0&&{thinking:n}}),n=[]),s=sr()}for(const o of e.parts)switch(o.type){case"text":case"image":case"audio":case"video":case"document":s.contentParts.push(o);break;case"tool-call":au(o)&&s.toolCalls.push({id:o.id,type:"function",function:{name:o.name,arguments:o.arguments},...o.metadata!==void 0&&{metadata:o.metadata}});break;case"tool-result":i(),(o.state==="complete"||o.state==="error")&&!r.has(o.toolCallId)&&(t.push({role:"tool",content:o.content,toolCallId:o.toolCallId}),r.add(o.toolCallId));break;case"thinking":o.content&&n.push({content:o.content,...o.signature&&{signature:o.signature}});break;case"structured-output":if(o.status==="complete"){const a=o.raw!==""?o.raw:o.data!==void 0?ru(o.data):"";a!==""&&s.contentParts.push({type:"text",content:a})}break}i();for(const o of e.parts)if(o.type==="tool-call"&&(o.output!==void 0&&!r.has(o.id)&&(t.push({role:"tool",content:pi(o.output),toolCallId:o.id}),r.add(o.id)),o.output===void 0&&o.state==="approval-responded"&&o.approval?.approved!==void 0&&!r.has(o.id))){const a=o.approval.approved;t.push({role:"tool",content:JSON.stringify({approved:a,...a&&{pendingExecution:!0},message:a?"User approved this action":"User denied this action"}),toolCallId:o.id}),r.add(o.id)}return t.length===0&&t.push({role:"assistant",content:null}),t}function Os(e,t){const s=[];if(e.role==="assistant"&&e.thinking?.length)for(const n of e.thinking)n.content&&s.push({type:"thinking",content:n.content,...n.signature&&{signature:n.signature}});if(e.role==="tool"&&e.toolCallId)s.push({type:"tool-result",toolCallId:e.toolCallId,content:tr(e.content),state:"complete"});else if(Array.isArray(e.content))for(const n of e.content)s.push(n);else{const n=tr(e.content);n&&s.push({type:"text",content:n})}if(e.toolCalls&&e.toolCalls.length>0)for(const n of e.toolCalls)s.push({type:"tool-call",id:n.id,name:n.function.name,arguments:n.function.arguments,state:"input-complete",...n.metadata!==void 0&&{metadata:n.metadata}});return{id:t||Se(),role:e.role==="tool"?"assistant":e.role,parts:s}}function uu(e){if("parts"in e)return{...e,id:e.id||Se()};const t=e.id||Se();switch(e.role){case"user":return{id:t,role:"user",parts:cu(e.content)};case"assistant":return Os({role:"assistant",content:e.content??null,...e.toolCalls&&{toolCalls:e.toolCalls}},t);case"tool":return Os({role:"tool",content:e.content,toolCallId:e.toolCallId},t);case"system":case"developer":return{id:t,role:"system",parts:e.content?[{type:"text",content:e.content}]:[]};case"reasoning":return{id:t,role:"assistant",parts:e.content?[{type:"thinking",content:e.content}]:[]};default:return{id:t,role:"assistant",parts:[]}}}function cu(e){if(typeof e=="string")return e?[{type:"text",content:e}]:[];const t=[];for(const s of e)s.type==="text"?t.push({type:"text",content:s.text}):s.type!=="binary"&&t.push(s);return t}function du(e,t){return"parts"in e?{...e,id:e.id||t(),createdAt:e.createdAt||new Date}:{...Os(e,t()),createdAt:new Date}}function Se(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function hu(e){const t=[];for(const s of e){const n=s.parts??[];if(s.role==="system"){t.push({...s,content:n.length>0?Ls(n):s.content??""});continue}if(s.role==="user"){t.push({...s,content:n.length>0?fu(n):s.content??""});continue}for(const o of n)o.type==="thinking"&&t.push({role:"reasoning",id:pu(s.id,o),content:o.content});const r=Ls(n),i=gu(n);t.push({...s,...r!==""&&{content:r},...i&&{toolCalls:i}});for(const o of n)o.type==="tool-result"&&t.push({role:"tool",id:mu(o.toolCallId),toolCallId:o.toolCallId,content:typeof o.content=="string"?o.content:JSON.stringify(o.content),...o.error!==void 0&&{error:o.error}})}return t}function Ls(e){const t=[];for(const s of e)s.type==="text"?t.push(s.content):s.type==="structured-output"&&s.status==="complete"&&s.raw!==""&&t.push(s.raw);return t.join("")}function fu(e){if(!e.some(s=>s.type==="image"||s.type==="audio"||s.type==="video"||s.type==="document"))return Ls(e);const t=[];for(const s of e)s.type==="text"?t.push({type:"text",text:s.content}):(s.type==="image"||s.type==="audio"||s.type==="video"||s.type==="document")&&t.push(s);return t}function gu(e){const t=[];for(const s of e)s.type==="tool-call"&&t.push({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments}});return t.length>0?t:void 0}function pu(e,t){return`${e}-reasoning-${t.id??vu(t.content)}`}function mu(e){return`tool-${e}`}function vu(e){let t=0;for(let s=0;s<e.length;s++)t=t*31+e.charCodeAt(s)|0;return Math.abs(t).toString(36)}var Su=class{shouldEmit(e,t){return!0}},nr=je((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),yu=je((e=>{var t=e&&e.__createBinding||(Object.create?(function(u,d,c,h){h===void 0&&(h=c);var f=Object.getOwnPropertyDescriptor(d,c);(!f||("get"in f?!d.__esModule:f.writable||f.configurable))&&(f={enumerable:!0,get:function(){return d[c]}}),Object.defineProperty(u,h,f)}):(function(u,d,c,h){h===void 0&&(h=c),u[h]=d[c]})),s=e&&e.__exportStar||function(u,d){for(var c in u)c!=="default"&&!Object.prototype.hasOwnProperty.call(d,c)&&t(d,u,c)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var n=nr();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return n.Allow}}),s(nr(),e);var r=class extends Error{};e.PartialJSON=r;var i=class extends Error{};e.MalformedJSON=i;function o(u,d=n.Allow.ALL){if(typeof u!="string")throw new TypeError(`expecting str, got ${typeof u}`);if(!u.trim())throw new Error(`${u} is empty`);return a(u.trim(),d)}e.parseJSON=o;var a=(u,d)=>{const c=u.length;let h=0;const f=y=>{throw new r(`${y} at position ${h}`)},g=y=>{throw new i(`${y} at position ${h}`)},p=()=>(I(),h>=c&&f("Unexpected end of input"),u[h]==='"'?v():u[h]==="{"?m():u[h]==="["?S():u.substring(h,h+4)==="null"||n.Allow.NULL&d&&c-h<4&&"null".startsWith(u.substring(h))?(h+=4,null):u.substring(h,h+4)==="true"||n.Allow.BOOL&d&&c-h<4&&"true".startsWith(u.substring(h))?(h+=4,!0):u.substring(h,h+5)==="false"||n.Allow.BOOL&d&&c-h<5&&"false".startsWith(u.substring(h))?(h+=5,!1):u.substring(h,h+8)==="Infinity"||n.Allow.INFINITY&d&&c-h<8&&"Infinity".startsWith(u.substring(h))?(h+=8,1/0):u.substring(h,h+9)==="-Infinity"||n.Allow._INFINITY&d&&1<c-h&&c-h<9&&"-Infinity".startsWith(u.substring(h))?(h+=9,-1/0):u.substring(h,h+3)==="NaN"||n.Allow.NAN&d&&c-h<3&&"NaN".startsWith(u.substring(h))?(h+=3,NaN):C()),v=()=>{const y=h;let R=!1;for(h++;h<c&&(u[h]!=='"'||R&&u[h-1]==="\\");)R=u[h]==="\\"?!R:!1,h++;if(u.charAt(h)=='"')try{return JSON.parse(u.substring(y,++h-Number(R)))}catch(b){g(String(b))}else if(n.Allow.STR&d)try{return JSON.parse(u.substring(y,h-Number(R))+'"')}catch{return JSON.parse(u.substring(y,u.lastIndexOf("\\"))+'"')}f("Unterminated string literal")},m=()=>{h++,I();const y={};try{for(;u[h]!=="}";){if(I(),h>=c&&n.Allow.OBJ&d)return y;const R=v();I(),h++;try{y[R]=p()}catch(b){if(n.Allow.OBJ&d)return y;throw b}I(),u[h]===","&&h++}}catch{if(n.Allow.OBJ&d)return y;f("Expected '}' at end of object")}return h++,y},S=()=>{h++;const y=[];try{for(;u[h]!=="]";)y.push(p()),I(),u[h]===","&&h++}catch{if(n.Allow.ARR&d)return y;f("Expected ']' at end of array")}return h++,y},C=()=>{if(h===0){u==="-"&&g("Not sure what '-' is");try{return JSON.parse(u)}catch(R){if(n.Allow.NUM&d)try{return JSON.parse(u.substring(0,u.lastIndexOf("e")))}catch{}g(String(R))}}const y=h;for(u[h]==="-"&&h++;u[h]&&",]}".indexOf(u[h])===-1;)h++;h==c&&!(n.Allow.NUM&d)&&f("Unterminated number literal");try{return JSON.parse(u.substring(y,h))}catch{u.substring(y,h)==="-"&&f("Not sure what '-' is");try{return JSON.parse(u.substring(y,u.lastIndexOf("e")))}catch(b){g(String(b))}}},I=()=>{for(;h<c&&`
|
|
8
|
-
\r `.includes(u[h]);)h++};return p()},l=o;e.parse=l})),Cu=yu(),Ru=class{parse(e){if(!(!e||e.trim()===""))try{return(0,Cu.parse)(e)}catch{return}}},vi=new Ru;function Iu(e){return vi.parse(e)}function wu(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type==="text"?r[r.length-1]={type:"text",content:s}:r.push({type:"text",content:s}),{...n,parts:r}})}function ls(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.find(l=>l.type==="tool-call"&&l.id===s.id),o=s.metadata??i?.metadata,a={type:"tool-call",id:s.id,name:s.name,arguments:s.arguments,state:s.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{metadata:o}};return i?r[r.indexOf(i)]=a:r.push(a),{...n,parts:r}})}function us(e,t,s,n,r,i){return e.map(o=>{if(o.id!==t)return o;const a=[...o.parts],l=a.findIndex(d=>d.type==="tool-result"&&d.toolCallId===s),u={type:"tool-result",toolCallId:s,content:n,state:r,...i&&{error:i}};return l>=0?a[l]=u:a.push(u),{...o,parts:a}})}function bu(e,t,s,n){return e.map(r=>{if(r.id!==t)return r;const i=[...r.parts],o=i.find(a=>a.type==="tool-call"&&a.id===s);if(o){const a=i.indexOf(o);i[a]={...o,state:"approval-requested",approval:{id:n,needsApproval:!0}}}return{...r,parts:i}})}function cs(e,t,s,n,r){return e.map(i=>{const o=[...i.parts],a=o.find(l=>l.type==="tool-call"&&l.id===t);if(a){const l=o.indexOf(a);o[l]={...a,output:r?{error:r}:s,state:n??(r?"error":"complete")}}return{...i,parts:o}})}function _u(e,t,s){return e.map(n=>{const r=[...n.parts],i=r.find(o=>o.type==="tool-call"&&o.approval?.id===t);if(i&&i.approval){const o=r.indexOf(i);r[o]={...i,approval:{...i.approval,approved:s},state:"approval-responded"}}return{...n,parts:r}})}function Mu(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.findIndex(c=>c.type==="structured-output"),o=i>=0?r[i]:null,a=(o?.raw??"")+s,l=Iu(a),u=l??o?.partial,d={type:"structured-output",status:"streaming",raw:a,...u!==void 0?{partial:u}:{},...o?.reasoning!==void 0?{reasoning:o.reasoning}:{}};return i>=0?r[i]=d:r.push(d),{...n,parts:r}})}function Eu(e,t,s,n,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(c=>c.type==="structured-output"),l=a>=0?o[a].raw:"";let u=n||l;if(u===""&&s!==void 0)try{u=JSON.stringify(s)}catch{}const d={type:"structured-output",status:"complete",data:s,partial:s,raw:u,...r!==void 0?{reasoning:r}:{}};return a>=0?o[a]=d:o.push(d),{...i,parts:o}})}function rr(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.findIndex(a=>a.type==="structured-output");if(i<0)return r.push({type:"structured-output",status:"error",raw:"",errorMessage:s}),{...n,parts:r};const o=r[i];return o.status==="complete"?n:(r[i]={...o,status:"error",errorMessage:s},{...n,parts:r})})}function ds(e,t,s,n,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(u=>u.type==="thinking"&&u.stepId===s),l={type:"thinking",content:n,stepId:s,...r&&{signature:r}};return a>=0?o[a]=l:o.push(l),{...i,parts:o}})}var xu=12,Pu=class Si{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;recording=null;recordingStartTime=0;constructor(t={}){this.chunkStrategy=t.chunkStrategy||new Su,this.events=t.events||{},this.jsonParser=t.jsonParser||vi,this.recordingEnabled=t.recording??!1,t.initialMessages&&(this.messages=[...t.initialMessages])}setMessages(t){this.messages=[...t],this.emitMessagesChange()}addUserMessage(t,s){const n=typeof t=="string"?[{type:"text",content:t}]:t.map(i=>i),r={id:s??Se(),role:"user",parts:n,createdAt:new Date};return this.messages=[...this.messages,r],this.emitMessagesChange(),r}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(t){this.prepareAssistantMessage();const{messageId:s}=this.ensureAssistantMessage(t);return this.pendingManualMessageId=s,s}getCurrentAssistantMessageId(){let t=null;for(const[s,n]of this.messageStates)n.role==="assistant"&&(t=s);return t}addToolResult(t,s,n){const r=this.messages.find(l=>l.parts.some(u=>u.type==="tool-call"&&u.id===t));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${t}`);return}let i=cs(this.messages,t,s,n?"error":void 0,n);const o=pi(s),a=n?"error":"complete";i=us(i,r.id,t,o,a,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(t,s){this.messages=_u(this.messages,t,s),this.emitMessagesChange()}toModelMessages(){const t=[];for(const s of this.messages)t.push(...iu(s));return t}getMessages(){return this.messages}areAllToolsComplete(){const t=this.messages.findLast(r=>r.role==="assistant");if(!t)return!0;const s=t.parts.filter(r=>r.type==="tool-call");if(s.length===0)return!0;const n=new Set(t.parts.filter(r=>r.type==="tool-result").map(r=>r.toolCallId));return s.every(r=>r.state==="complete"||r.state==="approval-responded"||r.output!==void 0&&!r.approval||n.has(r.id))}removeMessagesAfter(t){const s=new Set(this.messages.slice(0,t+1).map(n=>n.id));for(const n of this.structuredMessageIds)s.has(n)||this.structuredMessageIds.delete(n);for(const n of this.structuredOutputUpdateBatches.keys())s.has(n)||this.structuredOutputUpdateBatches.delete(n);for(const n of this.messageStates.keys())s.has(n)||this.messageStates.delete(n);for(const[n,r]of this.toolCallToMessage)s.has(r)||this.toolCallToMessage.delete(n);for(const n of this.activeMessageIds)s.has(n)||this.activeMessageIds.delete(n);this.messages=this.messages.slice(0,t+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(t){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(const s of t)this.processChunk(s);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(t){switch(this.recording&&this.recording.chunks.push({chunk:t,timestamp:Date.now(),index:this.recording.chunks.length}),t.type){case"TEXT_MESSAGE_START":this.handleTextMessageStartEvent(t);break;case"TEXT_MESSAGE_CONTENT":this.handleTextMessageContentEvent(t);break;case"TEXT_MESSAGE_END":this.handleTextMessageEndEvent(t);break;case"TOOL_CALL_START":this.handleToolCallStartEvent(t);break;case"TOOL_CALL_ARGS":this.handleToolCallArgsEvent(t);break;case"TOOL_CALL_END":this.handleToolCallEndEvent(t);break;case"RUN_FINISHED":this.handleRunFinishedEvent(t);break;case"RUN_ERROR":this.handleRunErrorEvent(t);break;case"STEP_FINISHED":this.handleStepFinishedEvent(t);break;case"MESSAGES_SNAPSHOT":this.handleMessagesSnapshotEvent(t);break;case"CUSTOM":this.handleCustomEvent(t);break;case"RUN_STARTED":this.handleRunStartedEvent(t);break;case"REASONING_START":case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"REASONING_MESSAGE_CONTENT":this.handleReasoningMessageContentEvent(t);break;case"TOOL_CALL_RESULT":this.handleToolCallResultEvent(t);break;case"STEP_STARTED":this.handleStepStartedEvent(t);break}}createMessageState(t,s){const n={id:t,role:s,totalTextContent:"",currentSegmentText:"",lastEmittedText:"",hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(t,n),n}getMessageState(t){return this.messageStates.get(t)}consumePendingThinkingStep(t){if(!this.pendingThinkingStepId)return;const s=this.pendingThinkingStepId;t.currentThinkingStepId=s,t.thinkingSteps.has(s)||(t.thinkingSteps.set(s,""),t.thinkingStepOrder.push(s)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){const t=Array.from(this.activeMessageIds).reverse();for(const s of t){const n=this.messageStates.get(s);if(n&&n.role==="assistant")return s}return null}ensureAssistantMessage(t){if(t){const o=this.getMessageState(t);if(o)return{messageId:t,state:o}}const s=this.getActiveAssistantMessageId();if(s){const o=this.getMessageState(s);if(o)return{messageId:s,state:o}}if(t){const o=this.messages.find(a=>a.id===t);if(o){const a=this.createMessageState(t,o.role);this.activeMessageIds.add(t);const l=o.parts.length>0?o.parts[o.parts.length-1]:null;return l&&l.type==="text"&&(a.currentSegmentText=l.content,a.lastEmittedText=l.content,a.totalTextContent=l.content),{messageId:t,state:a}}}const n=t||Se(),r={id:n,role:"assistant",parts:[],createdAt:new Date};this.messages=[...this.messages,r];const i=this.createMessageState(n,"assistant");return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}handleTextMessageStartEvent(t){const{messageId:s,role:n}=t,r=n==="user"||n==="system"?n:"assistant";if(this.pendingManualMessageId){const o=this.pendingManualMessageId;if(this.pendingManualMessageId=null,o!==s){this.messages=this.messages.map(l=>l.id===o?{...l,id:s}:l);const a=this.messageStates.get(o);a&&(a.id=s,this.messageStates.delete(o),this.messageStates.set(s,a)),this.activeMessageIds.delete(o),this.activeMessageIds.add(s)}this.messageStates.has(s)||(this.createMessageState(s,r),this.activeMessageIds.add(s)),this.emitMessagesChange();return}if(this.messages.find(o=>o.id===s)){this.activeMessageIds.add(s);const o=this.messageStates.get(s);o?o.hasToolCallsSinceTextStart&&(o.currentSegmentText!==o.lastEmittedText&&this.emitTextUpdateForMessage(s),o.currentSegmentText="",o.lastEmittedText="",o.hasToolCallsSinceTextStart=!1):this.createMessageState(s,r);return}const i={id:s,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(s,r),this.activeMessageIds.add(s),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(t){const{messageId:s}=t,n=this.getMessageState(s);n&&(n.isComplete||(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),this.completeAllToolCallsForMessage(s)))}handleMessagesSnapshotEvent(t){this.resetStreamState(),this.messages=t.messages.map(uu),this.emitMessagesChange()}handleTextMessageContentEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(t.messageId);if(this.completeAllToolCallsForMessage(s),this.structuredMessageIds.has(s)){let d=t.delta||"";if(d===""&&t.content!==void 0&&t.content!==""){const c=(this.messages.find(h=>h.id===s)?.parts.find(h=>h.type==="structured-output")??{raw:""}).raw;t.content.startsWith(c)?d=t.content.slice(c.length):c.startsWith(t.content)?d="":d=t.content}d!==""&&(this.messages=Mu(this.messages,s,d),n.totalTextContent+=d,this.queueStructuredOutputUpdate(s,d),this.emitMessagesChange());return}const r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(t,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),n.currentSegmentText="",n.lastEmittedText="",n.hasToolCallsSinceTextStart=!1);const i=n.currentSegmentText;let o=i;const a=t.delta||"";a!==""?o=i+a:t.content!==void 0&&t.content!==""&&(t.content.startsWith(i)?o=t.content:i.startsWith(t.content)?o=i:o=i+t.content);const l=o.slice(i.length);n.currentSegmentText=o,n.totalTextContent+=l;const u=t.delta||t.content||"";this.chunkStrategy.shouldEmit(u,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s)}handleToolCallStartEvent(t){const s=t.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(s??void 0);r.hasToolCallsSinceTextStart=!0;const i=t.toolCallId;if(!r.toolCalls.get(i)){const o="awaiting-input",a=t.toolCallName??t.toolName,l=t.metadata,u={id:t.toolCallId,name:a,arguments:"",state:o,parsedArguments:void 0,index:t.index??r.toolCalls.size,...l!==void 0&&{metadata:l}};r.toolCalls.set(i,u),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=ls(this.messages,n,{id:t.toolCallId,name:a,arguments:"",state:o,...l!==void 0&&{metadata:l}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,t.toolCallId,o,"")}}handleToolCallArgsEvent(t){const s=t.toolCallId,n=this.toolCallToMessage.get(s);if(!n)return;const r=this.getMessageState(n);if(!r)return;const i=r.toolCalls.get(s);if(!i)return;const o=i.state==="awaiting-input";i.arguments+=t.delta||"",o&&t.delta&&(i.state="input-streaming"),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=ls(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(t){const s=this.toolCallToMessage.get(t.toolCallId);if(!s)return;const n=this.getMessageState(s);if(!n)return;const r=n.toolCalls.get(t.toolCallId);if(r&&r.state!=="input-complete"){t.input!==void 0&&!r.arguments&&(r.arguments=JSON.stringify(t.input));const i=n.toolCallOrder.indexOf(t.toolCallId);this.completeToolCall(s,i,r),t.input!==void 0&&(r.parsedArguments=t.input)}if(t.result){let i;if(Array.isArray(t.result))i=t.result;else try{i=JSON.parse(t.result)}catch{i=t.result}this.messages=cs(this.messages,t.toolCallId,i,t.state==="output-error"?"error":void 0);const o=t.state==="output-error"?"error":"complete";this.messages=us(this.messages,s,t.toolCallId,t.result,o,o==="error"?this.extractToolResultError(i):void 0),this.emitMessagesChange()}}extractToolResultError(t){return t&&typeof t=="object"&&"error"in t&&typeof t.error=="string"?t.error:typeof t=="string"?t:"Tool execution failed"}handleToolCallResultEvent(t){const s=this.toolCallToMessage.get(t.toolCallId);if(!s)return;let n;try{n=JSON.parse(t.content)}catch{n=t.content}this.messages=cs(this.messages,t.toolCallId,n,t.state==="output-error"?"error":void 0);const r=t.state==="output-error"?"error":"complete";this.messages=us(this.messages,s,t.toolCallId,t.content,r,r==="error"?this.extractToolResultError(n):void 0),this.emitMessagesChange()}handleRunStartedEvent(t){this.activeRuns.add(t.runId)}handleRunFinishedEvent(t){this.finishReason=t.finishReason??null,this.activeRuns.delete(t.runId),this.activeRuns.size===0&&(this.isDone=!0,this.completeAllToolCalls(),this.finalizeStream())}handleRunErrorEvent(t){this.hasError=!0;const s="runId"in t&&typeof t.runId=="string"?t.runId:void 0;s?this.activeRuns.delete(s):this.activeRuns.clear();const{messageId:n}=this.ensureAssistantMessage(),r=t.message||t.error?.message||"An error occurred";!t.message&&!t.error?.message&&console.error("[StreamProcessor] RUN_ERROR with no message; original chunk:",t),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=rr(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,"error"),this.emitMessagesChange());const i=new Error(r),o=t.code??t.error?.code;o!==void 0&&Object.assign(i,{code:o}),t.rawEvent!==void 0&&Object.assign(i,{rawEvent:t.rawEvent}),this.events.onError?.(i)}handleStepStartedEvent(t){const s=t.stepId??Se(),n=this.getActiveAssistantMessageId();if(n){const r=this.getMessageState(n);if(r){r.currentThinkingStepId=s,r.thinkingSteps.has(s)||(r.thinkingSteps.set(s,""),r.thinkingStepOrder.push(s)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=s}handleStepFinishedEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);if(n.hasSeenReasoningEvents){if(t.signature){const a=n.currentThinkingStepId??t.stepId;if(!a)return;const l=n.thinkingSteps.get(a);l!==void 0&&(n.thinkingStepSignatures.set(a,t.signature),this.messages=ds(this.messages,s,a,l,t.signature),this.emitMessagesChange())}return}this.consumePendingThinkingStep(n);const r=n.currentThinkingStepId??t.stepId??Se();n.thinkingSteps.has(r)||(n.thinkingSteps.set(r,""),n.thinkingStepOrder.push(r),n.currentThinkingStepId=r);const i=n.thinkingSteps.get(r)??"";let o=i;t.delta&&t.delta!==""?o=i+t.delta:t.content&&t.content!==""&&(t.content.startsWith(i)?o=t.content:i.startsWith(t.content)?o=i:o=i+t.content),n.thinkingSteps.set(r,o),t.signature&&n.thinkingStepSignatures.set(r,t.signature),this.messages=ds(this.messages,s,r,o,n.thinkingStepSignatures.get(r)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(s,r,o)}handleReasoningMessageContentEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;const r=t.delta||"";this.consumePendingThinkingStep(n);const i=n.currentThinkingStepId??t.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,""),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);const o=(n.thinkingSteps.get(i)??"")+r;n.thinkingSteps.set(i,o),this.messages=ds(this.messages,s,i,o,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(s,i,o)}handleCustomEvent(t){const s=this.getActiveAssistantMessageId();if(t.name==="structured-output.start"&&t.value){const n=t.value.messageId??s;n&&(this.ensureAssistantMessage(n),this.structuredMessageIds.add(n),this.structuredOutputUpdateBatches.delete(n),this.events.onStructuredOutputChange?.({phase:"start",messageId:n,status:"streaming",raw:""}));return}if(t.name==="structured-output.complete"&&t.value){const n=t.value,r=n.messageId??s;r&&(this.flushStructuredOutputUpdate(r),this.messages=Eu(this.messages,r,n.object,n.raw??"",n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,"complete"),this.emitMessagesChange())}if(t.name==="tool-input-available"&&t.value){const{toolCallId:n,toolName:r,input:i}=t.value;this.events.onToolCall?.({toolCallId:n,toolName:r,input:i});return}if(t.name==="approval-requested"&&t.value){const{toolCallId:n,toolName:r,input:i,approval:o}=t.value,a=s??this.toolCallToMessage.get(n);a&&(this.messages=bu(this.messages,a,n,o.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:o.id});return}if(t.name==="ui-resource"&&t.value){const n=t.value,r=this.toolCallToMessage.get(n.toolCallId)??s;if(r){const i={type:"ui-resource",resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(o=>o.id===r?{...o,parts:[...o.parts,i]}:o),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){const n=t.value&&typeof t.value=="object"?t.value.toolCallId:void 0;this.events.onCustomEvent(t.name,t.value,{toolCallId:n})}}isNewTextSegment(t,s){return t.content!==void 0&&(t.content.length<s.length||!t.content.startsWith(s)&&!s.startsWith(t.content))}completeAllToolCalls(){for(const t of this.activeMessageIds)this.completeAllToolCallsForMessage(t)}completeAllToolCallsForMessage(t){const s=this.getMessageState(t);s&&s.toolCalls.forEach((n,r)=>{if(n.state!=="input-complete"){const i=s.toolCallOrder.indexOf(r);this.completeToolCall(t,i,n)}})}completeToolCall(t,s,n){n.state="input-complete",n.parsedArguments=this.jsonParser.parse(n.arguments),!this.isToolCallPartErrored(n.id)&&(this.messages=ls(this.messages,t,{id:n.id,name:n.name,arguments:n.arguments,state:"input-complete",...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(t,n.id,"input-complete",n.arguments))}isToolCallPartErrored(t){return this.messages.some(s=>s.parts.some(n=>n.type==="tool-call"&&n.id===t&&n.state==="error"))}emitTextUpdateForMessage(t){const s=this.getMessageState(t);s&&(s.lastEmittedText=s.currentSegmentText,this.messages=wu(this.messages,t,s.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(t,s.currentSegmentText))}queueStructuredOutputUpdate(t,s){const n=this.structuredOutputUpdateBatches.get(t),r={delta:`${n?.delta??""}${s}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(t,r),r.chunkCount>=xu&&this.flushStructuredOutputUpdate(t)}flushStructuredOutputUpdate(t){const s=this.structuredOutputUpdateBatches.get(t);!s||s.chunkCount===0||(this.structuredOutputUpdateBatches.delete(t),this.emitStructuredOutputChange(t,"update",s.delta))}emitStructuredOutputChange(t,s,n){const r=this.messages.find(i=>i.id===t)?.parts.find(i=>i.type==="structured-output");r&&this.events.onStructuredOutputChange?.({phase:s,messageId:t,status:r.status,raw:r.raw,...r.partial!==void 0?{partial:r.partial}:{},...r.data!==void 0?{data:r.data}:{},...r.reasoning!==void 0?{reasoning:r.reasoning}:{},...r.errorMessage!==void 0?{errorMessage:r.errorMessage}:{},...n!==void 0?{delta:n}:{}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){let t;for(const s of this.activeMessageIds){const n=this.getMessageState(s);if(!n)continue;this.completeAllToolCallsForMessage(s),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),n.isComplete=!0;const r=this.messages.find(i=>i.id===s);r&&r.role==="assistant"&&(t=r)}for(const s of this.structuredMessageIds)this.flushStructuredOutputUpdate(s),this.messages=rr(this.messages,s,"Stream ended without structured-output.complete"),this.emitStructuredOutputChange(s,"error");if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),t&&!this.hasError&&this.isWhitespaceOnlyMessage(t)){this.messages=this.messages.filter(s=>s.id!==t.id),this.emitMessagesChange();return}t&&this.events.onStreamEnd?.(t)}getCompletedToolCalls(){const t=[];for(const s of this.messageStates.values())for(const n of s.toolCalls.values())n.state==="input-complete"&&t.push({id:n.id,type:"function",function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return t}getResult(){const t=this.getCompletedToolCalls();let s="",n="";for(const r of this.messageStates.values()){s+=r.totalTextContent;for(const i of r.thinkingStepOrder)n+=r.thinkingSteps.get(i)??""}return{content:s,thinking:n||void 0,toolCalls:t.length>0?t:void 0,finishReason:this.finishReason}}getState(){let t="",s="";const n=new Map,r=[];for(const i of this.messageStates.values()){t+=i.totalTextContent;for(const o of i.thinkingStepOrder)s+=i.thinkingSteps.get(o)??"";for(const[o,a]of i.toolCalls)n.set(o,a);r.push(...i.toolCallOrder)}return{content:t,thinking:s,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:"1.0",timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(t){return t.parts.length===0?!1:t.parts.every(s=>s.type==="text"&&s.content.trim()==="")}static async replay(t,s){return new Si(s).process(Tu(t))}};function Tu(e){return{async*[Symbol.asyncIterator](){for(const{chunk:t}of e.chunks)yield t}}}var Nt=(e=>(e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e))(Nt||{}),Au=class{#t=!0;#e;#s;#n;#i;#r;#o;#a;#f=0;#l=5;#c=!1;#d=!1;#u=null;#h=()=>{this.debugLog("Connected to event bus"),this.#r=!0,this.#c=!1,this.debugLog("Emitting queued events",this.#i),this.#i.forEach(e=>this.emitEventToBus(e)),this.#i=[],this.stopConnectLoop(),this.#s().removeEventListener("tanstack-connect-success",this.#h)};#g=()=>{if(this.#f<this.#l){this.#f++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#s().removeEventListener("tanstack-connect",this.#g),this.#d=!0,this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};#p=()=>{this.#c||(this.#c=!0,this.#s().addEventListener("tanstack-connect-success",this.#h),this.#g())};constructor({pluginId:e,debug:t=!1,enabled:s=!0,reconnectEveryMs:n=300}){this.#e=e,this.#t=s,this.#s=this.getGlobalTarget,this.#n=t,this.debugLog(" Initializing event subscription for plugin",this.#e),this.#i=[],this.#r=!1,this.#d=!1,this.#o=null,this.#a=n}startConnectLoop(){this.#o!==null||this.#r||(this.debugLog(`Starting connect loop (every ${this.#a}ms)`),this.#o=setInterval(this.#g,this.#a))}stopConnectLoop(){this.#c=!1,this.#o!==null&&(clearInterval(this.#o),this.#o=null,this.#i=[],this.debugLog("Stopped connect loop"))}debugLog(...e){this.#n&&console.log(`🌴 [tanstack-devtools:${this.#e}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;const e=typeof EventTarget<"u"?new EventTarget:void 0;return typeof e>"u"||typeof e.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog("Using new EventTarget as fallback"),e)}getPluginId(){return this.#e}dispatchCustomEventShim(e,t){try{const s=new Event(e,{detail:t});this.#s().dispatchEvent(s)}catch{this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(e,t){try{this.#s().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog("Emitting event to client bus",e),this.dispatchCustomEvent("tanstack-dispatch-event",e)}createEventPayload(e,t){return{type:`${this.#e}:${e}`,payload:t,pluginId:this.#e}}emit(e,t){if(!this.#t){this.debugLog("Event bus client is disabled, not emitting event",e,t);return}if(this.#u&&(this.debugLog("Emitting event to internal event target",e,t),this.#u.dispatchEvent(new CustomEvent(`${this.#e}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#d){this.debugLog("Previously failed to connect, not emitting to bus");return}if(!this.#r){this.debugLog("Bus not available, will be pushed as soon as connected"),this.#i.push(this.createEventPayload(e,t)),typeof CustomEvent<"u"&&!this.#c&&(this.#p(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,s){const n=s?.withEventTarget??!1,r=`${this.#e}:${e}`;if(n&&(this.#u||(this.#u=new EventTarget),this.#u.addEventListener(r,o=>{t(o.detail)})),!this.#t)return this.debugLog("Event bus client is disabled, not registering event",r),()=>{};const i=o=>{this.debugLog("Received event from bus",o.detail),t(o.detail)};return this.#s().addEventListener(r,i),this.debugLog("Registered event to bus",r),()=>{n&&this.#u?.removeEventListener(r,i),this.#s().removeEventListener(r,i)}}onAll(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=s=>{const n=s.detail;e(n)};return this.#s().addEventListener("tanstack-devtools-global",t),()=>this.#s().removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=s=>{const n=s.detail;this.#e&&n.pluginId!==this.#e||e(n)};return this.#s().addEventListener("tanstack-devtools-global",t),()=>this.#s().removeEventListener("tanstack-devtools-global",t)}};function Ou(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():Math.random().toString(36).slice(2)}var Ct;function ir(){return Ct!==void 0||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__=Ou()),Ct=globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__),Ct}var Lu=0;function oe(e){return e==null||e===""?"missing":`value-${encodeURIComponent(String(e))}`}function Fs(e){const t=e.runtimeId??ir(),s=e.eventId&&e.eventId.length>0?e.eventId:[e.source,e.eventType,oe(t),oe(e.clientId),oe(e.requestId),oe(e.streamId),oe(e.hookId),oe(e.threadId),oe(e.runId),oe(e.messageId),oe(e.toolCallId),oe(e.sequence),e.timestamp,ir(),Lu++].join(":");return{...e,runtimeId:t,eventId:s}}var Fu=class extends Au{constructor(){super({pluginId:"tanstack-ai-devtools"})}},or=Symbol.for("tanstack.ai.devtools.eventClient");function Nu(){const e=globalThis,t=e[or];if(t)return t;const s=new Fu;return e[or]=s,s}var ut=Nu();function ke(e,t){ut.emit(e,t)}var yi=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent("client:created",{initialMessageCount:e})}loadingChanged(e){this.emitEvent("client:loading:changed",{isLoading:e})}errorChanged(e){this.emitEvent("client:error:changed",{error:e})}textUpdated(e,t,s,n){this.emitEvent("text:chunk:content",{streamId:e,messageId:t,content:s,...n})}toolCallStateChanged(e,t,s,n,r,i,o){this.emitEvent("tools:call:updated",{streamId:e,messageId:t,toolCallId:s,toolName:n,state:r,arguments:i,...o})}thinkingUpdated(e,t,s,n,r){this.emitEvent("text:chunk:thinking",{streamId:e,messageId:t,content:s,delta:n,...r})}structuredOutputChanged(e,t,s,n,r){this.emitEvent(e,{streamId:t,messageId:s,...n,...r})}approvalRequested(e,t,s,n,r,i,o){this.emitEvent("tools:approval:requested",{streamId:e,messageId:t,toolCallId:s,toolName:n,input:r,approvalId:i,...o})}messageAppended(e,t,s){const n=e.parts.filter(r=>r.type==="text").map(r=>r.content).join(" ");this.emitEvent("text:message:created",{streamId:t,messageId:e.id,role:e.role,content:n,parts:e.parts,...s})}messageSent(e,t){const s=typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.content).join("");this.emitEvent("text:message:created",{messageId:e,role:"user",content:s,...Array.isArray(t)&&{parts:t}}),this.emitEvent("text:message:user",{messageId:e,role:"user",content:s,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent("client:reloaded",{fromMessageIndex:e})}stopped(){this.emitEvent("client:stopped")}messagesCleared(){this.emitEvent("client:messages:cleared")}toolResultAdded(e,t,s,n,r){this.emitEvent("tools:result:added",{toolCallId:e,toolName:t,output:s,state:n,...r})}toolApprovalResponded(e,t,s,n){this.emitEvent("tools:approval:responded",{approvalId:e,toolCallId:t,approved:s,...n})}toolFixtureApplied(e){this.emitEvent("devtools:tool-fixture:applied",{...e})}},Du=class extends yi{emitEvent(e,t){const s=Date.now(),n=e.startsWith("text:")||e.startsWith("tools:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",r=e.startsWith("client:")||e.startsWith("tools:")||e.startsWith("text:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",i=n?"user-visible":"client-state",o={hookId:this.clientId,...typeof t?.threadId=="string"?{threadId:t.threadId}:{},...typeof t?.runId=="string"?{runId:t.runId}:{},...typeof t?.streamId=="string"?{streamId:t.streamId}:{},...typeof t?.messageId=="string"?{messageId:t.messageId}:{},...typeof t?.toolCallId=="string"?{toolCallId:t.toolCallId}:{}};if(r){const a=Fs({eventType:e,clientId:this.clientId,...o,source:"client",visibility:i,timestamp:s});ut.emit(e,{...t,...a})}else{const a=Fs({eventType:e,source:"client",visibility:"client-state",timestamp:s});ut.emit(e,{...t,...a})}}},ku=class extends yi{emitEvent(){}},$u=class{events;constructor(e){this.events=new ku(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,s,n){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return""}observeChunk(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Bu=e=>new $u(e),Ns=class extends Error{missingFeature;constructor(e){super(Uu(e)),this.name="UnsupportedResponseStreamError",this.missingFeature=e}};function Uu(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function Vu(e){if(!e.body)throw new Ns("Response.body");if(typeof e.body.getReader!="function")throw new Ns("Response.body.getReader");return e.body.getReader()}function Gu(){if(typeof globalThis.TextDecoder!="function")throw new Ns("TextDecoder");return new globalThis.TextDecoder}function Hu(e){if(!e.startsWith("data:"))return e;const t=e.slice(5);return t.startsWith(" ")?t.slice(1):t}var Ci=new WeakMap;function st(e){return"runId"in e&&typeof e.runId=="string"?e.runId:Ci.get(e)}var ju=class extends Error{constructor(){super("Stream ended with unterminated trailing data — connection was likely cut short."),this.name="StreamTruncatedError"}};function ar(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Rt(e,t){if(!e)throw new Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function zu(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((s,n)=>{t[n]=s}),t}return e}async function*qu(e,t){try{const s=Gu();let n="";for(;!t?.aborted;){const{done:r,value:i}=await e.read();if(r)break;n+=s.decode(i,{stream:!0});const o=n.split(`
|
|
9
|
-
`);n=o.pop()||"";for(const a of o)a.trim()&&(yield a)}if(n.trim()&&!t?.aborted)throw new ju}finally{e.releaseLock()}}async function*Ri(e,t){if(!e.ok)throw new Error(`HTTP error! status: ${e.status} ${e.statusText}`);const s=Vu(e);let n,r,i;for await(const o of qu(s,t)){if(o.startsWith(":")||o.startsWith("event:")||o.startsWith("id:")||o.startsWith("retry:"))continue;const a=Hu(o);if(a==="[DONE]"){yield{type:Nt.RUN_FINISHED,threadId:n??"",runId:r??"",model:i??"",timestamp:Date.now(),finishReason:"stop"};return}const l=JSON.parse(a);"threadId"in l&&typeof l.threadId=="string"&&(n=l.threadId),"runId"in l&&typeof l.runId=="string"&&(r=l.runId),"model"in l&&typeof l.model=="string"&&(i=l.model),yield l}}function lr(e){if(!e)throw new Error("Connection adapter is required");const t="connect"in e,s="subscribe"in e,n="send"in e;if(t&&(s||n))throw new Error("Connection adapter must provide either connect or both subscribe and send, not both modes");if(s&&n)return{subscribe:e.subscribe.bind(e),send:e.send.bind(e)};if(!t)throw new Error("Connection adapter must provide either connect or both subscribe and send");let r=[],i=[];function o(a,l){l&&Ci.set(a,l);const u=i.shift();u?u(a):r.push(a)}return{subscribe(a){const l=r.splice(0),u=[];return r=l,i=u,(async function*(){for(;!a?.aborted;){let d;const c=l.shift();c!==void 0?d=c:d=await new Promise(h=>{const f=()=>h(null);u.push(g=>{a?.removeEventListener("abort",f),h(g)}),a?.addEventListener("abort",f,{once:!0})}),d!==null&&(yield d)}})()},async send(a,l,u,d){let c=!1,h,f;try{const g=e.connect(a,l,u,d);for await(const p of g)"threadId"in p&&typeof p.threadId=="string"&&(h=p.threadId),"runId"in p&&typeof p.runId=="string"&&(f=p.runId),(p.type==="RUN_FINISHED"||p.type==="RUN_ERROR")&&(c=!0),o(p,d?.runId);!u?.aborted&&!c&&o({type:Nt.RUN_FINISHED,threadId:Rt(h??d?.threadId,"threadId"),runId:Rt(f??d?.runId,"runId"),model:"connect-wrapper",timestamp:Date.now(),finishReason:"stop"})}catch(g){if(!u?.aborted&&!c){const p=g instanceof Error?g.message:"Unknown error in connect()";o({type:Nt.RUN_ERROR,threadId:Rt(h??d?.threadId,"threadId"),runId:Rt(f??d?.runId,"runId"),timestamp:Date.now(),message:p})}throw g}}}}function Wu(e,t,s,n){const r=hu(e),i={...n.body,...s?.forwardedProps??{},...t};return{threadId:s?.threadId??ar("thread"),runId:s?.runId??ar("run"),...s?.parentRunId!==void 0&&{parentRunId:s.parentRunId},state:{},messages:r,tools:s?.clientTools??[],context:[],forwardedProps:i,data:{...i}}}function Pc(e,t={}){return{async*connect(s,n,r,i){const o=typeof e=="function"?e():e,a=typeof t=="function"?await t():t,l={"Content-Type":"application/json",...zu(a.headers)},u=Wu(s,n,i,a),d=a.fetchClient??fetch,c=r||a.signal;yield*Ri(await d(o,{method:"POST",headers:l,body:JSON.stringify(u),credentials:a.credentials||"same-origin",...c?{signal:c}:{}}),r)}}}function Ku(e){return{async*connect(t,s,n,r){if(!n)throw new Error("fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.");if(!r)throw new Error("fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.");const i=await e({messages:t,data:s,threadId:r.threadId,runId:r.runId},{signal:n});i instanceof Response?yield*Ri(i,n):yield*Qu(i,n)}}}async function*Qu(e,t){if(t.aborted)return;const s=e[Symbol.asyncIterator](),n=new Promise(r=>{t.addEventListener("abort",()=>r({done:!0,value:void 0}),{once:!0})});try{for(;;){const r=await Promise.race([s.next(),n]);if(r.done)return;yield r.value}}finally{await s.return?.()}}function ur(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function cr(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function Ju(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var Xu=class{constructor(e,t,s){this.adapter=e,this.id=t,this.applyMessages=s}adapter;id;applyMessages;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;readInitial(){try{return this.adapter.getItem(this.id)}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;const t=this.messagesGeneration;e.then(s=>{Array.isArray(s)&&this.messagesGeneration===t&&this.applyMessages(s)}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.skipNextPersist){this.skipNextPersist=!1;return}const t=this.generation,s=[...e];this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,s)})}remove(){const e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){const t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{const t=e();if(t instanceof Promise){this.queuePending=!0;const s=t.catch(()=>{});this.queue=s,s.finally(()=>{this.queue===s&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){const t=st(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const s=ur(e);if(s&&this.clearedToolCallIds.has(s))return!0;const n=Ju(e);if(n&&this.clearedMessageIds.has(n))return s&&this.clearedToolCallIds.add(s),!0;const r=cr(e);return r?!!this.clearedMessageIds.has(r):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){const e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){const t=cr(e);t&&this.clearedMessageIds.add(t);const s=ur(e);s&&this.clearedToolCallIds.add(s)}isRunlessChunkFromIgnoredRun(e){return st(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type==="TEXT_MESSAGE_START"||e.type==="TEXT_MESSAGE_CONTENT"||e.type==="TOOL_CALL_START"||e.type==="TOOL_CALL_ARGS"||e.type==="TOOL_CALL_END"||e.type==="TOOL_CALL_RESULT"||e.type==="MESSAGES_SNAPSHOT"||e.type==="RUN_ERROR"}};function dr(e){const{connection:t,fetcher:s}=e;if(t&&s)throw new Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(s)return Ku(s);throw new Error("ChatClient: either `connection` or `fetcher` is required.")}var Yu=class{processor;connection;uniqueId;threadId;persistor;currentRunId=null;bodyOption={};forwardedPropsOption={};context=void 0;pendingMessageBody=void 0;isLoading=!1;isSubscribed=!1;error=void 0;status="ready";connectionStatus="disconnected";abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;errorReportedGeneration=null;streamGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;devtoolsMounted=!1;callbacksRef;constructor(e){if(this.uniqueId=e.id||this.generateUniqueId("chat"),this.threadId=e.threadId||this.generateUniqueId("thread"),e.persistence&&(this.persistor=new Xu(e.persistence,this.uniqueId,n=>this.processor.setMessages(n))),this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.context=e.context,this.connection=lr(dr(e)),this.clientToolsRef={current:new Map},e.tools)for(const n of e.tools)this.clientToolsRef.current.set(n.name,n);this.devtoolsBridge=(e.devtoolsBridgeFactory??Bu)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}};const t=this.persistor?.readInitial(),s=Array.isArray(t)?t:e.initialMessages;this.processor=new Pu({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...s?{initialMessages:s}:{},events:{onMessagesChange:n=>{this.persistor?.notifyMessagesChanged(n),this.callbacksRef.current.onMessagesChange(n)},onStreamStart:()=>{this.setStatus("streaming");const n=this.processor.getCurrentAssistantMessageId();if(!n)return;const r=this.processor.getMessages().find(i=>i.id===n);r&&(this.currentMessageId=r.id,this.events.messageAppended(r,this.currentStreamId||void 0))},onStreamEnd:n=>{this.callbacksRef.current.onFinish(n),this.setStatus("ready"),this.resolveProcessing()},onError:n=>{this.reportStreamError(n)},onTextUpdate:(n,r)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,n,r)},onThinkingUpdate:(n,r)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,n,r,void 0)},onStructuredOutputChange:n=>{const r=this.devtoolsBridge.resolveStreamId(),i=n.phase==="start"?"structured-output:started":n.phase==="complete"?"structured-output:completed":n.phase==="error"?"structured-output:errored":"structured-output:updated";this.currentMessageId=n.messageId,this.events.structuredOutputChanged(i,r,n.messageId,{status:n.status,raw:n.raw,...n.partial!==void 0?{partial:n.partial}:{},...n.data!==void 0?{data:n.data}:{},...n.reasoning!==void 0?{reasoning:n.reasoning}:{},...n.errorMessage!==void 0?{errorMessage:n.errorMessage}:{},...n.delta!==void 0?{delta:n.delta}:{}})},onToolCallStateChange:(n,r,i,o)=>{const a=this.processor.getMessages().find(l=>l.id===n)?.parts.find(l=>l.type==="tool-call"&&l.id===r)?.name||"unknown";this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,n,r,a,i,o)},onToolCall:n=>{const r=(this.activeClientTools??this.clientToolsRef.current).get(n.toolName),i=r?.execute;if(i){const o=this.devtoolsBridge.getCurrentRunEventContext(),a=(async()=>{try{const l=this.activeClientTools===null?this.context:this.activeContext,u=await i(n.input,{toolCallId:n.toolCallId,context:l,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:n.toolCallId,tool:n.toolName,output:u,state:"output-available"},r,o)}catch(l){await this.addToolResultForClientTool({toolCallId:n.toolCallId,tool:n.toolName,output:null,state:"output-error",errorText:l.message},r,o)}finally{this.pendingToolExecutions.delete(n.toolCallId)}})();this.pendingToolExecutions.set(n.toolCallId,a)}},onApprovalRequest:n=>{const r=this.devtoolsBridge.resolveStreamId(),i=this.findMessageIdForToolCall(n.toolCallId)??this.currentMessageId??"";this.events.approvalRequested(r,i,n.toolCallId,n.toolName,n.input,n.approvalId)},onCustomEvent:(n,r,i)=>{this.callbacksRef.current.onCustomEvent(n,r,i)}}}),this.persistor?.hydrateAsync(t)}mountDevtools(){this.devtoolsMounted||(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}drainIgnoredRunlessChunk(e){if(e.type!=="RUN_ERROR")return;const t=this.persistor?.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type==="RUN_STARTED"){const n=st(e)??e.runId;this.activeRunIds.add(n),this.persistor?.onRunStarted(n),this.setSessionGenerating(!0);return}if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const s=st(e);s?(this.activeRunIds.delete(s),this.persistor?.onRunSettled(s)):e.type==="RUN_ERROR"&&(this.activeRunIds.clear(),this.persistor?.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0),t?.resolveProcessing!==!1&&this.resolveProcessing()}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}resetSessionGenerating(){this.activeRunIds.clear(),this.persistor?.resetIgnored(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){return{hookId:this.uniqueId,clientId:this.uniqueId,threadId:this.threadId,metadata:{hookName:e?.hookName??"useChat",outputKind:e?.outputKind??"chat",...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:t=>{this.processor.setMessages(t)},addToolResult:(t,s,n)=>{this.processor.addToolResult(t,s,n)},generateId:t=>this.generateUniqueId(t)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){const t=this.processor.getMessages();for(const s of t)if(s.parts.find(n=>n.type==="tool-call"&&n.id===e))return s.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),e?.setReadyStatus&&this.setStatus("ready")}reportStreamError(e){const t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status==="submitted"||this.status==="streaming")&&this.setStatus("error"),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;const e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(t=>{t instanceof Error&&t.name!=="AbortError"&&(this.setConnectionStatus("error"),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(t)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!=="error"&&this.setConnectionStatus("disconnected")))})}async consumeSubscription(e){const t=this.connection.subscribe(e);for await(const s of t){if(e.aborted)break;if(this.connectionStatus==="connecting"&&this.setConnectionStatus("connected"),this.persistor?.shouldIgnoreChunk(s)??!1){(s.type==="RUN_FINISHED"||s.type==="RUN_ERROR")&&(st(s)?this.updateRunLifecycle(s,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(s));continue}this.callbacksRef.current.onChunk(s),this.devtoolsBridge.observeChunk(s),this.processor.processChunk(s),this.updateRunLifecycle(s),await new Promise(n=>setTimeout(n,0))}}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t){if(this.mountDevtools(),typeof e=="string"&&!e.trim()||this.isLoading)return;const s=this.normalizeMessageInput(e);this.pendingMessageBody=t;const n=this.processor.addUserMessage(s.content,s.id);this.events.messageSent(n.id,s.content),await this.streamResponse()}normalizeMessageInput(e){return typeof e=="string"?{content:e.trim()}:{content:e.content,id:e.id}}async append(e){this.mountDevtools();const t=du(e,Se);if(t.role==="system")return;const s=t;this.events.messageAppended(s);const n=this.processor.getMessages();if(this.processor.setMessages([...n,s]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;const e=++this.streamGeneration,t=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.currentRunId=t,this.setIsLoading(!0),this.setStatus("submitted"),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;const s=this.abortController.signal;this.pendingToolExecutions.clear();let n=!1,r=null,i=!1;try{const o=this.processor.getMessages(),a=new Map(this.clientToolsRef.current),l=this.context;if(await this.callbacksRef.current.onResponse(),s.aborted)return!1;const u={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId("stream"),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=a,this.activeContext=l,this.processor.prepareAssistantMessage(),this.ensureSubscription();const d=this.waitForProcessing(),c={threadId:this.threadId,runId:t,clientTools:Array.from(a.values()).map(h=>({name:h.name,description:h.description,parameters:h.inputSchema?As(h.inputSchema):{type:"object"}})),forwardedProps:{...u}};if(this.devtoolsBridge.beginRun(c.runId,this.threadId),r=c.runId,this.devtoolsBridge.emitRunLifecycle("run:created",c.runId,"created"),this.devtoolsBridge.emitRunLifecycle("run:started",c.runId,"started"),this.devtoolsBridge.emitSnapshot(),await this.connection.send(o,u,s,c),await d,e!==this.streamGeneration)return!1;if(this.status==="error")return r&&(this.devtoolsBridge.emitRunLifecycle("run:errored",r,"errored",this.error?{error:this.error.message}:{}),i=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),n=!0}catch(o){if(o instanceof Error){if(o.name==="AbortError")return r&&(this.devtoolsBridge.emitRunLifecycle("run:cancelled",r,"cancelled"),i=!0),!1;e===this.streamGeneration&&(this.reportStreamError(o),r&&(this.devtoolsBridge.emitRunLifecycle("run:errored",r,"errored",{error:o.message}),i=!0))}}finally{if(e===this.streamGeneration&&(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.currentRunId=null,this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,r&&!i&&(n?this.devtoolsBridge.emitRunLifecycle("run:completed",r,"completed"):s.aborted&&this.devtoolsBridge.emitRunLifecycle("run:cancelled",r,"cancelled")),await this.drainPostStreamActions(),n)){const o=this.processor.getMessages().at(-1)?.parts.at(-1),{finishReason:a}=this.processor.getState();if(o?.type==="tool-result"&&a!=="stop"&&this.shouldAutoSend())try{await this.checkForContinuation()}catch(l){console.error("Failed to continue flow after tool result:",l)}else this.status!=="ready"&&this.setStatus("ready")}}return n}subscribe(e){const t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus("connecting"),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected")}async reload(){const e=this.processor.getMessages();if(e.length===0)return;const t=e.findLastIndex(s=>s.role==="user");t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){const e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){this.persistor&&(this.persistor.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()):this.activeRunIds.size>0&&this.resetSessionGenerating(),this.persistor.beginClear()),this.processor.clearMessages(),this.persistor?.remove(),this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){const t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t)}async addToolResultForClientTool(e,t,s){if(t&&e.state!=="output-error")try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(n){e={...e,output:null,state:"output-error",errorText:n.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||"output-available",s),this.processor.addToolResult(e.toolCallId,e.output,e.state==="output-error"?e.errorText||"Tool execution failed":void 0),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}validateClientToolOutput(e,t){return e.outputSchema&&Ut(e.outputSchema)?Zl(e.outputSchema,t):t}async addToolApprovalResponse(e){const t=this.processor.getMessages();let s;for(const n of t){const r=n.parts.find(i=>i.type==="tool-call"&&i.approval?.id===e.id);if(r){s=r.id;break}}if(s&&this.events.toolApprovalResponded(e.id,s,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){this.postStreamActions.push(e)}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}shouldAutoSend(){const e=this.processor.getMessages().findLast(t=>t.role==="assistant");return!e||!e.parts.some(t=>t.type==="tool-call")?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){const t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected"),this.connection=lr(dr({connection:e.connection,fetcher:e.fetcher})),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),"context"in e&&(this.context=e.context),e.tools!==void 0){this.clientToolsRef.current=new Map;for(const t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}},hr=Symbol.for("tanstack.ai.devtools.activeBridgeByHookId");function fr(){const e=globalThis,t=e[hr];if(t)return t;const s=new Map;return e[hr]=s,s}var Zu=class{options;bridgeId;unsubscribers=[];disposed=!1;superseded=!1;registered=!1;constructor(e){this.options=e,this.bridgeId=ec(e.hookId)}emitRegistered(){this.prepareForMountEmit()&&(this.registered=!0,ke("hook:registered",{...this.createEnvelope("hook:registered"),...this.createMetadataPayload(),lifecycle:"mounted"}))}emitUpdated(){this.prepareForEmit()&&ke("hook:updated",{...this.createEnvelope("hook:updated"),...this.createMetadataPayload(),lifecycle:"active"})}emitSnapshot(){this.prepareForEmit()&&ke("hook:state-snapshot",{...this.createEnvelope("hook:state-snapshot"),...this.createMetadataPayload(),state:this.options.getSnapshot()})}emitToolsRegistered(){if(!this.prepareForEmit())return;const e=this.options.getTools?Array.from(this.options.getTools()).map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema?As(t.inputSchema):{type:"object"},outputSchema:t.outputSchema?As(t.outputSchema):void 0,needsApproval:t.needsApproval,metadata:t.metadata})):[];ke("tools:registered",{...this.createEnvelope("tools:registered"),...this.createMetadataPayload(),tools:e})}emitRunLifecycle(e,t,s,n={}){this.prepareForEmit()&&ke(e,{...this.createEnvelope(e,"client-state",{runId:t}),runId:t,status:s,...n.error?{error:n.error}:{}})}deactivate(){const e=fr();e.get(this.options.hookId)===this&&e.delete(this.options.hookId);for(const t of this.unsubscribers.splice(0))t()}supersede(){this.disposed||(this.superseded=!0,this.disposed=!0,this.deactivate())}dispose(){if(!this.disposed){if(this.disposed=!0,!this.registered){this.deactivate();return}ke("hook:unregistered",{...this.createEnvelope("hook:unregistered"),...this.createMetadataPayload(),reason:"disposed"}),this.deactivate()}}prepareForEmit(){return this.disposed||this.superseded?!1:(this.activate(),!0)}prepareForMountEmit(){return this.superseded?!1:(this.disposed&&(this.disposed=!1,this.registered=!1),this.activate(),!0)}activate(){if(this.disposed)return;const e=fr(),t=e.get(this.options.hookId);t&&t!==this&&(typeof t.supersede=="function"?t.supersede():t.deactivate()),e.set(this.options.hookId,this),!(this.unsubscribers.length>0)&&(this.unsubscribers.push(ut.on("devtools:request-state",s=>{this.handleRequestState(s)})),this.options.applyToolFixture&&this.unsubscribers.push(ut.on("devtools:tool-fixture:apply",s=>{this.handleToolFixtureApply(s)})))}handleRequestState(e){if(this.disposed||this.superseded)return;const t=e.payload.targetHookId;t&&t!==this.options.hookId||(this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot())}async handleToolFixtureApply(e){const t=e.payload;this.matchesFixtureTarget(t)&&await this.options.applyToolFixture?.(t)}matchesFixtureTarget(e){return!e.hookId&&!e.threadId?!1:e.hookId?e.hookId===this.options.hookId:!(e.threadId&&(!this.options.threadId||e.threadId!==this.options.threadId))}createEnvelope(e,t="client-state",s={}){return Fs({eventType:e,source:"client",visibility:t,clientId:this.options.clientId,hookId:this.options.hookId,correlationId:this.bridgeId,...this.options.threadId?{threadId:this.options.threadId}:{},...s.runId?{runId:s.runId}:{},timestamp:Date.now()})}createMetadataPayload(){return{hookId:this.options.hookId,hookName:this.options.metadata.hookName,...this.options.metadata.name?{displayName:this.options.metadata.name}:{},...this.options.metadata.outputKind?{outputKind:this.options.metadata.outputKind}:{},...this.options.metadata.framework?{framework:this.options.metadata.framework}:{}}}},gr=0;function ec(e){const t=globalThis.crypto;return t?.randomUUID?`bridge:${e}:${t.randomUUID()}`:(gr+=1,`bridge:${e}:${gr}`)}var tc=class extends Zu{events;chatOptions;currentRunId=null;currentRunThreadId=null;currentStreamId=null;lastStreamId=null;lastRunEventContext;constructor(e){super({...e,applyToolFixture:t=>this.applyFixture(t)}),this.chatOptions=e,this.events=new ac(e.clientId,this)}setCurrentStreamId(e){this.currentStreamId=e,e&&(this.lastStreamId=e)}recordStreamId(e){e&&(this.lastStreamId=e)}mountWithTools(e){this.events.clientCreated(e),this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot()}notifyToolsChanged(){this.emitToolsRegistered(),this.emitSnapshot()}getCurrentStreamId(){return this.currentStreamId}getLastStreamId(){return this.lastStreamId}resolveStreamId(){return this.currentStreamId??this.lastStreamId??this.chatOptions.generateId("stream")}beginRun(e,t){this.currentRunId=e,this.currentRunThreadId=t,this.lastRunEventContext={runId:e,threadId:t}}observeChunk(e){if(e.type==="RUN_STARTED"){this.beginRun(e.runId,e.threadId);return}if(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR"){const t=(e.type==="RUN_FINISHED",e.runId);if(!t||t===this.currentRunId){const s=this.getCurrentRunEventContext();s&&(this.lastRunEventContext=s),this.currentRunId=null,this.currentRunThreadId=null}}}getCurrentRunEventContext(){if(this.currentRunId)return{threadId:this.currentRunThreadId??this.chatOptions.threadId??"",runId:this.currentRunId}}getCurrentOrLastRunEventContext(){return this.getCurrentRunEventContext()??this.lastRunEventContext}findToolCallContext(e){const t={toolCallId:e},s=this.getCurrentRunEventContext();return s?{threadId:s.threadId,runId:s.runId,toolCallId:e}:this.chatOptions.threadId?{threadId:this.chatOptions.threadId,toolCallId:e}:t}async applyFixture(e){const t=this.chatOptions.getMessages(),s=e.threadId??this.chatOptions.threadId??"";if(e.execute){await this.executeFixture(e,t,s);return}const{message:n,toolCallId:r}=this.createReplayMessageFromFixture(e,t),i=n.id;this.events.messageAppended(n,void 0,{threadId:s,toolCallId:r,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,n]),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:s,...e.runId?{runId:e.runId}:{},toolName:e.toolName,input:e.input,output:e.output,messageId:i,toolCallId:r,...e.execute!==void 0?{execute:e.execute}:{},...e.message?{message:e.message}:{},...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}async executeFixture(e,t,s){const n=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i={id:r,role:"assistant",parts:[{type:"tool-call",id:n,name:e.toolName,arguments:hs(e.input),input:e.input,state:"input-complete"}],createdAt:new Date};this.events.messageAppended(i,void 0,{threadId:s,toolCallId:n,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,i]),this.emitSnapshot();const o=this.findClientTool(e.toolName)?.execute;if(!o){console.warn(`[ai-devtools] tool fixture "${e.toolName}" requested execute=true but no client tool implementation is registered; replaying saved output instead.`),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:e.output,errorText:e.errorText});return}let a;try{a=await o(e.input)}catch(l){console.error(`[ai-devtools] tool fixture "${e.toolName}" execute threw`,l),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:null,errorText:l instanceof Error?`${l.name}: ${l.message}`:`Tool execution failed: ${String(l)}`});return}this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:a})}addToolResultForFixture(e){const t=e.errorText?"output-error":"output-available";this.events.toolResultAdded(e.toolCallId,e.fixture.toolName,e.output,t,{threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolCallId:e.toolCallId}),this.chatOptions.addToolResult(e.toolCallId,e.output,e.errorText),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolName:e.fixture.toolName,input:e.fixture.input,output:e.output,execute:!0,messageId:e.messageId,toolCallId:e.toolCallId,...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}createReplayMessageFromFixture(e,t){const s=this.cloneFixtureSourceMessage(e,t);if(s)return s;const n=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i=e.errorText?"error":"complete";return{toolCallId:n,message:{id:r,role:"assistant",parts:[{type:"tool-call",id:n,name:e.toolName,arguments:hs(e.input),input:e.input,state:"input-complete",output:e.output},{type:"tool-result",toolCallId:n,content:hs(e.output),state:i,...e.errorText?{error:e.errorText}:{}}],createdAt:new Date}}}cloneFixtureSourceMessage(e,t){const s=e.message;if(!s||!Array.isArray(s.parts))return;const n=this.createFixtureToolCallIdMap(s.parts,t),r=s.parts.map(a=>nc(a,n)).filter(a=>!!a),i=e.toolCallId?n.get(e.toolCallId):void 0;if(ic(r,{...i?{mappedToolCallId:i}:{},output:e.output}),r.length===0)return;const o=(e.toolCallId?n.get(e.toolCallId):void 0)??rc(r);if(o)return{toolCallId:o,message:{id:this.resolveFixtureMessageId(s.id,t),role:s.role,parts:r,createdAt:new Date}}}createFixtureToolCallIdMap(e,t){const s=new Map;for(const n of e)!Ii(n)||n.type!=="tool-call"||typeof n.id=="string"&&s.set(n.id,this.resolveFixtureToolCallId(n.id,t));return s}resolveFixtureMessageId(e,t){return e&&!t.some(s=>s.id===e)?e:this.chatOptions.generateId("fixture-msg")}resolveFixtureToolCallId(e,t){return e&&!oc(t,e)?e:this.chatOptions.generateId("fixture-tool-call")}findClientTool(e){const t=this.chatOptions.getTools?.();if(t){for(const s of t)if(s.name===e)return s}}};function Ii(e){return typeof e=="object"&&e!==null}function hs(e){if(typeof e=="string")return e;if(e===void 0||typeof e=="function"||typeof e=="symbol")return String(e);try{return JSON.stringify(e)}catch(t){return console.error("[ai-devtools] failed to JSON.stringify fixture value; falling back to String(). Tool call arguments may be malformed.",{error:t,value:e}),String(e)}}function sc(e){try{return JSON.parse(e)}catch(t){return console.error("[ai-devtools] failed to JSON.parse fixture result content; replaying as raw string. Fixture payload may be corrupted.",{error:t,content:e}),e}}function nc(e,t){if(!Ii(e)||typeof e.type!="string")return;const s={...e};return e.type==="tool-call"&&typeof e.id=="string"&&(s.id=t.get(e.id)??e.id),e.type==="tool-result"&&typeof e.toolCallId=="string"&&(s.toolCallId=t.get(e.toolCallId)??e.toolCallId),s}function rc(e){const t=e.find(s=>s.type==="tool-call");return t?.type==="tool-call"?t.id:void 0}function ic(e,t){for(const s of e){if(s.type!=="tool-result")continue;const n=e.find(r=>r.type==="tool-call"&&r.id===s.toolCallId&&r.output===void 0);n&&(n.output=Array.isArray(s.content)?s.content:sc(s.content))}if(t.mappedToolCallId&&t.output!==void 0){const s=e.find(n=>n.type==="tool-call"&&n.id===t.mappedToolCallId&&n.output===void 0);s&&(s.output=t.output)}}function oc(e,t){return e.some(s=>s.parts.some(n=>n.type==="tool-call"?n.id===t:n.type==="tool-result"?n.toolCallId===t:!1))}var ac=class extends Du{constructor(e,t){super(e),this.helper=t}helper;afterEmit(e){e&&this.helper.recordStreamId(e),this.helper.emitSnapshot()}textUpdated(e,t,s,n){super.textUpdated(e,t,s,n??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}thinkingUpdated(e,t,s,n,r){super.thinkingUpdated(e,t,s,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}messageAppended(e,t,s){super.messageAppended(e,t,s??this.helper.getCurrentRunEventContext()),this.afterEmit(t)}toolCallStateChanged(e,t,s,n,r,i,o){super.toolCallStateChanged(e,t,s,n,r,i,o??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}structuredOutputChanged(e,t,s,n,r){super.structuredOutputChanged(e,t,s,n,r??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(t)}approvalRequested(e,t,s,n,r,i,o){super.approvalRequested(e,t,s,n,r,i,o??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(e)}toolResultAdded(e,t,s,n,r){super.toolResultAdded(e,t,s,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit()}toolApprovalResponded(e,t,s,n){super.toolApprovalResponded(e,t,s,n??this.helper.getCurrentRunEventContext()),this.afterEmit()}clientCreated(e){super.clientCreated(e),this.afterEmit()}loadingChanged(e){super.loadingChanged(e),this.afterEmit()}errorChanged(e){super.errorChanged(e),this.afterEmit()}reloaded(e){super.reloaded(e),this.afterEmit()}stopped(){super.stopped(),this.afterEmit()}messagesCleared(){super.messagesCleared(),this.afterEmit()}messageSent(e,t){super.messageSent(e,t),this.afterEmit()}toolFixtureApplied(e){super.toolFixtureApplied(e),this.afterEmit()}};function lc(e){return new tc(e)}function Tc(e){const t=(0,w.useId)(),s=e.id||t,[n,r]=(0,w.useState)(e.initialMessages||[]),[i,o]=(0,w.useState)(!1),[a,l]=(0,w.useState)(void 0),[u,d]=(0,w.useState)("ready"),[c,h]=(0,w.useState)(!1),[f,g]=(0,w.useState)("disconnected"),[p,v]=(0,w.useState)(!1),m=(0,w.useRef)(e.initialMessages||[]),S=(0,w.useRef)(!0),C=(0,w.useRef)(null),I=(0,w.useRef)(null);m.current=n;const y=(0,w.useRef)(e);y.current=e;const R=(0,w.useMemo)(()=>{const F=e.initialMessages||[];S.current=!1;const L=y.current,B=new Yu({devtoolsBridgeFactory:lc,...L.connection?{connection:L.connection}:{fetcher:L.fetcher},id:s,initialMessages:F,...L.body!==void 0&&{body:L.body},...L.threadId!==void 0&&{threadId:L.threadId},...L.forwardedProps!==void 0&&{forwardedProps:L.forwardedProps},...L.persistence!==void 0&&{persistence:L.persistence},...L.context!==void 0&&{context:L.context},devtools:{...L.devtools,framework:"react",hookName:"useChat",outputKind:L.outputSchema?"structured":"chat"},onResponse:N=>{C.current===B&&y.current.onResponse?.(N)},onChunk:N=>{C.current===B&&y.current.onChunk?.(N)},onFinish:N=>{C.current===B&&y.current.onFinish?.(N)},onError:N=>{C.current===B&&y.current.onError?.(N)},...L.tools!==void 0&&{tools:L.tools},onCustomEvent:(N,he,fe)=>{C.current===B&&y.current.onCustomEvent?.(N,he,fe)},...e.streamProcessor!==void 0&&{streamProcessor:e.streamProcessor},onMessagesChange:N=>{C.current===B&&r(N)},onLoadingChange:N=>{C.current===B&&o(N)},onErrorChange:N=>{C.current===B&&l(N)},onStatusChange:N=>{C.current===B&&d(N)},onSubscriptionChange:N=>{C.current===B&&h(N)},onConnectionStatusChange:N=>{C.current===B&&g(N)},onSessionGeneratingChange:N=>{C.current===B&&v(N)}});return C.current=B,B},[s]);(0,w.useEffect)(()=>{const F=R.getMessages();F!==m.current&&r(F)},[R]),(0,w.useEffect)(()=>{R.updateOptions({body:e.body})},[R,e.body]),(0,w.useEffect)(()=>{e.forwardedProps!==void 0&&R.updateOptions({forwardedProps:e.forwardedProps})},[R,e.forwardedProps]),(0,w.useEffect)(()=>{e.tools!==void 0&&R.updateOptions({tools:e.tools})},[R,e.tools]),(0,w.useEffect)(()=>{R.updateOptions({context:e.context})},[R,e.context]),(0,w.useEffect)(()=>{e.live?R.subscribe():R.unsubscribe()},[R,e.live]),(0,w.useEffect)(()=>(I.current&&(clearTimeout(I.current),I.current=null),C.current=R,R.mountDevtools(),()=>{I.current=setTimeout(()=>{C.current===R&&(C.current=null),I.current=null},0),y.current.live?R.unsubscribe():R.stop(),R.dispose()}),[R]);const b=(0,w.useCallback)(async F=>{await R.sendMessage(F)},[R]),_=(0,w.useCallback)(async F=>{await R.append(F)},[R]),M=(0,w.useCallback)(async()=>{await R.reload()},[R]),P=(0,w.useCallback)(()=>{R.stop()},[R]),E=(0,w.useCallback)(()=>{R.clear()},[R]),O=(0,w.useCallback)(F=>{R.setMessagesManually(F)},[R]),se=(0,w.useCallback)(async F=>{await R.addToolResult(F)},[R]),H=(0,w.useCallback)(async F=>{await R.addToolApprovalResponse(F)},[R]),j=R.getMessages(),Z=(0,w.useMemo)(()=>{let F=-1;for(let L=j.length-1;L>=0;L--)if(j[L]?.role==="user"){F=L;break}if(F===-1)return null;for(let L=j.length-1;L>F;L--){const B=j[L];if(B?.role!=="assistant")continue;const N=B.parts.find(he=>he.type==="structured-output");if(N)return N}return null},[j]);return{messages:j,sendMessage:b,append:_,reload:M,stop:P,isLoading:i,error:a,status:u,isSubscribed:c,connectionStatus:f,sessionGenerating:p,setMessages:O,clear:E,addToolResult:se,addToolApprovalResponse:H,partial:(0,w.useMemo)(()=>Z?Z.partial??Z.data??{}:{},[Z]),final:(0,w.useMemo)(()=>!Z||Z.status!=="complete"?null:Z.data,[Z])}}var Ac=new Uint8Array(128).fill(128);export{hc as C,fc as S,Qr as _,Ec as a,gc as b,wc as c,Ha as d,Cc as f,Xr as g,ei as h,Mc as i,Ic as l,Sc as m,Pc as n,bc as o,yc as p,xc as r,_c as s,Tc as t,Rc as u,vc as v,_r as x,mc as y};
|
|
7
|
+
color: hsl(${Math.max(0,Math.min(120-120*p,120))}deg 100% 31%);`,s?.key)}return s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(r),o=!1,r}return i.updateDeps=a=>{n=a},i}function Qn(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var Bl=(e,t)=>Math.abs(e-t)<1.01,Ul=(e,t,s)=>{let n;return function(...r){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,r),s)}},Jn=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},Vl=e=>e,Gl=e=>{const t=Math.max(e.startIndex-e.overscan,0),s=Math.min(e.endIndex+e.overscan,e.count-1),n=[];for(let r=t;r<=s;r++)n.push(r);return n},Hl=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const r=i=>{const{width:a,height:l}=i;t({width:Math.round(a),height:Math.round(l)})};if(r(Jn(s)),!n.ResizeObserver)return()=>{};const o=new n.ResizeObserver(i=>{const a=()=>{const l=i[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){r({width:u.inlineSize,height:u.blockSize});return}}r(Jn(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},Xn={passive:!0},Yn=typeof window>"u"?!0:"onscrollend"in window,jl=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let r=0;const o=e.options.useScrollendEvent&&Yn?()=>{}:Ul(n,()=>{t(r,!1)},e.options.isScrollingResetDelay),i=c=>()=>{const{horizontal:d,isRtl:h}=e.options;r=d?s.scrollLeft*(h&&-1||1):s.scrollTop,o(),t(r,c)},a=i(!0),l=i(!1);s.addEventListener("scroll",a,Xn);const u=e.options.useScrollendEvent&&Yn;return u&&s.addEventListener("scrollend",l,Xn),()=>{s.removeEventListener("scroll",a),u&&s.removeEventListener("scrollend",l)}},zl=(e,t,s)=>{if(t?.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},ql=(e,{adjustments:t=0,behavior:s},n)=>{var r,o;const i=e+t;(o=(r=n.scrollElement)==null?void 0:r.scrollTo)==null||o.call(r,{[n.options.horizontal?"left":"top"]:i,behavior:s})},Wl=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,s,n;return((n=(s=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:s.now)==null?void 0:n.call(s))??Date.now()},this.observer=(()=>{let t=null;const s=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(n=>{n.forEach(r=>{const o=()=>{const i=r.target,a=this.indexFromElement(i);if(!i.isConnected){this.observer.unobserve(i);return}this.shouldMeasureDuringScroll(a)&&this.resizeItem(a,this.options.measureElement(i,r,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));return{disconnect:()=>{var n;(n=s())==null||n.disconnect(),t=null},observe:n=>{var r;return(r=s())==null?void 0:r.observe(n,{box:"border-box"})},unobserve:n=>{var r;return(r=s())==null?void 0:r.unobserve(n)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([s,n])=>{typeof n>"u"&&delete t[s]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Vl,rangeExtractor:Gl,onChange:()=>{},measureElement:zl,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var s,n;(n=(s=this.options).onChange)==null||n.call(s,this,t)},this.maybeNotify=De(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const s=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==s){if(this.cleanup(),!s){this.maybeNotify();return}this.scrollElement=s,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(n=>{this.observer.observe(n)}),this.unsubs.push(this.options.observeElementRect(this,n=>{this.scrollRect=n,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(n,r)=>{this.scrollAdjustments=0,this.scrollDirection=r?this.getScrollOffset()<n?"forward":"backward":null,this.scrollOffset=n,this.isScrolling=r,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,s)=>{const n=new Map,r=new Map;for(let o=s-1;o>=0;o--){const i=t[o];if(n.has(i.lane))continue;const a=r.get(i.lane);if(a==null||i.end>a.end?r.set(i.lane,i):i.end<a.end&&n.set(i.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((o,i)=>o.end===i.end?o.index-i.index:o.end-i.end)[0]:void 0},this.getMeasurementOptions=De(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,s,n,r,o,i,a)=>(this.prevLanes!==void 0&&this.prevLanes!==i&&(this.lanesChangedFlag=!0),this.prevLanes=i,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:s,scrollMargin:n,getItemKey:r,enabled:o,lanes:i,laneAssignmentMode:a}),{key:!1}),this.getMeasurements=De(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:s,scrollMargin:n,getItemKey:r,enabled:o,lanes:i,laneAssignmentMode:a},l)=>{if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const h of this.laneAssignments.keys())h>=t&&this.laneAssignments.delete(h);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(h=>{this.itemSizeCache.set(h.key,h.size)}));const u=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const c=this.measurementsCache.slice(0,u),d=new Array(i).fill(void 0);for(let h=0;h<u;h++){const f=c[h];f&&(d[f.lane]=h)}for(let h=u;h<t;h++){const f=r(h),g=this.laneAssignments.get(h);let p,v;const m=a==="estimate"||l.has(f);if(g!==void 0&&this.options.lanes>1){p=g;const y=d[p],R=y!==void 0?c[y]:void 0;v=R?R.end+this.options.gap:s+n}else{const y=this.options.lanes===1?c[h-1]:this.getFurthestMeasurement(c,h);v=y?y.end+this.options.gap:s+n,p=y?y.lane:h%this.options.lanes,this.options.lanes>1&&m&&this.laneAssignments.set(h,p)}const S=l.get(f),C=typeof S=="number"?S:this.options.estimateSize(h),I=v+C;c[h]={index:h,start:v,size:C,end:I,key:f,lane:p},d[p]=h}return this.measurementsCache=c,c},{key:!1,debug:()=>this.options.debug}),this.calculateRange=De(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,s,n,r)=>this.range=t.length>0&&s>0?Kl({measurements:t,outerSize:s,scrollOffset:n,lanes:r}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=De(()=>{let t=null,s=null;const n=this.calculateRange();return n&&(t=n.startIndex,s=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,s]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,s]},(t,s,n,r,o)=>r===null||o===null?[]:t({startIndex:r,endIndex:o,overscan:s,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const s=this.options.indexAttribute,n=t.getAttribute(s);return n?parseInt(n,10):(console.warn(`Missing attribute name '${s}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var s;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const n=this.scrollState.index??((s=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:s.index);if(n!==void 0&&this.range){const r=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),o=Math.max(0,n-r),i=Math.min(this.options.count-1,n+r);return t>=o&&t<=i}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((o,i)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(i))});return}const s=this.indexFromElement(t),n=this.options.getItemKey(s),r=this.elementsCache.get(n);r!==t&&(r&&this.observer.unobserve(r),this.observer.observe(t),this.elementsCache.set(n,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(s)&&this.resizeItem(s,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,s)=>{var n;const r=this.measurementsCache[t];if(!r)return;const o=s-(this.itemSizeCache.get(r.key)??r.size);o!==0&&(((n=this.scrollState)==null?void 0:n.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,o,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,s)),this.notify(!1))},this.getVirtualItems=De(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,s)=>{const n=[];for(let r=0,o=t.length;r<o;r++){const i=s[t[r]];n.push(i)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const s=this.getMeasurements();if(s.length!==0)return Qn(s[fo(0,s.length-1,n=>Qn(s[n]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,s,n=0)=>{if(!this.scrollElement)return 0;const r=this.getSize(),o=this.getScrollOffset();s==="auto"&&(s=t>=o+r?"end":"start"),s==="center"?t+=(n-r)/2:s==="end"&&(t-=r);const i=this.getMaxScrollOffset();return Math.max(Math.min(i,t),0)},this.getOffsetForIndex=(t,s="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getSize(),r=this.getScrollOffset(),o=this.measurementsCache[t];if(!o)return;if(s==="auto")if(o.end>=r+n-this.options.scrollPaddingEnd)s="end";else if(o.start<=r+this.options.scrollPaddingStart)s="start";else return[r,s];if(s==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),s];const i=s==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(i,s,o.size),s]},this.scrollToOffset=(t,{align:s="start",behavior:n="auto"}={})=>{const r=this.getOffsetForAlignment(t,s),o=this.now();this.scrollState={index:null,align:s,behavior:n,startedAt:o,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:s="auto",behavior:n="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const r=this.getOffsetForIndex(t,s);if(!r)return;const[o,i]=r,a=this.now();this.scrollState={index:t,align:i,behavior:n,startedAt:a,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:s="auto"}={})=>{const n=this.getScrollOffset()+t,r=this.now();this.scrollState={index:null,align:"start",behavior:s,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const s=this.getMeasurements();let n;if(s.length===0)n=this.options.paddingStart;else if(this.options.lanes===1)n=((t=s[s.length-1])==null?void 0:t.end)??0;else{const r=Array(this.options.lanes).fill(null);let o=s.length-1;for(;o>=0&&r.some(i=>i===null);){const i=s[o];r[i.lane]===null&&(r[i.lane]=i.end),o--}n=Math.max(...r.filter(i=>i!==null))}return Math.max(n-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:s,behavior:n})=>{this.options.scrollToFn(t,{behavior:n,adjustments:s},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const e=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,t=e?e[0]:this.scrollState.lastTargetOffset,s=1,n=t!==this.scrollState.lastTargetOffset;if(!n&&Bl(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=s){this.scrollState=null;return}}else this.scrollState.stableFrames=0,n&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior="auto",this._scrollToOffset(t,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}},fo=(e,t,s,n)=>{for(;e<=t;){const r=(e+t)/2|0,o=s(r);if(o<n)e=r+1;else if(o>n)t=r-1;else return r}return e>0?e-1:0};function Kl({measurements:e,outerSize:t,scrollOffset:s,lanes:n}){const r=e.length-1,o=l=>e[l].start;if(e.length<=n)return{startIndex:0,endIndex:r};let i=fo(0,r,o,s),a=i;if(n===1)for(;a<r&&e[a].end<s+t;)a++;else if(n>1){const l=Array(n).fill(0);for(;a<r&&l.some(c=>c<s+t);){const c=e[a];l[c.lane]=c.end,a++}const u=Array(n).fill(s+t);for(;i>=0&&u.some(c=>c>=s);){const c=e[i];u[c.lane]=c.start,i--}i=Math.max(0,i-i%n),a=Math.min(r,a+(n-1-a%n))}return{startIndex:i,endIndex:a}}var Zn=typeof document<"u"?w.useLayoutEffect:w.useEffect;function Ql({useFlushSync:e=!0,...t}){const s=w.useReducer(()=>({}),{})[1],n={...t,onChange:(o,i)=>{var a;e&&i?(0,Zr.flushSync)(s):s(),(a=t.onChange)==null||a.call(t,o,i)}},[r]=w.useState(()=>new Wl(n));return r.setOptions(n),Zn(()=>r._didMount(),[]),Zn(()=>r._willUpdate()),r}function Tc(e){return Ql({observeElementRect:Hl,observeElementOffset:jl,scrollToFn:ql,...e})}function er(e){const t={};for(const[s,n]of Object.entries(e))s!=="$schema"&&(t[s]=n);return t}function go(e){return(typeof e=="object"||typeof e=="function")&&e!==null}function po(e){if(!go(e)||!("~standard"in e))return!1;const t=e["~standard"];return typeof t!="object"||t===null||!("version"in t)||t.version!==1||!("jsonSchema"in t)||typeof t.jsonSchema!="object"||t.jsonSchema===null||!("input"in t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function Ut(e){return go(e)&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"version"in e["~standard"]&&e["~standard"].version===1&&"validate"in e["~standard"]&&typeof e["~standard"].validate=="function"}function Jl(e){return Object.keys(e).length>0?e:void 0}function Et(e,t=[]){const s={...e},n={};if(s.type==="object"&&s.properties){const r={...s.properties},o=Object.keys(r),i={};for(const a of o){const l=r[a];if(!l)continue;const u=!t.includes(a);let c=!1,d;if(l.type==="object"&&l.properties){const h=Et(l,l.required||[]);r[a]=u?{...h.schema,type:["object","null"]}:h.schema,c=u,d=h.nullWidening}else if(l.type==="array"&&l.items){const h=Array.isArray(l.items)?l.items[0]:l.items,f=h?Et(h,h.required||[]):void 0;r[a]={...l,items:f?f.schema:l.items,...u?{type:["array","null"]}:{}},c=u,d=f?.nullWidening?{items:f.nullWidening}:void 0}else u&&(l.type&&!Array.isArray(l.type)?(r[a]={...l,type:[l.type,"null"]},c=!0):Array.isArray(l.type)&&!l.type.includes("null")&&(r[a]={...l,type:[...l.type,"null"]},c=!0));(c||d)&&(i[a]={...d??{},...c?{widened:!0}:{}})}s.properties=r,s.required=o,s.additionalProperties=!1,Object.keys(i).length>0&&(n.properties=i)}if(s.type==="array"&&s.items){const r=Array.isArray(s.items)?s.items[0]:s.items;if(r){const o=Et(r,r.required||[]);s.items=o.schema,o.nullWidening&&(n.items=o.nullWidening)}}return{schema:s,nullWidening:Jl(n)}}function Xl(e){if(po(e)){const t=er(e["~standard"].jsonSchema.input({target:"draft-07"}));return"properties"in t&&!t.type&&(t.type="object"),t.type==="object"&&!("properties"in t)&&(t.properties={}),t.type==="object"&&!("required"in t)&&(t.required=[]),t}if(Ut(e))throw new Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e!="object"?e:er(e)}function As(e,t={}){if(!e)return;const{forStructuredOutput:s=!1}=t;if(!s&&!po(e)&&!Ut(e))return e;const n=Xl(e);return!n||typeof n!="object"||!s?n:Et(n,n.required||[]).schema}var Yl=class extends Error{name="StandardSchemaValidationError";issues;constructor(e){super(`Validation failed: ${e.map(t=>t.message||"Validation failed").join(", ")}`),this.issues=e}};function Zl(e,t){if(!Ut(e))return t;const s=e["~standard"].validate(t);if(s instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!s.issues)return s.value;throw new Yl(s.issues)}var eu=new Set(["text","image","audio","video","document"]);function tu(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.type!="string"||!eu.has(t.type))return!1;if(t.type==="text")return typeof t.content=="string";const s=t.source;if(typeof s!="object"||s===null)return!1;const n=s;return typeof n.value!="string"?!1:n.type==="data"?typeof n.mimeType=="string":n.type==="url"}function su(e){return Array.isArray(e)&&e.length>0&&e.every(tu)}function mo(e){return typeof e=="string"||su(e)?e:JSON.stringify(e)}function nu(e){return e.type==="text"||e.type==="image"||e.type==="audio"||e.type==="video"||e.type==="document"}function ru(e){try{return JSON.stringify(e)}catch{return""}}function vo(e){return e.length===0?null:e.every(t=>t.type==="text")?e.map(t=>t.content).join("")||null:e}function tr(e){return e===null?"":typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.content).join("")}function ou(e){return e.role==="system"?[]:e.role!=="assistant"?[iu(e)]:lu(e)}function iu(e){const t=[];for(const s of e.parts)nu(s)&&t.push(s);return{role:e.role,content:vo(t)}}function sr(){return{contentParts:[],toolCalls:[]}}function au(e){return e.state==="input-complete"||e.state==="complete"||e.state==="approval-responded"||e.state==="error"||e.output!==void 0}function lu(e){const t=[];let s=sr(),n=[];const r=new Set;function o(){const i=vo(s.contentParts),a=i!==null,l=s.toolCalls.length>0;(a||l)&&(t.push({role:"assistant",content:i,...l&&{toolCalls:s.toolCalls},...n.length>0&&{thinking:n}}),n=[]),s=sr()}for(const i of e.parts)switch(i.type){case"text":case"image":case"audio":case"video":case"document":s.contentParts.push(i);break;case"tool-call":au(i)&&s.toolCalls.push({id:i.id,type:"function",function:{name:i.name,arguments:i.arguments},...i.metadata!==void 0&&{metadata:i.metadata}});break;case"tool-result":o(),(i.state==="complete"||i.state==="error")&&!r.has(i.toolCallId)&&(t.push({role:"tool",content:i.content,toolCallId:i.toolCallId}),r.add(i.toolCallId));break;case"thinking":i.content&&n.push({content:i.content,...i.signature&&{signature:i.signature}});break;case"structured-output":if(i.status==="complete"){const a=i.raw!==""?i.raw:i.data!==void 0?ru(i.data):"";a!==""&&s.contentParts.push({type:"text",content:a})}break}o();for(const i of e.parts)if(i.type==="tool-call"&&(i.output!==void 0&&!r.has(i.id)&&(t.push({role:"tool",content:mo(i.output),toolCallId:i.id}),r.add(i.id)),i.output===void 0&&i.state==="approval-responded"&&i.approval?.approved!==void 0&&!r.has(i.id))){const a=i.approval.approved;t.push({role:"tool",content:JSON.stringify({approved:a,...a&&{pendingExecution:!0},message:a?"User approved this action":"User denied this action"}),toolCallId:i.id}),r.add(i.id)}return t.length===0&&t.push({role:"assistant",content:null}),t}function Os(e,t){const s=[];if(e.role==="assistant"&&e.thinking?.length)for(const n of e.thinking)n.content&&s.push({type:"thinking",content:n.content,...n.signature&&{signature:n.signature}});if(e.role==="tool"&&e.toolCallId)s.push({type:"tool-result",toolCallId:e.toolCallId,content:tr(e.content),state:"complete"});else if(Array.isArray(e.content))for(const n of e.content)s.push(n);else{const n=tr(e.content);n&&s.push({type:"text",content:n})}if(e.toolCalls&&e.toolCalls.length>0)for(const n of e.toolCalls)s.push({type:"tool-call",id:n.id,name:n.function.name,arguments:n.function.arguments,state:"input-complete",...n.metadata!==void 0&&{metadata:n.metadata}});return{id:t||Se(),role:e.role==="tool"?"assistant":e.role,parts:s}}function uu(e){if("parts"in e)return{...e,id:e.id||Se()};const t=e.id||Se();switch(e.role){case"user":return{id:t,role:"user",parts:cu(e.content)};case"assistant":return Os({role:"assistant",content:e.content??null,...e.toolCalls&&{toolCalls:e.toolCalls}},t);case"tool":return Os({role:"tool",content:e.content,toolCallId:e.toolCallId},t);case"system":case"developer":return{id:t,role:"system",parts:e.content?[{type:"text",content:e.content}]:[]};case"reasoning":return{id:t,role:"assistant",parts:e.content?[{type:"thinking",content:e.content}]:[]};default:return{id:t,role:"assistant",parts:[]}}}function cu(e){if(typeof e=="string")return e?[{type:"text",content:e}]:[];const t=[];for(const s of e)s.type==="text"?t.push({type:"text",content:s.text}):s.type!=="binary"&&t.push(s);return t}function du(e,t){return"parts"in e?{...e,id:e.id||t(),createdAt:e.createdAt||new Date}:{...Os(e,t()),createdAt:new Date}}function Se(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function hu(e){const t=[];for(const s of e){const n=s.parts??[];if(s.role==="system"){t.push({...s,content:n.length>0?Ls(n):s.content??""});continue}if(s.role==="user"){t.push({...s,content:n.length>0?fu(n):s.content??""});continue}for(const i of n)i.type==="thinking"&&t.push({role:"reasoning",id:pu(s.id,i),content:i.content});const r=Ls(n),o=gu(n);t.push({...s,...r!==""&&{content:r},...o&&{toolCalls:o}});for(const i of n)i.type==="tool-result"&&t.push({role:"tool",id:mu(i.toolCallId),toolCallId:i.toolCallId,content:typeof i.content=="string"?i.content:JSON.stringify(i.content),...i.error!==void 0&&{error:i.error}})}return t}function Ls(e){const t=[];for(const s of e)s.type==="text"?t.push(s.content):s.type==="structured-output"&&s.status==="complete"&&s.raw!==""&&t.push(s.raw);return t.join("")}function fu(e){if(!e.some(s=>s.type==="image"||s.type==="audio"||s.type==="video"||s.type==="document"))return Ls(e);const t=[];for(const s of e)s.type==="text"?t.push({type:"text",text:s.content}):(s.type==="image"||s.type==="audio"||s.type==="video"||s.type==="document")&&t.push(s);return t}function gu(e){const t=[];for(const s of e)s.type==="tool-call"&&t.push({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments}});return t.length>0?t:void 0}function pu(e,t){return`${e}-reasoning-${t.id??vu(t.content)}`}function mu(e){return`tool-${e}`}function vu(e){let t=0;for(let s=0;s<e.length;s++)t=t*31+e.charCodeAt(s)|0;return Math.abs(t).toString(36)}var Su=class{shouldEmit(e,t){return!0}},nr=je((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),yu=je((e=>{var t=e&&e.__createBinding||(Object.create?(function(u,c,d,h){h===void 0&&(h=d);var f=Object.getOwnPropertyDescriptor(c,d);(!f||("get"in f?!c.__esModule:f.writable||f.configurable))&&(f={enumerable:!0,get:function(){return c[d]}}),Object.defineProperty(u,h,f)}):(function(u,c,d,h){h===void 0&&(h=d),u[h]=c[d]})),s=e&&e.__exportStar||function(u,c){for(var d in u)d!=="default"&&!Object.prototype.hasOwnProperty.call(c,d)&&t(c,u,d)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var n=nr();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return n.Allow}}),s(nr(),e);var r=class extends Error{};e.PartialJSON=r;var o=class extends Error{};e.MalformedJSON=o;function i(u,c=n.Allow.ALL){if(typeof u!="string")throw new TypeError(`expecting str, got ${typeof u}`);if(!u.trim())throw new Error(`${u} is empty`);return a(u.trim(),c)}e.parseJSON=i;var a=(u,c)=>{const d=u.length;let h=0;const f=y=>{throw new r(`${y} at position ${h}`)},g=y=>{throw new o(`${y} at position ${h}`)},p=()=>(I(),h>=d&&f("Unexpected end of input"),u[h]==='"'?v():u[h]==="{"?m():u[h]==="["?S():u.substring(h,h+4)==="null"||n.Allow.NULL&c&&d-h<4&&"null".startsWith(u.substring(h))?(h+=4,null):u.substring(h,h+4)==="true"||n.Allow.BOOL&c&&d-h<4&&"true".startsWith(u.substring(h))?(h+=4,!0):u.substring(h,h+5)==="false"||n.Allow.BOOL&c&&d-h<5&&"false".startsWith(u.substring(h))?(h+=5,!1):u.substring(h,h+8)==="Infinity"||n.Allow.INFINITY&c&&d-h<8&&"Infinity".startsWith(u.substring(h))?(h+=8,1/0):u.substring(h,h+9)==="-Infinity"||n.Allow._INFINITY&c&&1<d-h&&d-h<9&&"-Infinity".startsWith(u.substring(h))?(h+=9,-1/0):u.substring(h,h+3)==="NaN"||n.Allow.NAN&c&&d-h<3&&"NaN".startsWith(u.substring(h))?(h+=3,NaN):C()),v=()=>{const y=h;let R=!1;for(h++;h<d&&(u[h]!=='"'||R&&u[h-1]==="\\");)R=u[h]==="\\"?!R:!1,h++;if(u.charAt(h)=='"')try{return JSON.parse(u.substring(y,++h-Number(R)))}catch(b){g(String(b))}else if(n.Allow.STR&c)try{return JSON.parse(u.substring(y,h-Number(R))+'"')}catch{return JSON.parse(u.substring(y,u.lastIndexOf("\\"))+'"')}f("Unterminated string literal")},m=()=>{h++,I();const y={};try{for(;u[h]!=="}";){if(I(),h>=d&&n.Allow.OBJ&c)return y;const R=v();I(),h++;try{y[R]=p()}catch(b){if(n.Allow.OBJ&c)return y;throw b}I(),u[h]===","&&h++}}catch{if(n.Allow.OBJ&c)return y;f("Expected '}' at end of object")}return h++,y},S=()=>{h++;const y=[];try{for(;u[h]!=="]";)y.push(p()),I(),u[h]===","&&h++}catch{if(n.Allow.ARR&c)return y;f("Expected ']' at end of array")}return h++,y},C=()=>{if(h===0){u==="-"&&g("Not sure what '-' is");try{return JSON.parse(u)}catch(R){if(n.Allow.NUM&c)try{return JSON.parse(u.substring(0,u.lastIndexOf("e")))}catch{}g(String(R))}}const y=h;for(u[h]==="-"&&h++;u[h]&&",]}".indexOf(u[h])===-1;)h++;h==d&&!(n.Allow.NUM&c)&&f("Unterminated number literal");try{return JSON.parse(u.substring(y,h))}catch{u.substring(y,h)==="-"&&f("Not sure what '-' is");try{return JSON.parse(u.substring(y,u.lastIndexOf("e")))}catch(b){g(String(b))}}},I=()=>{for(;h<d&&`
|
|
8
|
+
\r `.includes(u[h]);)h++};return p()},l=i;e.parse=l})),Cu=yu(),Ru=class{parse(e){if(!(!e||e.trim()===""))try{return(0,Cu.parse)(e)}catch{return}}},So=new Ru;function Iu(e){return So.parse(e)}function wu(e){const t=e?.metadata;return typeof t=="object"&&t!==null&&t.providerExecuted===!0?t:null}function bu(e){return wu(e)!==null}function _u(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],o=r.length>0?r[r.length-1]:null;return o&&o.type==="text"?r[r.length-1]={type:"text",content:s}:r.push({type:"text",content:s}),{...n,parts:r}})}function ls(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],o=r.find(l=>l.type==="tool-call"&&l.id===s.id),i=s.metadata??o?.metadata,a={type:"tool-call",id:s.id,name:s.name,arguments:s.arguments,state:s.state,...o?.approval&&{approval:{...o.approval}},...o?.output!==void 0&&{output:o.output},...i!==void 0&&{metadata:i}};return o?r[r.indexOf(o)]=a:r.push(a),{...n,parts:r}})}function us(e,t,s,n,r,o){return e.map(i=>{if(i.id!==t)return i;const a=[...i.parts],l=a.findIndex(c=>c.type==="tool-result"&&c.toolCallId===s),u={type:"tool-result",toolCallId:s,content:n,state:r,...o&&{error:o}};return l>=0?a[l]=u:a.push(u),{...i,parts:a}})}function Mu(e,t,s,n){return e.map(r=>{if(r.id!==t)return r;const o=[...r.parts],i=o.find(a=>a.type==="tool-call"&&a.id===s);if(i){const a=o.indexOf(i);o[a]={...i,state:"approval-requested",approval:{id:n,needsApproval:!0}}}return{...r,parts:o}})}function cs(e,t,s,n,r){return e.map(o=>{const i=[...o.parts],a=i.find(l=>l.type==="tool-call"&&l.id===t);if(a){const l=i.indexOf(a);i[l]={...a,output:r?{error:r}:s,state:n??(r?"error":"complete")}}return{...o,parts:i}})}function Eu(e,t,s){return e.map(n=>{const r=[...n.parts],o=r.find(i=>i.type==="tool-call"&&i.approval?.id===t);if(o&&o.approval){const i=r.indexOf(o);r[i]={...o,approval:{...o.approval,approved:s},state:"approval-responded"}}return{...n,parts:r}})}function xu(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],o=r.findIndex(d=>d.type==="structured-output"),i=o>=0?r[o]:null,a=(i?.raw??"")+s,l=Iu(a),u=l??i?.partial,c={type:"structured-output",status:"streaming",raw:a,...u!==void 0?{partial:u}:{},...i?.reasoning!==void 0?{reasoning:i.reasoning}:{}};return o>=0?r[o]=c:r.push(c),{...n,parts:r}})}function Pu(e,t,s,n,r){return e.map(o=>{if(o.id!==t)return o;const i=[...o.parts],a=i.findIndex(d=>d.type==="structured-output"),l=a>=0?i[a].raw:"";let u=n||l;if(u===""&&s!==void 0)try{u=JSON.stringify(s)}catch{}const c={type:"structured-output",status:"complete",data:s,partial:s,raw:u,...r!==void 0?{reasoning:r}:{}};return a>=0?i[a]=c:i.push(c),{...o,parts:i}})}function rr(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],o=r.findIndex(a=>a.type==="structured-output");if(o<0)return r.push({type:"structured-output",status:"error",raw:"",errorMessage:s}),{...n,parts:r};const i=r[o];return i.status==="complete"?n:(r[o]={...i,status:"error",errorMessage:s},{...n,parts:r})})}function ds(e,t,s,n,r){return e.map(o=>{if(o.id!==t)return o;const i=[...o.parts],a=i.findIndex(u=>u.type==="thinking"&&u.stepId===s),l={type:"thinking",content:n,stepId:s,...r&&{signature:r}};return a>=0?i[a]=l:i.push(l),{...o,parts:i}})}var Tu=12,Au=class yo{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;recording=null;recordingStartTime=0;constructor(t={}){this.chunkStrategy=t.chunkStrategy||new Su,this.events=t.events||{},this.jsonParser=t.jsonParser||So,this.recordingEnabled=t.recording??!1,t.initialMessages&&(this.messages=[...t.initialMessages])}setMessages(t){this.messages=[...t],this.emitMessagesChange()}addUserMessage(t,s){const n=typeof t=="string"?[{type:"text",content:t}]:t.map(o=>o),r={id:s??Se(),role:"user",parts:n,createdAt:new Date};return this.messages=[...this.messages,r],this.emitMessagesChange(),r}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(t){this.prepareAssistantMessage();const{messageId:s}=this.ensureAssistantMessage(t);return this.pendingManualMessageId=s,s}getCurrentAssistantMessageId(){let t=null;for(const[s,n]of this.messageStates)n.role==="assistant"&&(t=s);return t}addToolResult(t,s,n){const r=this.messages.find(l=>l.parts.some(u=>u.type==="tool-call"&&u.id===t));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${t}`);return}let o=cs(this.messages,t,s,n?"error":void 0,n);const i=mo(s),a=n?"error":"complete";o=us(o,r.id,t,i,a,n),this.messages=o,this.emitMessagesChange()}addToolApprovalResponse(t,s){this.messages=Eu(this.messages,t,s),this.emitMessagesChange()}toModelMessages(){const t=[];for(const s of this.messages)t.push(...ou(s));return t}getMessages(){return this.messages}areAllToolsComplete(){const t=this.messages.findLast(r=>r.role==="assistant");if(!t)return!0;const s=t.parts.filter(r=>r.type==="tool-call");if(s.length===0)return!0;const n=new Set(t.parts.filter(r=>r.type==="tool-result").map(r=>r.toolCallId));return s.every(r=>r.state==="complete"||r.state==="approval-responded"||r.output!==void 0&&!r.approval||n.has(r.id)||bu(r))}removeMessagesAfter(t){const s=new Set(this.messages.slice(0,t+1).map(n=>n.id));for(const n of this.structuredMessageIds)s.has(n)||this.structuredMessageIds.delete(n);for(const n of this.structuredOutputUpdateBatches.keys())s.has(n)||this.structuredOutputUpdateBatches.delete(n);for(const n of this.messageStates.keys())s.has(n)||this.messageStates.delete(n);for(const[n,r]of this.toolCallToMessage)s.has(r)||this.toolCallToMessage.delete(n);for(const n of this.activeMessageIds)s.has(n)||this.activeMessageIds.delete(n);this.messages=this.messages.slice(0,t+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(t){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(const s of t)this.processChunk(s);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(t){switch(this.recording&&this.recording.chunks.push({chunk:t,timestamp:Date.now(),index:this.recording.chunks.length}),t.type){case"TEXT_MESSAGE_START":this.handleTextMessageStartEvent(t);break;case"TEXT_MESSAGE_CONTENT":this.handleTextMessageContentEvent(t);break;case"TEXT_MESSAGE_END":this.handleTextMessageEndEvent(t);break;case"TOOL_CALL_START":this.handleToolCallStartEvent(t);break;case"TOOL_CALL_ARGS":this.handleToolCallArgsEvent(t);break;case"TOOL_CALL_END":this.handleToolCallEndEvent(t);break;case"RUN_FINISHED":this.handleRunFinishedEvent(t);break;case"RUN_ERROR":this.handleRunErrorEvent(t);break;case"STEP_FINISHED":this.handleStepFinishedEvent(t);break;case"MESSAGES_SNAPSHOT":this.handleMessagesSnapshotEvent(t);break;case"CUSTOM":this.handleCustomEvent(t);break;case"RUN_STARTED":this.handleRunStartedEvent(t);break;case"REASONING_START":case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"REASONING_MESSAGE_CONTENT":this.handleReasoningMessageContentEvent(t);break;case"TOOL_CALL_RESULT":this.handleToolCallResultEvent(t);break;case"STEP_STARTED":this.handleStepStartedEvent(t);break}}createMessageState(t,s){const n={id:t,role:s,totalTextContent:"",currentSegmentText:"",lastEmittedText:"",hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(t,n),n}getMessageState(t){return this.messageStates.get(t)}consumePendingThinkingStep(t){if(!this.pendingThinkingStepId)return;const s=this.pendingThinkingStepId;t.currentThinkingStepId=s,t.thinkingSteps.has(s)||(t.thinkingSteps.set(s,""),t.thinkingStepOrder.push(s)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){const t=Array.from(this.activeMessageIds).reverse();for(const s of t){const n=this.messageStates.get(s);if(n&&n.role==="assistant")return s}return null}ensureAssistantMessage(t){if(t){const i=this.getMessageState(t);if(i)return{messageId:t,state:i}}const s=this.getActiveAssistantMessageId();if(s){const i=this.getMessageState(s);if(i)return{messageId:s,state:i}}if(t){const i=this.messages.find(a=>a.id===t);if(i){const a=this.createMessageState(t,i.role);this.activeMessageIds.add(t);const l=i.parts.length>0?i.parts[i.parts.length-1]:null;return l&&l.type==="text"&&(a.currentSegmentText=l.content,a.lastEmittedText=l.content,a.totalTextContent=l.content),{messageId:t,state:a}}}const n=t||Se(),r={id:n,role:"assistant",parts:[],createdAt:new Date};this.messages=[...this.messages,r];const o=this.createMessageState(n,"assistant");return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:o}}handleTextMessageStartEvent(t){const{messageId:s,role:n}=t,r=n==="user"||n==="system"?n:"assistant";if(this.pendingManualMessageId){const i=this.pendingManualMessageId;if(this.pendingManualMessageId=null,i!==s){this.messages=this.messages.map(l=>l.id===i?{...l,id:s}:l);const a=this.messageStates.get(i);a&&(a.id=s,this.messageStates.delete(i),this.messageStates.set(s,a)),this.activeMessageIds.delete(i),this.activeMessageIds.add(s)}this.messageStates.has(s)||(this.createMessageState(s,r),this.activeMessageIds.add(s)),this.emitMessagesChange();return}if(this.messages.find(i=>i.id===s)){this.activeMessageIds.add(s);const i=this.messageStates.get(s);i?i.hasToolCallsSinceTextStart&&(i.currentSegmentText!==i.lastEmittedText&&this.emitTextUpdateForMessage(s),i.currentSegmentText="",i.lastEmittedText="",i.hasToolCallsSinceTextStart=!1):this.createMessageState(s,r);return}const o={id:s,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,o],this.createMessageState(s,r),this.activeMessageIds.add(s),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(t){const{messageId:s}=t,n=this.getMessageState(s);n&&(n.isComplete||(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),this.completeAllToolCallsForMessage(s)))}handleMessagesSnapshotEvent(t){this.resetStreamState();const s=this.messages,n=t.messages.map(uu);this.messages=this.reconcileSnapshotToolCalls(n,s),this.emitMessagesChange()}reconcileSnapshotToolCalls(t,s){const n=new Map;for(const i of s)for(const a of i.parts)a.type==="tool-call"&&n.set(a.id,a);const r=new Set;for(const i of t)for(const a of i.parts)a.type==="tool-call"&&r.add(a.id);const o=[];for(const i of t){const a=i.role==="assistant"&&i.parts.length===1?i.parts.find(c=>c.type==="tool-result"):void 0;if(!a){o.push(i);continue}const l=o.findLast(c=>c.parts.some(d=>d.type==="tool-call"&&d.id===a.toolCallId))??o.findLast(c=>c.role==="assistant"&&!(c.parts.length===1&&c.parts[0]?.type==="tool-result"));if(!l){r.has(a.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${a.toolCallId}") will not be able to locate this call`),o.push(i);continue}const u=[...l.parts];if(!r.has(a.toolCallId)&&!u.some(c=>c.type==="tool-call"&&c.id===a.toolCallId)){const c=n.get(a.toolCallId);c?(u.push({...c}),r.add(c.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${a.toolCallId}") will not be able to locate this call`)}u.push(a),l.parts=u}return o}handleTextMessageContentEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(t.messageId);if(this.completeAllToolCallsForMessage(s),this.structuredMessageIds.has(s)){let c=t.delta||"";if(c===""&&t.content!==void 0&&t.content!==""){const d=(this.messages.find(h=>h.id===s)?.parts.find(h=>h.type==="structured-output")??{raw:""}).raw;t.content.startsWith(d)?c=t.content.slice(d.length):d.startsWith(t.content)?c="":c=t.content}c!==""&&(this.messages=xu(this.messages,s,c),n.totalTextContent+=c,this.queueStructuredOutputUpdate(s,c),this.emitMessagesChange());return}const r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(t,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),n.currentSegmentText="",n.lastEmittedText="",n.hasToolCallsSinceTextStart=!1);const o=n.currentSegmentText;let i=o;const a=t.delta||"";a!==""?i=o+a:t.content!==void 0&&t.content!==""&&(t.content.startsWith(o)?i=t.content:o.startsWith(t.content)?i=o:i=o+t.content);const l=i.slice(o.length);n.currentSegmentText=i,n.totalTextContent+=l;const u=t.delta||t.content||"";this.chunkStrategy.shouldEmit(u,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s)}handleToolCallStartEvent(t){const s=t.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(s??void 0);r.hasToolCallsSinceTextStart=!0;const o=t.toolCallId;if(!r.toolCalls.get(o)){const i="awaiting-input",a=t.toolCallName??t.toolName,l=t.metadata,u={id:t.toolCallId,name:a,arguments:"",state:i,parsedArguments:void 0,index:t.index??r.toolCalls.size,...l!==void 0&&{metadata:l}};r.toolCalls.set(o,u),r.toolCallOrder.push(o),this.toolCallToMessage.set(o,n),this.messages=ls(this.messages,n,{id:t.toolCallId,name:a,arguments:"",state:i,...l!==void 0&&{metadata:l}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,t.toolCallId,i,"")}}handleToolCallArgsEvent(t){const s=t.toolCallId,n=this.toolCallToMessage.get(s);if(!n)return;const r=this.getMessageState(n);if(!r)return;const o=r.toolCalls.get(s);if(!o)return;const i=o.state==="awaiting-input";o.arguments+=t.delta||"",i&&t.delta&&(o.state="input-streaming"),o.parsedArguments=this.jsonParser.parse(o.arguments),this.messages=ls(this.messages,n,{id:o.id,name:o.name,arguments:o.arguments,state:o.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,o.id,o.state,o.arguments)}handleToolCallEndEvent(t){const s=this.toolCallToMessage.get(t.toolCallId);if(!s)return;const n=this.getMessageState(s);if(!n)return;const r=n.toolCalls.get(t.toolCallId);if(r&&r.state!=="input-complete"){t.input!==void 0&&!r.arguments&&(r.arguments=JSON.stringify(t.input));const o=n.toolCallOrder.indexOf(t.toolCallId);this.completeToolCall(s,o,r),t.input!==void 0&&(r.parsedArguments=t.input)}if(t.result){let o;if(Array.isArray(t.result))o=t.result;else try{o=JSON.parse(t.result)}catch{o=t.result}this.messages=cs(this.messages,t.toolCallId,o,t.state==="output-error"?"error":void 0);const i=t.state==="output-error"?"error":"complete";this.messages=us(this.messages,s,t.toolCallId,t.result,i,i==="error"?this.extractToolResultError(o):void 0),this.emitMessagesChange()}}extractToolResultError(t){return t&&typeof t=="object"&&"error"in t&&typeof t.error=="string"?t.error:typeof t=="string"?t:"Tool execution failed"}handleToolCallResultEvent(t){const s=this.toolCallToMessage.get(t.toolCallId);if(!s)return;let n;try{n=JSON.parse(t.content)}catch{n=t.content}this.messages=cs(this.messages,t.toolCallId,n,t.state==="output-error"?"error":void 0);const r=t.state==="output-error"?"error":"complete";this.messages=us(this.messages,s,t.toolCallId,t.content,r,r==="error"?this.extractToolResultError(n):void 0),this.emitMessagesChange()}handleRunStartedEvent(t){this.activeRuns.add(t.runId)}handleRunFinishedEvent(t){this.finishReason=t.finishReason??null,this.activeRuns.delete(t.runId),this.activeRuns.size===0&&(this.isDone=!0,this.completeAllToolCalls(),this.finalizeStream())}handleRunErrorEvent(t){this.hasError=!0;const s="runId"in t&&typeof t.runId=="string"?t.runId:void 0;s?this.activeRuns.delete(s):this.activeRuns.clear();const{messageId:n}=this.ensureAssistantMessage(),r=t.message||t.error?.message||"An error occurred";!t.message&&!t.error?.message&&console.error("[StreamProcessor] RUN_ERROR with no message; original chunk:",t),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=rr(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,"error"),this.emitMessagesChange());const o=new Error(r),i=t.code??t.error?.code;i!==void 0&&Object.assign(o,{code:i}),t.rawEvent!==void 0&&Object.assign(o,{rawEvent:t.rawEvent}),this.events.onError?.(o)}handleStepStartedEvent(t){const s=t.stepId??Se(),n=this.getActiveAssistantMessageId();if(n){const r=this.getMessageState(n);if(r){r.currentThinkingStepId=s,r.thinkingSteps.has(s)||(r.thinkingSteps.set(s,""),r.thinkingStepOrder.push(s)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=s}handleStepFinishedEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);if(n.hasSeenReasoningEvents){if(t.signature){const a=n.currentThinkingStepId??t.stepId;if(!a)return;const l=n.thinkingSteps.get(a);l!==void 0&&(n.thinkingStepSignatures.set(a,t.signature),this.messages=ds(this.messages,s,a,l,t.signature),this.emitMessagesChange())}return}this.consumePendingThinkingStep(n);const r=n.currentThinkingStepId??t.stepId??Se();n.thinkingSteps.has(r)||(n.thinkingSteps.set(r,""),n.thinkingStepOrder.push(r),n.currentThinkingStepId=r);const o=n.thinkingSteps.get(r)??"";let i=o;t.delta&&t.delta!==""?i=o+t.delta:t.content&&t.content!==""&&(t.content.startsWith(o)?i=t.content:o.startsWith(t.content)?i=o:i=o+t.content),n.thinkingSteps.set(r,i),t.signature&&n.thinkingStepSignatures.set(r,t.signature),this.messages=ds(this.messages,s,r,i,n.thinkingStepSignatures.get(r)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(s,r,i)}handleReasoningMessageContentEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;const r=t.delta||"";this.consumePendingThinkingStep(n);const o=n.currentThinkingStepId??t.messageId;n.thinkingSteps.has(o)||(n.thinkingSteps.set(o,""),n.thinkingStepOrder.push(o),n.currentThinkingStepId=o);const i=(n.thinkingSteps.get(o)??"")+r;n.thinkingSteps.set(o,i),this.messages=ds(this.messages,s,o,i,n.thinkingStepSignatures.get(o)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(s,o,i)}handleCustomEvent(t){const s=this.getActiveAssistantMessageId();if(t.name==="structured-output.start"&&t.value){const n=t.value.messageId??s;n&&(this.ensureAssistantMessage(n),this.structuredMessageIds.add(n),this.structuredOutputUpdateBatches.delete(n),this.events.onStructuredOutputChange?.({phase:"start",messageId:n,status:"streaming",raw:""}));return}if(t.name==="structured-output.complete"&&t.value){const n=t.value,r=n.messageId??s;r&&(this.flushStructuredOutputUpdate(r),this.messages=Pu(this.messages,r,n.object,n.raw??"",n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,"complete"),this.emitMessagesChange())}if(t.name==="tool-input-available"&&t.value){const{toolCallId:n,toolName:r,input:o}=t.value;this.events.onToolCall?.({toolCallId:n,toolName:r,input:o});return}if(t.name==="approval-requested"&&t.value){const{toolCallId:n,toolName:r,input:o,approval:i}=t.value,a=s??this.toolCallToMessage.get(n);a&&(this.messages=Mu(this.messages,a,n,i.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:o,approvalId:i.id});return}if(t.name==="ui-resource"&&t.value){const n=t.value,r=this.toolCallToMessage.get(n.toolCallId)??s;if(r){const o={type:"ui-resource",resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(i=>i.id===r?{...i,parts:[...i.parts,o]}:i),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){const n=t.value&&typeof t.value=="object"?t.value.toolCallId:void 0;this.events.onCustomEvent(t.name,t.value,{toolCallId:n})}}isNewTextSegment(t,s){return t.content!==void 0&&(t.content.length<s.length||!t.content.startsWith(s)&&!s.startsWith(t.content))}completeAllToolCalls(){for(const t of this.activeMessageIds)this.completeAllToolCallsForMessage(t)}completeAllToolCallsForMessage(t){const s=this.getMessageState(t);s&&s.toolCalls.forEach((n,r)=>{if(n.state!=="input-complete"){const o=s.toolCallOrder.indexOf(r);this.completeToolCall(t,o,n)}})}completeToolCall(t,s,n){n.state="input-complete",n.parsedArguments=this.jsonParser.parse(n.arguments),!this.isToolCallPartErrored(n.id)&&(this.messages=ls(this.messages,t,{id:n.id,name:n.name,arguments:n.arguments,state:"input-complete",...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(t,n.id,"input-complete",n.arguments))}isToolCallPartErrored(t){return this.messages.some(s=>s.parts?.some(n=>n.type==="tool-call"&&n.id===t&&n.state==="error"))}emitTextUpdateForMessage(t){const s=this.getMessageState(t);s&&(s.lastEmittedText=s.currentSegmentText,this.messages=_u(this.messages,t,s.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(t,s.currentSegmentText))}queueStructuredOutputUpdate(t,s){const n=this.structuredOutputUpdateBatches.get(t),r={delta:`${n?.delta??""}${s}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(t,r),r.chunkCount>=Tu&&this.flushStructuredOutputUpdate(t)}flushStructuredOutputUpdate(t){const s=this.structuredOutputUpdateBatches.get(t);!s||s.chunkCount===0||(this.structuredOutputUpdateBatches.delete(t),this.emitStructuredOutputChange(t,"update",s.delta))}emitStructuredOutputChange(t,s,n){const r=this.messages.find(o=>o.id===t)?.parts.find(o=>o.type==="structured-output");r&&this.events.onStructuredOutputChange?.({phase:s,messageId:t,status:r.status,raw:r.raw,...r.partial!==void 0?{partial:r.partial}:{},...r.data!==void 0?{data:r.data}:{},...r.reasoning!==void 0?{reasoning:r.reasoning}:{},...r.errorMessage!==void 0?{errorMessage:r.errorMessage}:{},...n!==void 0?{delta:n}:{}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){let t;for(const s of this.activeMessageIds){const n=this.getMessageState(s);if(!n)continue;this.completeAllToolCallsForMessage(s),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),n.isComplete=!0;const r=this.messages.find(o=>o.id===s);r&&r.role==="assistant"&&(t=r)}for(const s of this.structuredMessageIds)this.flushStructuredOutputUpdate(s),this.messages=rr(this.messages,s,"Stream ended without structured-output.complete"),this.emitStructuredOutputChange(s,"error");if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),t&&!this.hasError&&this.isWhitespaceOnlyMessage(t)){this.messages=this.messages.filter(s=>s.id!==t.id),this.emitMessagesChange();return}t&&this.events.onStreamEnd?.(t)}getCompletedToolCalls(){const t=[];for(const s of this.messageStates.values())for(const n of s.toolCalls.values())n.state==="input-complete"&&t.push({id:n.id,type:"function",function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return t}getResult(){const t=this.getCompletedToolCalls();let s="",n="";for(const r of this.messageStates.values()){s+=r.totalTextContent;for(const o of r.thinkingStepOrder)n+=r.thinkingSteps.get(o)??""}return{content:s,thinking:n||void 0,toolCalls:t.length>0?t:void 0,finishReason:this.finishReason}}getState(){let t="",s="";const n=new Map,r=[];for(const o of this.messageStates.values()){t+=o.totalTextContent;for(const i of o.thinkingStepOrder)s+=o.thinkingSteps.get(i)??"";for(const[i,a]of o.toolCalls)n.set(i,a);r.push(...o.toolCallOrder)}return{content:t,thinking:s,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:"1.0",timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(t){return t.parts.length===0?!1:t.parts.every(s=>s.type==="text"&&s.content.trim()==="")}static async replay(t,s){return new yo(s).process(Ou(t))}};function Ou(e){return{async*[Symbol.asyncIterator](){for(const{chunk:t}of e.chunks)yield t}}}var Nt=(e=>(e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e))(Nt||{}),Lu=class{#t=!0;#e;#s;#n;#o;#r;#i;#a;#f=0;#l=5;#c=!1;#d=!1;#u=null;#h=()=>{this.debugLog("Connected to event bus"),this.#r=!0,this.#c=!1,this.debugLog("Emitting queued events",this.#o),this.#o.forEach(e=>this.emitEventToBus(e)),this.#o=[],this.stopConnectLoop(),this.#s().removeEventListener("tanstack-connect-success",this.#h)};#g=()=>{if(this.#f<this.#l){this.#f++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#s().removeEventListener("tanstack-connect",this.#g),this.#d=!0,this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};#p=()=>{this.#c||(this.#c=!0,this.#s().addEventListener("tanstack-connect-success",this.#h),this.#g())};constructor({pluginId:e,debug:t=!1,enabled:s=!0,reconnectEveryMs:n=300}){this.#e=e,this.#t=s,this.#s=this.getGlobalTarget,this.#n=t,this.debugLog(" Initializing event subscription for plugin",this.#e),this.#o=[],this.#r=!1,this.#d=!1,this.#i=null,this.#a=n}startConnectLoop(){this.#i!==null||this.#r||(this.debugLog(`Starting connect loop (every ${this.#a}ms)`),this.#i=setInterval(this.#g,this.#a))}stopConnectLoop(){this.#c=!1,this.#i!==null&&(clearInterval(this.#i),this.#i=null,this.#o=[],this.debugLog("Stopped connect loop"))}debugLog(...e){this.#n&&console.log(`🌴 [tanstack-devtools:${this.#e}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;const e=typeof EventTarget<"u"?new EventTarget:void 0;return typeof e>"u"||typeof e.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog("Using new EventTarget as fallback"),e)}getPluginId(){return this.#e}dispatchCustomEventShim(e,t){try{const s=new Event(e,{detail:t});this.#s().dispatchEvent(s)}catch{this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(e,t){try{this.#s().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog("Emitting event to client bus",e),this.dispatchCustomEvent("tanstack-dispatch-event",e)}createEventPayload(e,t){return{type:`${this.#e}:${e}`,payload:t,pluginId:this.#e}}emit(e,t){if(!this.#t){this.debugLog("Event bus client is disabled, not emitting event",e,t);return}if(this.#u&&(this.debugLog("Emitting event to internal event target",e,t),this.#u.dispatchEvent(new CustomEvent(`${this.#e}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#d){this.debugLog("Previously failed to connect, not emitting to bus");return}if(!this.#r){this.debugLog("Bus not available, will be pushed as soon as connected"),this.#o.push(this.createEventPayload(e,t)),typeof CustomEvent<"u"&&!this.#c&&(this.#p(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,s){const n=s?.withEventTarget??!1,r=`${this.#e}:${e}`;if(n&&(this.#u||(this.#u=new EventTarget),this.#u.addEventListener(r,i=>{t(i.detail)})),!this.#t)return this.debugLog("Event bus client is disabled, not registering event",r),()=>{};const o=i=>{this.debugLog("Received event from bus",i.detail),t(i.detail)};return this.#s().addEventListener(r,o),this.debugLog("Registered event to bus",r),()=>{n&&this.#u?.removeEventListener(r,o),this.#s().removeEventListener(r,o)}}onAll(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=s=>{const n=s.detail;e(n)};return this.#s().addEventListener("tanstack-devtools-global",t),()=>this.#s().removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=s=>{const n=s.detail;this.#e&&n.pluginId!==this.#e||e(n)};return this.#s().addEventListener("tanstack-devtools-global",t),()=>this.#s().removeEventListener("tanstack-devtools-global",t)}};function Fu(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():Math.random().toString(36).slice(2)}var Ct;function or(){return Ct!==void 0||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__=Fu()),Ct=globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__),Ct}var Nu=0;function ie(e){return e==null||e===""?"missing":`value-${encodeURIComponent(String(e))}`}function Fs(e){const t=e.runtimeId??or(),s=e.eventId&&e.eventId.length>0?e.eventId:[e.source,e.eventType,ie(t),ie(e.clientId),ie(e.requestId),ie(e.streamId),ie(e.hookId),ie(e.threadId),ie(e.runId),ie(e.messageId),ie(e.toolCallId),ie(e.sequence),e.timestamp,or(),Nu++].join(":");return{...e,runtimeId:t,eventId:s}}var Du=class extends Lu{constructor(){super({pluginId:"tanstack-ai-devtools"})}},ir=Symbol.for("tanstack.ai.devtools.eventClient");function ku(){const e=globalThis,t=e[ir];if(t)return t;const s=new Du;return e[ir]=s,s}var ut=ku();function ke(e,t){ut.emit(e,t)}var Co=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent("client:created",{initialMessageCount:e})}loadingChanged(e){this.emitEvent("client:loading:changed",{isLoading:e})}errorChanged(e){this.emitEvent("client:error:changed",{error:e})}textUpdated(e,t,s,n){this.emitEvent("text:chunk:content",{streamId:e,messageId:t,content:s,...n})}toolCallStateChanged(e,t,s,n,r,o,i){this.emitEvent("tools:call:updated",{streamId:e,messageId:t,toolCallId:s,toolName:n,state:r,arguments:o,...i})}thinkingUpdated(e,t,s,n,r){this.emitEvent("text:chunk:thinking",{streamId:e,messageId:t,content:s,delta:n,...r})}structuredOutputChanged(e,t,s,n,r){this.emitEvent(e,{streamId:t,messageId:s,...n,...r})}approvalRequested(e,t,s,n,r,o,i){this.emitEvent("tools:approval:requested",{streamId:e,messageId:t,toolCallId:s,toolName:n,input:r,approvalId:o,...i})}messageAppended(e,t,s){const n=e.parts.filter(r=>r.type==="text").map(r=>r.content).join(" ");this.emitEvent("text:message:created",{streamId:t,messageId:e.id,role:e.role,content:n,parts:e.parts,...s})}messageSent(e,t){const s=typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.content).join("");this.emitEvent("text:message:created",{messageId:e,role:"user",content:s,...Array.isArray(t)&&{parts:t}}),this.emitEvent("text:message:user",{messageId:e,role:"user",content:s,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent("client:reloaded",{fromMessageIndex:e})}stopped(){this.emitEvent("client:stopped")}messagesCleared(){this.emitEvent("client:messages:cleared")}toolResultAdded(e,t,s,n,r){this.emitEvent("tools:result:added",{toolCallId:e,toolName:t,output:s,state:n,...r})}toolApprovalResponded(e,t,s,n){this.emitEvent("tools:approval:responded",{approvalId:e,toolCallId:t,approved:s,...n})}toolFixtureApplied(e){this.emitEvent("devtools:tool-fixture:applied",{...e})}},$u=class extends Co{emitEvent(e,t){const s=Date.now(),n=e.startsWith("text:")||e.startsWith("tools:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",r=e.startsWith("client:")||e.startsWith("tools:")||e.startsWith("text:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",o=n?"user-visible":"client-state",i={hookId:this.clientId,...typeof t?.threadId=="string"?{threadId:t.threadId}:{},...typeof t?.runId=="string"?{runId:t.runId}:{},...typeof t?.streamId=="string"?{streamId:t.streamId}:{},...typeof t?.messageId=="string"?{messageId:t.messageId}:{},...typeof t?.toolCallId=="string"?{toolCallId:t.toolCallId}:{}};if(r){const a=Fs({eventType:e,clientId:this.clientId,...i,source:"client",visibility:o,timestamp:s});ut.emit(e,{...t,...a})}else{const a=Fs({eventType:e,source:"client",visibility:"client-state",timestamp:s});ut.emit(e,{...t,...a})}}},Bu=class extends Co{emitEvent(){}},Uu=class{events;constructor(e){this.events=new Bu(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,s,n){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return""}observeChunk(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Vu=e=>new Uu(e),Ns=class extends Error{missingFeature;constructor(e){super(Gu(e)),this.name="UnsupportedResponseStreamError",this.missingFeature=e}};function Gu(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function Hu(e){if(!e.body)throw new Ns("Response.body");if(typeof e.body.getReader!="function")throw new Ns("Response.body.getReader");return e.body.getReader()}function ju(){if(typeof globalThis.TextDecoder!="function")throw new Ns("TextDecoder");return new globalThis.TextDecoder}function zu(e){if(!e.startsWith("data:"))return e;const t=e.slice(5);return t.startsWith(" ")?t.slice(1):t}var Ro=new WeakMap;function st(e){return"runId"in e&&typeof e.runId=="string"?e.runId:Ro.get(e)}var qu=class extends Error{constructor(){super("Stream ended with unterminated trailing data — connection was likely cut short."),this.name="StreamTruncatedError"}};function ar(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Rt(e,t){if(!e)throw new Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function Wu(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((s,n)=>{t[n]=s}),t}return e}async function*Ku(e,t){try{const s=ju();let n="";for(;!t?.aborted;){const{done:r,value:o}=await e.read();if(r)break;n+=s.decode(o,{stream:!0});const i=n.split(`
|
|
9
|
+
`);n=i.pop()||"";for(const a of i)a.trim()&&(yield a)}if(n.trim()&&!t?.aborted)throw new qu}finally{e.releaseLock()}}async function*Io(e,t){if(!e.ok)throw new Error(`HTTP error! status: ${e.status} ${e.statusText}`);const s=Hu(e);let n,r,o;for await(const i of Ku(s,t)){if(i.startsWith(":")||i.startsWith("event:")||i.startsWith("id:")||i.startsWith("retry:"))continue;const a=zu(i);if(a==="[DONE]"){yield{type:Nt.RUN_FINISHED,threadId:n??"",runId:r??"",model:o??"",timestamp:Date.now(),finishReason:"stop"};return}const l=JSON.parse(a);"threadId"in l&&typeof l.threadId=="string"&&(n=l.threadId),"runId"in l&&typeof l.runId=="string"&&(r=l.runId),"model"in l&&typeof l.model=="string"&&(o=l.model),yield l}}function lr(e){if(!e)throw new Error("Connection adapter is required");const t="connect"in e,s="subscribe"in e,n="send"in e;if(t&&(s||n))throw new Error("Connection adapter must provide either connect or both subscribe and send, not both modes");if(s&&n)return{subscribe:e.subscribe.bind(e),send:e.send.bind(e)};if(!t)throw new Error("Connection adapter must provide either connect or both subscribe and send");let r=[],o=[];function i(a,l){l&&Ro.set(a,l);const u=o.shift();u?u(a):r.push(a)}return{subscribe(a){const l=r.splice(0),u=[];return r=l,o=u,(async function*(){for(;!a?.aborted;){let c;const d=l.shift();d!==void 0?c=d:c=await new Promise(h=>{const f=()=>h(null);u.push(g=>{a?.removeEventListener("abort",f),h(g)}),a?.addEventListener("abort",f,{once:!0})}),c!==null&&(yield c)}})()},async send(a,l,u,c){let d=!1,h,f;try{const g=e.connect(a,l,u,c);for await(const p of g)"threadId"in p&&typeof p.threadId=="string"&&(h=p.threadId),"runId"in p&&typeof p.runId=="string"&&(f=p.runId),(p.type==="RUN_FINISHED"||p.type==="RUN_ERROR")&&(d=!0),i(p,c?.runId);!u?.aborted&&!d&&i({type:Nt.RUN_FINISHED,threadId:Rt(h??c?.threadId,"threadId"),runId:Rt(f??c?.runId,"runId"),model:"connect-wrapper",timestamp:Date.now(),finishReason:"stop"})}catch(g){if(!u?.aborted&&!d){const p=g instanceof Error?g.message:"Unknown error in connect()";i({type:Nt.RUN_ERROR,threadId:Rt(h??c?.threadId,"threadId"),runId:Rt(f??c?.runId,"runId"),timestamp:Date.now(),message:p})}throw g}}}}function Qu(e,t,s,n){const r=hu(e),o={...n.body,...s?.forwardedProps??{},...t};return{threadId:s?.threadId??ar("thread"),runId:s?.runId??ar("run"),...s?.parentRunId!==void 0&&{parentRunId:s.parentRunId},state:{},messages:r,tools:s?.clientTools??[],context:[],forwardedProps:o,data:{...o}}}function Ac(e,t={}){return{async*connect(s,n,r,o){const i=typeof e=="function"?e():e,a=typeof t=="function"?await t():t,l={"Content-Type":"application/json",...Wu(a.headers)},u=Qu(s,n,o,a),c=a.fetchClient??fetch,d=r||a.signal;yield*Io(await c(i,{method:"POST",headers:l,body:JSON.stringify(u),credentials:a.credentials||"same-origin",...d?{signal:d}:{}}),r)}}}function Ju(e){return{async*connect(t,s,n,r){if(!n)throw new Error("fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.");if(!r)throw new Error("fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.");const o=await e({messages:t,data:s,threadId:r.threadId,runId:r.runId},{signal:n});o instanceof Response?yield*Io(o,n):yield*Xu(o,n)}}}async function*Xu(e,t){if(t.aborted)return;const s=e[Symbol.asyncIterator](),n=new Promise(r=>{t.addEventListener("abort",()=>r({done:!0,value:void 0}),{once:!0})});try{for(;;){const r=await Promise.race([s.next(),n]);if(r.done)return;yield r.value}}finally{await s.return?.()}}function ur(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function cr(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function Yu(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var Zu=class{constructor(e,t,s){this.adapter=e,this.id=t,this.applyMessages=s}adapter;id;applyMessages;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;readInitial(){try{return this.adapter.getItem(this.id)}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;const t=this.messagesGeneration;e.then(s=>{Array.isArray(s)&&this.messagesGeneration===t&&this.applyMessages(s)}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.skipNextPersist){this.skipNextPersist=!1;return}const t=this.generation,s=[...e];this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,s)})}remove(){const e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){const t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{const t=e();if(t instanceof Promise){this.queuePending=!0;const s=t.catch(()=>{});this.queue=s,s.finally(()=>{this.queue===s&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){const t=st(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const s=ur(e);if(s&&this.clearedToolCallIds.has(s))return!0;const n=Yu(e);if(n&&this.clearedMessageIds.has(n))return s&&this.clearedToolCallIds.add(s),!0;const r=cr(e);return r?!!this.clearedMessageIds.has(r):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){const e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){const t=cr(e);t&&this.clearedMessageIds.add(t);const s=ur(e);s&&this.clearedToolCallIds.add(s)}isRunlessChunkFromIgnoredRun(e){return st(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type==="TEXT_MESSAGE_START"||e.type==="TEXT_MESSAGE_CONTENT"||e.type==="TOOL_CALL_START"||e.type==="TOOL_CALL_ARGS"||e.type==="TOOL_CALL_END"||e.type==="TOOL_CALL_RESULT"||e.type==="MESSAGES_SNAPSHOT"||e.type==="RUN_ERROR"}};function dr(e){const{connection:t,fetcher:s}=e;if(t&&s)throw new Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(s)return Ju(s);throw new Error("ChatClient: either `connection` or `fetcher` is required.")}var ec=class{processor;connection;uniqueId;threadId;persistor;currentRunId=null;bodyOption={};forwardedPropsOption={};context=void 0;pendingMessageBody=void 0;isLoading=!1;isSubscribed=!1;error=void 0;status="ready";connectionStatus="disconnected";abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;errorReportedGeneration=null;streamGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;devtoolsMounted=!1;callbacksRef;constructor(e){if(this.uniqueId=e.id||this.generateUniqueId("chat"),this.threadId=e.threadId||this.generateUniqueId("thread"),e.persistence&&(this.persistor=new Zu(e.persistence,this.uniqueId,n=>this.processor.setMessages(n))),this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.context=e.context,this.connection=lr(dr(e)),this.clientToolsRef={current:new Map},e.tools)for(const n of e.tools)this.clientToolsRef.current.set(n.name,n);this.devtoolsBridge=(e.devtoolsBridgeFactory??Vu)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}};const t=this.persistor?.readInitial(),s=Array.isArray(t)?t:e.initialMessages;this.processor=new Au({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...s?{initialMessages:s}:{},events:{onMessagesChange:n=>{this.persistor?.notifyMessagesChanged(n),this.callbacksRef.current.onMessagesChange(n)},onStreamStart:()=>{this.setStatus("streaming");const n=this.processor.getCurrentAssistantMessageId();if(!n)return;const r=this.processor.getMessages().find(o=>o.id===n);r&&(this.currentMessageId=r.id,this.events.messageAppended(r,this.currentStreamId||void 0))},onStreamEnd:n=>{this.callbacksRef.current.onFinish(n),this.setStatus("ready"),this.resolveProcessing()},onError:n=>{this.reportStreamError(n)},onTextUpdate:(n,r)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,n,r)},onThinkingUpdate:(n,r)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,n,r,void 0)},onStructuredOutputChange:n=>{const r=this.devtoolsBridge.resolveStreamId(),o=n.phase==="start"?"structured-output:started":n.phase==="complete"?"structured-output:completed":n.phase==="error"?"structured-output:errored":"structured-output:updated";this.currentMessageId=n.messageId,this.events.structuredOutputChanged(o,r,n.messageId,{status:n.status,raw:n.raw,...n.partial!==void 0?{partial:n.partial}:{},...n.data!==void 0?{data:n.data}:{},...n.reasoning!==void 0?{reasoning:n.reasoning}:{},...n.errorMessage!==void 0?{errorMessage:n.errorMessage}:{},...n.delta!==void 0?{delta:n.delta}:{}})},onToolCallStateChange:(n,r,o,i)=>{const a=this.processor.getMessages().find(l=>l.id===n)?.parts.find(l=>l.type==="tool-call"&&l.id===r)?.name||"unknown";this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,n,r,a,o,i)},onToolCall:n=>{const r=(this.activeClientTools??this.clientToolsRef.current).get(n.toolName),o=r?.execute;if(o){const i=this.devtoolsBridge.getCurrentRunEventContext(),a=(async()=>{try{const l=this.activeClientTools===null?this.context:this.activeContext,u=await o(n.input,{toolCallId:n.toolCallId,context:l,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:n.toolCallId,tool:n.toolName,output:u,state:"output-available"},r,i)}catch(l){await this.addToolResultForClientTool({toolCallId:n.toolCallId,tool:n.toolName,output:null,state:"output-error",errorText:l.message},r,i)}finally{this.pendingToolExecutions.delete(n.toolCallId)}})();this.pendingToolExecutions.set(n.toolCallId,a)}},onApprovalRequest:n=>{const r=this.devtoolsBridge.resolveStreamId(),o=this.findMessageIdForToolCall(n.toolCallId)??this.currentMessageId??"";this.events.approvalRequested(r,o,n.toolCallId,n.toolName,n.input,n.approvalId)},onCustomEvent:(n,r,o)=>{this.callbacksRef.current.onCustomEvent(n,r,o)}}}),this.persistor?.hydrateAsync(t)}mountDevtools(){this.devtoolsMounted||(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}drainIgnoredRunlessChunk(e){if(e.type!=="RUN_ERROR")return;const t=this.persistor?.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type==="RUN_STARTED"){const n=st(e)??e.runId;this.activeRunIds.add(n),this.persistor?.onRunStarted(n),this.setSessionGenerating(!0);return}if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const s=st(e);s?(this.activeRunIds.delete(s),this.persistor?.onRunSettled(s)):e.type==="RUN_ERROR"&&(this.activeRunIds.clear(),this.persistor?.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0),t?.resolveProcessing!==!1&&this.resolveProcessing()}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}resetSessionGenerating(){this.activeRunIds.clear(),this.persistor?.resetIgnored(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){return{hookId:this.uniqueId,clientId:this.uniqueId,threadId:this.threadId,metadata:{hookName:e?.hookName??"useChat",outputKind:e?.outputKind??"chat",...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:t=>{this.processor.setMessages(t)},addToolResult:(t,s,n)=>{this.processor.addToolResult(t,s,n)},generateId:t=>this.generateUniqueId(t)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){const t=this.processor.getMessages();for(const s of t)if(s.parts.find(n=>n.type==="tool-call"&&n.id===e))return s.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),e?.setReadyStatus&&this.setStatus("ready")}reportStreamError(e){const t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status==="submitted"||this.status==="streaming")&&this.setStatus("error"),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;const e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(t=>{t instanceof Error&&t.name!=="AbortError"&&(this.setConnectionStatus("error"),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(t)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!=="error"&&this.setConnectionStatus("disconnected")))})}async consumeSubscription(e){const t=this.connection.subscribe(e);for await(const s of t){if(e.aborted)break;if(this.connectionStatus==="connecting"&&this.setConnectionStatus("connected"),this.persistor?.shouldIgnoreChunk(s)??!1){(s.type==="RUN_FINISHED"||s.type==="RUN_ERROR")&&(st(s)?this.updateRunLifecycle(s,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(s));continue}this.callbacksRef.current.onChunk(s),this.devtoolsBridge.observeChunk(s),this.processor.processChunk(s),this.updateRunLifecycle(s),await new Promise(n=>setTimeout(n,0))}}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t){if(this.mountDevtools(),typeof e=="string"&&!e.trim()||this.isLoading)return;const s=this.normalizeMessageInput(e);this.pendingMessageBody=t;const n=this.processor.addUserMessage(s.content,s.id);this.events.messageSent(n.id,s.content),await this.streamResponse()}normalizeMessageInput(e){return typeof e=="string"?{content:e.trim()}:{content:e.content,id:e.id}}async append(e){this.mountDevtools();const t=du(e,Se);if(t.role==="system")return;const s=t;this.events.messageAppended(s);const n=this.processor.getMessages();if(this.processor.setMessages([...n,s]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;const e=++this.streamGeneration,t=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.currentRunId=t,this.setIsLoading(!0),this.setStatus("submitted"),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;const s=this.abortController.signal;this.pendingToolExecutions.clear();let n=!1,r=null,o=!1;try{const i=this.processor.getMessages(),a=new Map(this.clientToolsRef.current),l=this.context;if(await this.callbacksRef.current.onResponse(),s.aborted)return!1;const u={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId("stream"),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=a,this.activeContext=l,this.processor.prepareAssistantMessage(),this.ensureSubscription();const c=this.waitForProcessing(),d={threadId:this.threadId,runId:t,clientTools:Array.from(a.values()).map(h=>({name:h.name,description:h.description,parameters:h.inputSchema?As(h.inputSchema):{type:"object"}})),forwardedProps:{...u}};if(this.devtoolsBridge.beginRun(d.runId,this.threadId),r=d.runId,this.devtoolsBridge.emitRunLifecycle("run:created",d.runId,"created"),this.devtoolsBridge.emitRunLifecycle("run:started",d.runId,"started"),this.devtoolsBridge.emitSnapshot(),await this.connection.send(i,u,s,d),await c,e!==this.streamGeneration)return!1;if(this.status==="error")return r&&(this.devtoolsBridge.emitRunLifecycle("run:errored",r,"errored",this.error?{error:this.error.message}:{}),o=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),n=!0}catch(i){if(i instanceof Error){if(i.name==="AbortError")return r&&(this.devtoolsBridge.emitRunLifecycle("run:cancelled",r,"cancelled"),o=!0),!1;e===this.streamGeneration&&(this.reportStreamError(i),r&&(this.devtoolsBridge.emitRunLifecycle("run:errored",r,"errored",{error:i.message}),o=!0))}}finally{if(e===this.streamGeneration&&(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.currentRunId=null,this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,r&&!o&&(n?this.devtoolsBridge.emitRunLifecycle("run:completed",r,"completed"):s.aborted&&this.devtoolsBridge.emitRunLifecycle("run:cancelled",r,"cancelled")),await this.drainPostStreamActions(),n)){const i=this.processor.getMessages().at(-1)?.parts.at(-1),{finishReason:a}=this.processor.getState();if(i?.type==="tool-result"&&a!=="stop"&&this.shouldAutoSend())try{await this.checkForContinuation()}catch(l){console.error("Failed to continue flow after tool result:",l)}else this.status!=="ready"&&this.setStatus("ready")}}return n}subscribe(e){const t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus("connecting"),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected")}async reload(){const e=this.processor.getMessages();if(e.length===0)return;const t=e.findLastIndex(s=>s.role==="user");t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){const e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){this.persistor&&(this.persistor.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()):this.activeRunIds.size>0&&this.resetSessionGenerating(),this.persistor.beginClear()),this.processor.clearMessages(),this.persistor?.remove(),this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){const t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t)}async addToolResultForClientTool(e,t,s){if(t&&e.state!=="output-error")try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(n){e={...e,output:null,state:"output-error",errorText:n.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||"output-available",s),this.processor.addToolResult(e.toolCallId,e.output,e.state==="output-error"?e.errorText||"Tool execution failed":void 0),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}validateClientToolOutput(e,t){return e.outputSchema&&Ut(e.outputSchema)?Zl(e.outputSchema,t):t}async addToolApprovalResponse(e){const t=this.processor.getMessages();let s;for(const n of t){const r=n.parts.find(o=>o.type==="tool-call"&&o.approval?.id===e.id);if(r){s=r.id;break}}if(s&&this.events.toolApprovalResponded(e.id,s,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){this.postStreamActions.push(e)}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}shouldAutoSend(){const e=this.processor.getMessages().findLast(t=>t.role==="assistant");return!e||!e.parts.some(t=>t.type==="tool-call")?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){const t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected"),this.connection=lr(dr({connection:e.connection,fetcher:e.fetcher})),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),"context"in e&&(this.context=e.context),e.tools!==void 0){this.clientToolsRef.current=new Map;for(const t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}},hr=Symbol.for("tanstack.ai.devtools.activeBridgeByHookId");function fr(){const e=globalThis,t=e[hr];if(t)return t;const s=new Map;return e[hr]=s,s}var tc=class{options;bridgeId;unsubscribers=[];disposed=!1;superseded=!1;registered=!1;constructor(e){this.options=e,this.bridgeId=sc(e.hookId)}emitRegistered(){this.prepareForMountEmit()&&(this.registered=!0,ke("hook:registered",{...this.createEnvelope("hook:registered"),...this.createMetadataPayload(),lifecycle:"mounted"}))}emitUpdated(){this.prepareForEmit()&&ke("hook:updated",{...this.createEnvelope("hook:updated"),...this.createMetadataPayload(),lifecycle:"active"})}emitSnapshot(){this.prepareForEmit()&&ke("hook:state-snapshot",{...this.createEnvelope("hook:state-snapshot"),...this.createMetadataPayload(),state:this.options.getSnapshot()})}emitToolsRegistered(){if(!this.prepareForEmit())return;const e=this.options.getTools?Array.from(this.options.getTools()).map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema?As(t.inputSchema):{type:"object"},outputSchema:t.outputSchema?As(t.outputSchema):void 0,needsApproval:t.needsApproval,metadata:t.metadata})):[];ke("tools:registered",{...this.createEnvelope("tools:registered"),...this.createMetadataPayload(),tools:e})}emitRunLifecycle(e,t,s,n={}){this.prepareForEmit()&&ke(e,{...this.createEnvelope(e,"client-state",{runId:t}),runId:t,status:s,...n.error?{error:n.error}:{}})}deactivate(){const e=fr();e.get(this.options.hookId)===this&&e.delete(this.options.hookId);for(const t of this.unsubscribers.splice(0))t()}supersede(){this.disposed||(this.superseded=!0,this.disposed=!0,this.deactivate())}dispose(){if(!this.disposed){if(this.disposed=!0,!this.registered){this.deactivate();return}ke("hook:unregistered",{...this.createEnvelope("hook:unregistered"),...this.createMetadataPayload(),reason:"disposed"}),this.deactivate()}}prepareForEmit(){return this.disposed||this.superseded?!1:(this.activate(),!0)}prepareForMountEmit(){return this.superseded?!1:(this.disposed&&(this.disposed=!1,this.registered=!1),this.activate(),!0)}activate(){if(this.disposed)return;const e=fr(),t=e.get(this.options.hookId);t&&t!==this&&(typeof t.supersede=="function"?t.supersede():t.deactivate()),e.set(this.options.hookId,this),!(this.unsubscribers.length>0)&&(this.unsubscribers.push(ut.on("devtools:request-state",s=>{this.handleRequestState(s)})),this.options.applyToolFixture&&this.unsubscribers.push(ut.on("devtools:tool-fixture:apply",s=>{this.handleToolFixtureApply(s)})))}handleRequestState(e){if(this.disposed||this.superseded)return;const t=e.payload.targetHookId;t&&t!==this.options.hookId||(this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot())}async handleToolFixtureApply(e){const t=e.payload;this.matchesFixtureTarget(t)&&await this.options.applyToolFixture?.(t)}matchesFixtureTarget(e){return!e.hookId&&!e.threadId?!1:e.hookId?e.hookId===this.options.hookId:!(e.threadId&&(!this.options.threadId||e.threadId!==this.options.threadId))}createEnvelope(e,t="client-state",s={}){return Fs({eventType:e,source:"client",visibility:t,clientId:this.options.clientId,hookId:this.options.hookId,correlationId:this.bridgeId,...this.options.threadId?{threadId:this.options.threadId}:{},...s.runId?{runId:s.runId}:{},timestamp:Date.now()})}createMetadataPayload(){return{hookId:this.options.hookId,hookName:this.options.metadata.hookName,...this.options.metadata.name?{displayName:this.options.metadata.name}:{},...this.options.metadata.outputKind?{outputKind:this.options.metadata.outputKind}:{},...this.options.metadata.framework?{framework:this.options.metadata.framework}:{}}}},gr=0;function sc(e){const t=globalThis.crypto;return t?.randomUUID?`bridge:${e}:${t.randomUUID()}`:(gr+=1,`bridge:${e}:${gr}`)}var nc=class extends tc{events;chatOptions;currentRunId=null;currentRunThreadId=null;currentStreamId=null;lastStreamId=null;lastRunEventContext;constructor(e){super({...e,applyToolFixture:t=>this.applyFixture(t)}),this.chatOptions=e,this.events=new uc(e.clientId,this)}setCurrentStreamId(e){this.currentStreamId=e,e&&(this.lastStreamId=e)}recordStreamId(e){e&&(this.lastStreamId=e)}mountWithTools(e){this.events.clientCreated(e),this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot()}notifyToolsChanged(){this.emitToolsRegistered(),this.emitSnapshot()}getCurrentStreamId(){return this.currentStreamId}getLastStreamId(){return this.lastStreamId}resolveStreamId(){return this.currentStreamId??this.lastStreamId??this.chatOptions.generateId("stream")}beginRun(e,t){this.currentRunId=e,this.currentRunThreadId=t,this.lastRunEventContext={runId:e,threadId:t}}observeChunk(e){if(e.type==="RUN_STARTED"){this.beginRun(e.runId,e.threadId);return}if(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR"){const t=(e.type==="RUN_FINISHED",e.runId);if(!t||t===this.currentRunId){const s=this.getCurrentRunEventContext();s&&(this.lastRunEventContext=s),this.currentRunId=null,this.currentRunThreadId=null}}}getCurrentRunEventContext(){if(this.currentRunId)return{threadId:this.currentRunThreadId??this.chatOptions.threadId??"",runId:this.currentRunId}}getCurrentOrLastRunEventContext(){return this.getCurrentRunEventContext()??this.lastRunEventContext}findToolCallContext(e){const t={toolCallId:e},s=this.getCurrentRunEventContext();return s?{threadId:s.threadId,runId:s.runId,toolCallId:e}:this.chatOptions.threadId?{threadId:this.chatOptions.threadId,toolCallId:e}:t}async applyFixture(e){const t=this.chatOptions.getMessages(),s=e.threadId??this.chatOptions.threadId??"";if(e.execute){await this.executeFixture(e,t,s);return}const{message:n,toolCallId:r}=this.createReplayMessageFromFixture(e,t),o=n.id;this.events.messageAppended(n,void 0,{threadId:s,toolCallId:r,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,n]),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:s,...e.runId?{runId:e.runId}:{},toolName:e.toolName,input:e.input,output:e.output,messageId:o,toolCallId:r,...e.execute!==void 0?{execute:e.execute}:{},...e.message?{message:e.message}:{},...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}async executeFixture(e,t,s){const n=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),o={id:r,role:"assistant",parts:[{type:"tool-call",id:n,name:e.toolName,arguments:hs(e.input),input:e.input,state:"input-complete"}],createdAt:new Date};this.events.messageAppended(o,void 0,{threadId:s,toolCallId:n,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,o]),this.emitSnapshot();const i=this.findClientTool(e.toolName)?.execute;if(!i){console.warn(`[ai-devtools] tool fixture "${e.toolName}" requested execute=true but no client tool implementation is registered; replaying saved output instead.`),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:e.output,errorText:e.errorText});return}let a;try{a=await i(e.input)}catch(l){console.error(`[ai-devtools] tool fixture "${e.toolName}" execute threw`,l),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:null,errorText:l instanceof Error?`${l.name}: ${l.message}`:`Tool execution failed: ${String(l)}`});return}this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:a})}addToolResultForFixture(e){const t=e.errorText?"output-error":"output-available";this.events.toolResultAdded(e.toolCallId,e.fixture.toolName,e.output,t,{threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolCallId:e.toolCallId}),this.chatOptions.addToolResult(e.toolCallId,e.output,e.errorText),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolName:e.fixture.toolName,input:e.fixture.input,output:e.output,execute:!0,messageId:e.messageId,toolCallId:e.toolCallId,...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}createReplayMessageFromFixture(e,t){const s=this.cloneFixtureSourceMessage(e,t);if(s)return s;const n=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),o=e.errorText?"error":"complete";return{toolCallId:n,message:{id:r,role:"assistant",parts:[{type:"tool-call",id:n,name:e.toolName,arguments:hs(e.input),input:e.input,state:"input-complete",output:e.output},{type:"tool-result",toolCallId:n,content:hs(e.output),state:o,...e.errorText?{error:e.errorText}:{}}],createdAt:new Date}}}cloneFixtureSourceMessage(e,t){const s=e.message;if(!s||!Array.isArray(s.parts))return;const n=this.createFixtureToolCallIdMap(s.parts,t),r=s.parts.map(a=>oc(a,n)).filter(a=>!!a),o=e.toolCallId?n.get(e.toolCallId):void 0;if(ac(r,{...o?{mappedToolCallId:o}:{},output:e.output}),r.length===0)return;const i=(e.toolCallId?n.get(e.toolCallId):void 0)??ic(r);if(i)return{toolCallId:i,message:{id:this.resolveFixtureMessageId(s.id,t),role:s.role,parts:r,createdAt:new Date}}}createFixtureToolCallIdMap(e,t){const s=new Map;for(const n of e)!wo(n)||n.type!=="tool-call"||typeof n.id=="string"&&s.set(n.id,this.resolveFixtureToolCallId(n.id,t));return s}resolveFixtureMessageId(e,t){return e&&!t.some(s=>s.id===e)?e:this.chatOptions.generateId("fixture-msg")}resolveFixtureToolCallId(e,t){return e&&!lc(t,e)?e:this.chatOptions.generateId("fixture-tool-call")}findClientTool(e){const t=this.chatOptions.getTools?.();if(t){for(const s of t)if(s.name===e)return s}}};function wo(e){return typeof e=="object"&&e!==null}function hs(e){if(typeof e=="string")return e;if(e===void 0||typeof e=="function"||typeof e=="symbol")return String(e);try{return JSON.stringify(e)}catch(t){return console.error("[ai-devtools] failed to JSON.stringify fixture value; falling back to String(). Tool call arguments may be malformed.",{error:t,value:e}),String(e)}}function rc(e){try{return JSON.parse(e)}catch(t){return console.error("[ai-devtools] failed to JSON.parse fixture result content; replaying as raw string. Fixture payload may be corrupted.",{error:t,content:e}),e}}function oc(e,t){if(!wo(e)||typeof e.type!="string")return;const s={...e};return e.type==="tool-call"&&typeof e.id=="string"&&(s.id=t.get(e.id)??e.id),e.type==="tool-result"&&typeof e.toolCallId=="string"&&(s.toolCallId=t.get(e.toolCallId)??e.toolCallId),s}function ic(e){const t=e.find(s=>s.type==="tool-call");return t?.type==="tool-call"?t.id:void 0}function ac(e,t){for(const s of e){if(s.type!=="tool-result")continue;const n=e.find(r=>r.type==="tool-call"&&r.id===s.toolCallId&&r.output===void 0);n&&(n.output=Array.isArray(s.content)?s.content:rc(s.content))}if(t.mappedToolCallId&&t.output!==void 0){const s=e.find(n=>n.type==="tool-call"&&n.id===t.mappedToolCallId&&n.output===void 0);s&&(s.output=t.output)}}function lc(e,t){return e.some(s=>s.parts.some(n=>n.type==="tool-call"?n.id===t:n.type==="tool-result"?n.toolCallId===t:!1))}var uc=class extends $u{constructor(e,t){super(e),this.helper=t}helper;afterEmit(e){e&&this.helper.recordStreamId(e),this.helper.emitSnapshot()}textUpdated(e,t,s,n){super.textUpdated(e,t,s,n??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}thinkingUpdated(e,t,s,n,r){super.thinkingUpdated(e,t,s,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}messageAppended(e,t,s){super.messageAppended(e,t,s??this.helper.getCurrentRunEventContext()),this.afterEmit(t)}toolCallStateChanged(e,t,s,n,r,o,i){super.toolCallStateChanged(e,t,s,n,r,o,i??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}structuredOutputChanged(e,t,s,n,r){super.structuredOutputChanged(e,t,s,n,r??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(t)}approvalRequested(e,t,s,n,r,o,i){super.approvalRequested(e,t,s,n,r,o,i??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(e)}toolResultAdded(e,t,s,n,r){super.toolResultAdded(e,t,s,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit()}toolApprovalResponded(e,t,s,n){super.toolApprovalResponded(e,t,s,n??this.helper.getCurrentRunEventContext()),this.afterEmit()}clientCreated(e){super.clientCreated(e),this.afterEmit()}loadingChanged(e){super.loadingChanged(e),this.afterEmit()}errorChanged(e){super.errorChanged(e),this.afterEmit()}reloaded(e){super.reloaded(e),this.afterEmit()}stopped(){super.stopped(),this.afterEmit()}messagesCleared(){super.messagesCleared(),this.afterEmit()}messageSent(e,t){super.messageSent(e,t),this.afterEmit()}toolFixtureApplied(e){super.toolFixtureApplied(e),this.afterEmit()}};function cc(e){return new nc(e)}function Oc(e){const t=(0,w.useId)(),s=e.id||t,[n,r]=(0,w.useState)(e.initialMessages||[]),[o,i]=(0,w.useState)(!1),[a,l]=(0,w.useState)(void 0),[u,c]=(0,w.useState)("ready"),[d,h]=(0,w.useState)(!1),[f,g]=(0,w.useState)("disconnected"),[p,v]=(0,w.useState)(!1),m=(0,w.useRef)(e.initialMessages||[]),S=(0,w.useRef)(!0),C=(0,w.useRef)(null),I=(0,w.useRef)(null);m.current=n;const y=(0,w.useRef)(e);y.current=e;const R=(0,w.useMemo)(()=>{const F=e.initialMessages||[];S.current=!1;const L=y.current,B=new ec({devtoolsBridgeFactory:cc,...L.connection?{connection:L.connection}:{fetcher:L.fetcher},id:s,initialMessages:F,...L.body!==void 0&&{body:L.body},...L.threadId!==void 0&&{threadId:L.threadId},...L.forwardedProps!==void 0&&{forwardedProps:L.forwardedProps},...L.persistence!==void 0&&{persistence:L.persistence},...L.context!==void 0&&{context:L.context},devtools:{...L.devtools,framework:"react",hookName:"useChat",outputKind:L.outputSchema?"structured":"chat"},onResponse:N=>{C.current===B&&y.current.onResponse?.(N)},onChunk:N=>{C.current===B&&y.current.onChunk?.(N)},onFinish:N=>{C.current===B&&y.current.onFinish?.(N)},onError:N=>{C.current===B&&y.current.onError?.(N)},...L.tools!==void 0&&{tools:L.tools},onCustomEvent:(N,he,fe)=>{C.current===B&&y.current.onCustomEvent?.(N,he,fe)},...e.streamProcessor!==void 0&&{streamProcessor:e.streamProcessor},onMessagesChange:N=>{C.current===B&&r(N)},onLoadingChange:N=>{C.current===B&&i(N)},onErrorChange:N=>{C.current===B&&l(N)},onStatusChange:N=>{C.current===B&&c(N)},onSubscriptionChange:N=>{C.current===B&&h(N)},onConnectionStatusChange:N=>{C.current===B&&g(N)},onSessionGeneratingChange:N=>{C.current===B&&v(N)}});return C.current=B,B},[s]);(0,w.useEffect)(()=>{const F=R.getMessages();F!==m.current&&r(F)},[R]),(0,w.useEffect)(()=>{R.updateOptions({body:e.body})},[R,e.body]),(0,w.useEffect)(()=>{e.forwardedProps!==void 0&&R.updateOptions({forwardedProps:e.forwardedProps})},[R,e.forwardedProps]),(0,w.useEffect)(()=>{e.tools!==void 0&&R.updateOptions({tools:e.tools})},[R,e.tools]),(0,w.useEffect)(()=>{R.updateOptions({context:e.context})},[R,e.context]),(0,w.useEffect)(()=>{e.live?R.subscribe():R.unsubscribe()},[R,e.live]),(0,w.useEffect)(()=>(I.current&&(clearTimeout(I.current),I.current=null),C.current=R,R.mountDevtools(),()=>{I.current=setTimeout(()=>{C.current===R&&(C.current=null),I.current=null},0),y.current.live?R.unsubscribe():R.stop(),R.dispose()}),[R]);const b=(0,w.useCallback)(async F=>{await R.sendMessage(F)},[R]),_=(0,w.useCallback)(async F=>{await R.append(F)},[R]),M=(0,w.useCallback)(async()=>{await R.reload()},[R]),P=(0,w.useCallback)(()=>{R.stop()},[R]),E=(0,w.useCallback)(()=>{R.clear()},[R]),O=(0,w.useCallback)(F=>{R.setMessagesManually(F)},[R]),se=(0,w.useCallback)(async F=>{await R.addToolResult(F)},[R]),H=(0,w.useCallback)(async F=>{await R.addToolApprovalResponse(F)},[R]),j=R.getMessages(),Z=(0,w.useMemo)(()=>{let F=-1;for(let L=j.length-1;L>=0;L--)if(j[L]?.role==="user"){F=L;break}if(F===-1)return null;for(let L=j.length-1;L>F;L--){const B=j[L];if(B?.role!=="assistant")continue;const N=B.parts.find(he=>he.type==="structured-output");if(N)return N}return null},[j]);return{messages:j,sendMessage:b,append:_,reload:M,stop:P,isLoading:o,error:a,status:u,isSubscribed:d,connectionStatus:f,sessionGenerating:p,setMessages:O,clear:E,addToolResult:se,addToolApprovalResponse:H,partial:(0,w.useMemo)(()=>Z?Z.partial??Z.data??{}:{},[Z]),final:(0,w.useMemo)(()=>!Z||Z.status!=="complete"?null:Z.data,[Z])}}var Lc=new Uint8Array(128).fill(128);export{gc as C,pc as S,Qr as _,Pc as a,mc as b,_c as c,Ha as d,Ic as f,Xr as g,eo as h,xc as i,bc as l,Cc as m,Ac as n,Mc as o,Rc as p,Tc as r,Ec as s,Oc as t,wc as u,yc as v,_r as x,Sc as y};
|