gitxp 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.output/nitro.json +17 -0
  2. package/.output/public/assets/index-BGHvBNtP.js +11 -0
  3. package/.output/public/assets/routes-DuE8S6pX.js +60 -0
  4. package/.output/public/assets/styles-D5xbQNYu.css +1 -0
  5. package/.output/server/_chunks/ssr-renderer.mjs +26 -0
  6. package/.output/server/_libs/@floating-ui/core+[...].mjs +671 -0
  7. package/.output/server/_libs/@floating-ui/dom+[...].mjs +649 -0
  8. package/.output/server/_libs/@floating-ui/react-dom+[...].mjs +856 -0
  9. package/.output/server/_libs/@radix-ui/react-arrow+[...].mjs +258 -0
  10. package/.output/server/_libs/@radix-ui/react-dialog+[...].mjs +1862 -0
  11. package/.output/server/_libs/@radix-ui/react-popper+[...].mjs +320 -0
  12. package/.output/server/_libs/@radix-ui/react-tooltip+[...].mjs +534 -0
  13. package/.output/server/_libs/@tanstack/db+[...].mjs +14680 -0
  14. package/.output/server/_libs/@tanstack/react-router+[...].mjs +14563 -0
  15. package/.output/server/_libs/@tanstack/react-router-ssr-query+[...].mjs +126 -0
  16. package/.output/server/_libs/@tanstack/router-core+[...].mjs +3636 -0
  17. package/.output/server/_libs/class-variance-authority+clsx.mjs +69 -0
  18. package/.output/server/_libs/cmdk.mjs +504 -0
  19. package/.output/server/_libs/h3+rou3+srvx.mjs +1361 -0
  20. package/.output/server/_libs/h3-v2.mjs +285 -0
  21. package/.output/server/_libs/lucide-react.mjs +158 -0
  22. package/.output/server/_libs/radix-ui__primitive.mjs +44 -0
  23. package/.output/server/_libs/radix-ui__react-context.mjs +108 -0
  24. package/.output/server/_libs/tailwind-merge.mjs +3380 -0
  25. package/.output/server/_libs/tanstack__history.mjs +384 -0
  26. package/.output/server/_libs/tanstack__query-core.mjs +2225 -0
  27. package/.output/server/_libs/tanstack__react-db.mjs +242 -0
  28. package/.output/server/_libs/tanstack__react-query.mjs +140 -0
  29. package/.output/server/_libs/ufo.mjs +64 -0
  30. package/.output/server/_runtime.mjs +35 -0
  31. package/.output/server/_ssr/empty-plugin-adapters-D9UWiqvJ.mjs +5 -0
  32. package/.output/server/_ssr/events-BNrmOvgU.mjs +13 -0
  33. package/.output/server/_ssr/notifications-DUoENv6E.mjs +514 -0
  34. package/.output/server/_ssr/router-DsUHD4bT.mjs +179 -0
  35. package/.output/server/_ssr/routes-DIFfr242.mjs +982 -0
  36. package/.output/server/_ssr/ssr.mjs +1854 -0
  37. package/.output/server/_ssr/start-5Z2QO8AU.mjs +4 -0
  38. package/.output/server/_tanstack-start-manifest_v-CrD0YpZr.mjs +20 -0
  39. package/.output/server/index.mjs +310 -0
  40. package/.output/server/node_modules/tslib/modules/index.js +70 -0
  41. package/.output/server/node_modules/tslib/modules/package.json +3 -0
  42. package/.output/server/node_modules/tslib/package.json +47 -0
  43. package/.output/server/node_modules/tslib/tslib.js +484 -0
  44. package/.output/server/package.json +9 -0
  45. package/LICENSE +21 -0
  46. package/README.md +325 -0
  47. package/bin/gitxp.js +85 -0
  48. package/package.json +92 -0
@@ -0,0 +1,60 @@
1
+ import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,S as s,T as c,_ as l,a as u,b as d,c as f,d as p,f as m,g as h,h as g,i as _,j as v,k as y,l as b,m as x,n as S,o as C,p as w,r as T,s as E,t as D,u as O,v as k,w as A,x as j,y as M}from"./index-BGHvBNtP.js";var N=class extends h{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),ee(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return F(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return F(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let n=this.options,r=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof s(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),n._defaulted&&!t(this.options,n)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let i=this.hasListeners();i&&te(this.#t,r,this.options,n)&&this.#m(),this.updateResult(),i&&(this.#t!==r||s(this.options.enabled,this.#t)!==s(n.enabled,this.#t)||s(this.options.staleTime,this.#t)!==s(n.staleTime,this.#t))&&this.#g();let a=this.#_();i&&(this.#t!==r||s(this.options.enabled,this.#t)!==s(n.enabled,this.#t)||a!==this.#f)&&this.#v(a)}getOptimisticResult(e){let n=this.#e.getQueryCache().build(this.#e,e),r=this.createResult(n,e);return t(this.getCurrentResult(),r)||(this.#r=r,this.#a=this.options,this.#i=this.#t.state),r}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(d)),t}#h(e){return!l()&&s(this.options.enabled,this.#t)!==!1&&M(e)}#g(){this.#b();let e=s(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=c(this.#r.dataUpdatedAt,e)+1;this.#u=r.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#f=e,!(this.#f===0||!this.#h(this.#f))&&(this.#d=r.setInterval(()=>{(this.options.refetchIntervalInBackground||g.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(r.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(r.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,c=e===n?this.#n:e.state,{state:l}=e,u={...l},d=!1,f;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&ee(e,t),o=i&&te(e,n,t,r);(a||o)&&(u={...u,...w(l.data,e.options)}),t._optimisticResults===`isRestoring`&&(u.fetchStatus=`idle`)}let{error:p,errorUpdatedAt:m,status:h}=u;f=u.data;let g=!1;if(t.placeholderData!==void 0&&f===void 0&&h===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,g=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(h=`success`,f=j(i?.data,e,t),d=!0)}if(t.select&&f!==void 0&&!g){if(i&&f===a?.data&&t.select===this.#s)f=this.#c;else try{this.#s=t.select,f=t.select(f),f=j(i?.data,f,t),this.#c=f,this.#o=null}catch(e){this.#o=e}}else f===void 0&&(this.#o=null);this.#o&&(p=this.#o,f=this.#c,m=Date.now(),h=`error`,d=!1);let _=u.fetchStatus===`fetching`,v=h===`pending`,y=h===`error`,b=v&&_,x=f!==void 0;return{status:h,fetchStatus:u.fetchStatus,isPending:v,isSuccess:h===`success`,isError:y,isInitialLoading:b,isLoading:b,data:f,dataUpdatedAt:u.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:_,isRefetching:_&&!v,isLoadingError:y&&!x,isPaused:u.fetchStatus===`paused`,isPlaceholderData:d,isRefetchError:y&&x,isStale:ne(e,t),refetch:this.refetch,isEnabled:s(t.enabled,e)!==!1}}updateResult(){let e=this.#r,n=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),t(n,e))return;this.#r=n;let r=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();x.batch(()=>{r&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function P(e,t){return s(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||s(t.retryOnMount,e)!==!1)}function ee(e,t){return P(e,t)||e.state.data!==void 0&&F(e,t,t.refetchOnMount)}function F(e,t,n){if(s(t.enabled,e)!==!1&&s(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&ne(e,t)}return!1}function te(e,t,n,r){return(e!==t||s(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&ne(e,n)}function ne(e,t){return s(t.enabled,e)!==!1&&e.isStaleByTime(s(t.staleTime,e))}var re=class extends h{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let n=this.options;this.options=this.#e.defaultMutationOptions(e),t(this.options,n)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&k(n.mutationKey)!==k(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??m();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){x.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},I=a(i(),1),ie=I.createContext(!1),ae=()=>I.useContext(ie);ie.Provider;var L=e();function oe(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var R=I.createContext(oe()),se=()=>I.useContext(R),ce=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?A(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},le=e=>{I.useEffect(()=>{e.clearReset()},[e])},ue=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||A(n,[e.error,r])),de=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},fe=(e,t)=>e?.suspense&&t.isPending,pe=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function me(e,t,r){let i=ae(),a=se(),o=n(r),s=o.defaultQueryOptions(e),c=o.getQueryCache().get(s.queryHash),l=e.subscribed!==!1;s._optimisticResults=i?`isRestoring`:l?`optimistic`:void 0,de(s),ce(s,a,c),le(a);let[u]=I.useState(()=>new t(o,s)),f=u.getOptimisticResult(s),p=!i&&l;if(I.useSyncExternalStore(I.useCallback(e=>{let t=p?u.subscribe(x.batchCalls(e)):d;return u.updateResult(),t},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),I.useEffect(()=>{u.setOptions(s)},[s,u]),fe(s,f))throw pe(s,u,a);if(ue({result:f,errorResetBoundary:a,throwOnError:s.throwOnError,query:c,suspense:s.suspense}))throw f.error;return s.notifyOnChangeProps?f:u.trackResult(f)}function he(e,t){return me(e,N,t)}function ge(e,t){let r=n(t),[i]=I.useState(()=>new re(r,e));I.useEffect(()=>{i.setOptions(e)},[i,e]);let a=I.useSyncExternalStore(I.useCallback(e=>i.subscribe(x.batchCalls(e)),[i]),()=>i.getCurrentResult(),()=>i.getCurrentResult()),o=I.useCallback((...e)=>{i.mutate(e[0],e[1]).catch(d)},[i]);if(a.error&&A(i.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:o,mutateAsync:a.mutate}}var _e=`__includes_scalar__`,ve=0,ye=class{},be=class extends ye{constructor(e,t){super(),this.collection=e,this.alias=t,this.type=`collectionRef`,Object.defineProperty(this,"sourceId",{value:`source-${++ve}`,enumerable:!1})}},xe=class extends ye{constructor(e,t){super(),this.query=e,this.alias=t,this.type=`queryRef`}},Se=class extends ye{constructor(e){super(),this.sources=e,this.type=`unionFrom`}get alias(){return this.sources[0]?.alias??``}},Ce=class extends ye{constructor(e){super(),this.queries=e,this.type=`unionAll`}get alias(){return``}},z=class extends ye{constructor(e){super(),this.path=e,this.type=`ref`}},we=class extends ye{constructor(e){super(),this.value=e,this.type=`val`}},Te=class extends ye{constructor(e,t){super(),this.name=e,this.args=t,this.type=`func`}},Ee=class extends ye{constructor(e,t){super(),this.name=e,this.args=t,this.type=`agg`}},De=class extends ye{constructor(e,t,n,r,i,a,o=`collection`,s){super(),this.query=e,this.correlationField=t,this.childCorrelationField=n,this.fieldName=r,this.parentFilters=i,this.parentProjection=a,this.materialization=o,this.scalarField=s,this.type=`includesSubquery`}},Oe=class extends ye{constructor(e,t){super(),this.branches=e,this.defaultValue=t,this.type=`conditionalSelect`}};function ke(e){return e instanceof Ee||e instanceof Oe||e instanceof Te||e instanceof z||e instanceof we||e instanceof De?!0:!e||typeof e!=`object`?!1:e.type===`conditionalSelect`?Array.isArray(e.branches):e.type===`agg`||e.type===`func`?typeof e.name==`string`&&Array.isArray(e.args):e.type===`ref`?Array.isArray(e.path):e.type===`val`?`value`in e:e.type===`includesSubquery`&&`query`in e&&`fieldName`in e}function Ae(e){let t=[],n=new Set,r=e=>{e.type===`collectionRef`?n.has(e.sourceId)||(n.add(e.sourceId),t.push(e)):e.type===`queryRef`?a(e.query):e.type===`unionFrom`?e.sources.forEach(r):e.queries.forEach(a)},i=e=>{e instanceof De?a(e.query):e instanceof Oe?(e.branches.forEach(e=>i(e.value)),e.defaultValue!==void 0&&i(e.defaultValue)):typeof e==`object`&&e&&!Array.isArray(e)&&!ke(e)&&e.__refProxy!==!0&&Object.values(e).forEach(i)},a=e=>{r(e.from),e.join?.forEach(({from:e})=>r(e)),e.select&&Object.values(e.select).forEach(i)};return a(e),t}function je(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Me(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Ne(e){return typeof e==`object`&&`expression`in e&&e.residual===!0}function Pe(e){return{expression:e,residual:!0}}function Fe(e,t){if(e.from.type===`unionFrom`){for(let n of e.from.sources)if(n.alias===t)return n}else if(e.from.type!==`unionAll`&&e.from.alias===t)return e.from;for(let n of e.join||[])if(n.from.alias===t)return n.from}function Ie(e,t,n){if(t.path.length!==0){if(t.path.length===1){let r=t.path[0];if(e.select){let t=e.select[r];if(t&&t.type===`ref`)return Ie(e,t,n)}return{collection:n,path:[r]}}if(t.path.length>1){let[r,...i]=t.path,a=Fe(e,r);return a?a.type===`queryRef`?Ie(a.query,new z(i),n):{collection:a.collection,path:i,alias:r,sourceId:a.sourceId}:void 0}}}function Le(){let e=typeof globalThis<`u`?globalThis.crypto:void 0;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();if(e&&typeof e.getRandomValues==`function`){let t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[];for(let e=0;e<16;e++)n.push(t[e].toString(16).padStart(2,`0`));return n.slice(0,4).join(``)+`-`+n.slice(4,6).join(``)+`-`+n.slice(6,8).join(``)+`-`+n.slice(8,10).join(``)+`-`+n.slice(10,16).join(``)}throw Error(`No secure random number generator available: neither crypto.randomUUID nor crypto.getRandomValues is defined in this environment.`)}var Re=class extends Error{constructor(e){super(e),this.name=`TanStackDBError`}},ze=class extends Re{constructor(e,t,n){let r=`${e===`insert`?`Insert`:`Update`} validation failed: ${t.map(e=>`
2
+ - ${e.message} - path: ${e.path}`).join(``)}`;super(n||r),this.name=`SchemaValidationError`,this.type=e,this.issues=t}},Be=class extends Re{constructor(e){super(e),this.name=`CollectionConfigurationError`}},Ve=class extends Be{constructor(){super(`Collection requires a config`)}},He=class extends Be{constructor(){super(`Collection requires a sync config`)}},Ue=class extends Be{constructor(){super(`Schema must implement the standard-schema interface`)}},We=class extends Be{constructor(){super(`Schema validation must be synchronous`)}},Ge=class extends Re{constructor(e){super(e),this.name=`CollectionStateError`}},Ke=class extends Ge{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}},qe=class extends Ge{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}},Je=class extends Ge{constructor(){super(`Collection is in error state`)}},Ye=class extends Ge{constructor(){super(`Active subscribers count is negative - this should never happen`)}},Xe=class extends Ge{constructor(){super(`Cannot subscribe to a disposed LiveQueryObserver`)}},Ze=class extends Re{constructor(e){super(e),this.name=`CollectionOperationError`}},Qe=class extends Ze{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}},$e=class extends Ze{constructor(e,t){super(`getKey returned an invalid key type. Expected string or number, but got ${e===null?`null`:typeof e}: ${JSON.stringify(e)}. Item: ${JSON.stringify(t)}`)}},et=class extends Ze{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}},tt=class extends Ze{constructor(e,t,n){let r=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${t}"`;n?.hasCustomGetKey&&n.hasDistinct?super(`${r}. This collection uses a custom getKey with .distinct(). The .distinct() operator deduplicates by the ENTIRE selected object (standard SQL behavior), but your custom getKey extracts only a subset of fields. This causes multiple distinct rows (with different values in non-key fields) to receive the same key. To fix this, either: (1) ensure your SELECT only includes fields that uniquely identify each row, (2) use .groupBy() with min()/max() aggregates to select one value per group, or (3) remove the custom getKey to use the default key behavior.`):n?.hasCustomGetKey&&n.hasJoins?super(`${r}. This collection uses a custom getKey with joined queries. Joined queries can produce multiple rows with the same key when relationships are not 1:1. Consider: (1) using a composite key in your getKey function (e.g., \`\${item.key1}-\${item.key2}\`), (2) ensuring your join produces unique rows per key, or (3) removing the custom getKey to use the default composite key behavior.`):super(r)}},nt=class extends Ze{constructor(){super(`The first argument to update is missing`)}},rt=class extends Ze{constructor(){super(`No keys were passed to update`)}},it=class extends Ze{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}},at=class extends Ze{constructor(e,t){super(`Updating the key of an item is not allowed. Original key: "${e}", Attempted new key: "${t}". Please delete the old item and create a new one if a key change is necessary.`)}},ot=class extends Ze{constructor(){super(`No keys were passed to delete`)}},st=class extends Ze{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}},ct=class extends Re{constructor(e){super(e),this.name=`MissingHandlerError`}},lt=class extends ct{constructor(){super(`Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.`)}},ut=class extends ct{constructor(){super(`Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.`)}},dt=class extends ct{constructor(){super(`Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.`)}},ft=class extends Re{constructor(e){super(e),this.name=`TransactionError`}},pt=class extends ft{constructor(){super(`mutationFn is required when creating a transaction`)}},mt=class extends ft{constructor(){super(`You can no longer call .mutate() as the transaction is no longer pending`)}},ht=class extends ft{constructor(){super(`You can no longer call .rollback() as the transaction is already completed`)}},gt=class extends ft{constructor(){super(`You can no longer call .commit() as the transaction is no longer pending`)}},_t=class extends ft{constructor(){super(`No pending sync transaction to write to`)}},vt=class extends ft{constructor(){super(`The pending sync transaction is already committed, you can't still write to it.`)}},yt=class extends ft{constructor(){super(`No pending sync transaction to commit`)}},bt=class extends ft{constructor(){super(`The pending sync transaction is already committed, you can't commit it again.`)}},xt=class extends Re{constructor(e){super(e),this.name=`QueryBuilderError`}},St=class extends xt{constructor(e){super(`Only one source is allowed in the ${e}`)}},Ct=class extends xt{constructor(e){super(`A sub query passed to a ${e} must have a from clause itself`)}},wt=class extends xt{constructor(e){super(`Invalid source for live query: The value provided for alias "${e}" is not a Collection or subquery. Live queries only accept Collection instances or subqueries. Please ensure you're passing a valid Collection or QueryBuilder, not a plain array or other data type.`)}},Tt=class extends xt{constructor(e,t){super(`Invalid source for ${e}: Expected ${e===`unionAll clause`?`an object with one or more key-value pairs like { alias: collection }`:`an object with a single key-value pair like { alias: collection }`}. For example: ${e===`unionAll clause`?`.unionAll({ todos: todosCollection, events: eventsCollection })`:e===`join clause`?`.join({ todos: todosCollection }, ({ todo, todos }) => eq(todo.id, todos.id))`:`.from({ todos: todosCollection })`}. Got: ${t}`)}},Et=class extends xt{constructor(){super(`Join condition must be an equality expression`)}},Dt=class extends xt{constructor(){super(`Query must have a from clause`)}},Ot=class extends xt{constructor(e){super(`Invalid where() expression: Expected a query expression, but received a ${e}. This usually happens when using JavaScript's comparison operators (===, !==, <, >, etc.) directly. Instead, use the query builder functions:
3
+
4
+ ❌ .where(({ user }) => user.id === 'abc')
5
+ ✅ .where(({ user }) => eq(user.id, 'abc'))
6
+
7
+ Available comparison functions: eq, gt, gte, lt, lte, and, or, not, like, ilike, isNull, isUndefined`)}},kt=class extends Re{constructor(e){super(e),this.name=`QueryCompilationError`}},At=class extends kt{constructor(e){super(`Unsafe alias path segment "${e}" is not allowed in .select(). Aliases must not contain "__proto__", "prototype", or "constructor".`),this.name=`UnsafeAliasPathError`}},jt=class extends kt{constructor(){super(`DISTINCT requires a SELECT clause.`)}},Mt=class extends kt{constructor(){super(`fn.select() cannot be used with groupBy(). groupBy requires the compiler to statically analyze aggregate functions (count, sum, max, etc.) in the SELECT clause, which is not possible with fn.select() since it is an opaque function. Use .select() instead of .fn.select() when combining with groupBy().`)}},Nt=class extends kt{constructor(e){super(`fn.select() cannot return ${e}. Child query builders, query expressions, and helpers such as eq(), toArray(), materialize(), concat(toArray()), and caseWhen() are query-construction values. Use them as direct fields in .select() instead.`)}},Pt=class extends kt{constructor(){super(`Top-level scalar select() is not supported by createLiveQueryCollection() or queryOnce(). Return an object from .select(), or use the scalar query inside toArray(...) or concat(toArray(...)).`)}},Ft=class extends kt{constructor(){super(`HAVING clause requires GROUP BY clause`)}},It=class extends kt{constructor(){super(`LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results`)}},Lt=class extends kt{constructor(e,t,n){let r=t?`alias "${e}" (collection "${t}")`:`collection "${e}"`,i=n?.length?`. Available keys: ${n.join(`, `)}`:``;super(`Input for ${r} not found in inputs map${i}`)}},Rt=class extends kt{constructor(e,t){super(`Subquery uses alias "${e}" which is already used in the parent query. Each alias must be unique across parent and subquery contexts. Parent query aliases: ${t.join(`, `)}. Please rename "${e}" in either the parent query or subquery to avoid conflicts.`)}},zt=class extends kt{constructor(e){super(`Unsupported FROM type: ${e}`)}},Bt=class extends kt{constructor(e){super(`Unknown expression type: ${e}`)}},Vt=class extends kt{constructor(){super(`Reference path cannot be empty`)}},Ht=class extends kt{constructor(e){super(`Unknown function: ${e}`)}},Ut=class extends kt{constructor(e){super(`Collection "${e}" not found during compilation of join`)}},Wt=class extends Re{constructor(e){super(e),this.name=`JoinError`}},Gt=class extends Wt{constructor(e){super(`Unsupported join type: ${e}`)}},Kt=class extends Wt{constructor(e){super(`Invalid join condition: both expressions refer to the same source "${e}"`)}},qt=class extends Wt{constructor(){super(`Invalid join condition: expressions must reference source aliases`)}},Jt=class extends Wt{constructor(e){super(`Invalid join condition: left expression refers to an unavailable source "${e}"`)}},Yt=class extends Wt{constructor(e){super(`Invalid join condition: right expression does not refer to the joined source "${e}"`)}},Xt=class extends Wt{constructor(){super(`Invalid join condition`)}},Zt=class extends Wt{constructor(e){super(`Unsupported join source type: ${e}`)}},Qt=class extends Re{constructor(e){super(e),this.name=`GroupByError`}},$t=class extends Qt{constructor(e){super(`Non-aggregate expression '${e}' in SELECT must also appear in GROUP BY clause`)}},en=class extends Qt{constructor(e){super(`Unsupported aggregate function: ${e}`)}},tn=class extends Qt{constructor(e){super(`Aggregate function in HAVING clause must also be in SELECT clause: ${e}`)}},nn=class extends Qt{constructor(e){super(`Unknown expression type in HAVING clause: ${e}`)}},rn=class extends Re{constructor(e,t){let n=t instanceof Error?t.message:String(t);super(`Collection "${e}" sync cleanup function threw an error: ${n}`),this.name=`SyncCleanupError`}},an=class extends Error{constructor(){super(`Sync transaction was aborted before application`),this.name=`AbortError`}},on=class extends Re{constructor(e){super(e),this.name=`QueryOptimizerError`}},sn=class extends on{constructor(){super(`Cannot combine empty expression list`)}},cn=class extends kt{constructor(e){super(`Internal error: compiler returned aliases without inputs: ${e.join(`, `)}. This indicates a bug in query compilation. Please report this issue.`)}},ln=class extends kt{constructor(){super(`setWindow() can only be called on collections with an ORDER BY clause. Add .orderBy() to your query to enable window movement.`)}};function B(e,t){return un(e,t,new Map)}function un(e,t,n){if(e===t)return!0;if(e==null||t==null||typeof e!=typeof t)return!1;if(e instanceof Date)return t instanceof Date&&e.getTime()===t.getTime();if(t instanceof Date)return!1;if(e instanceof RegExp)return t instanceof RegExp&&e.source===t.source&&e.flags===t.flags;if(t instanceof RegExp)return!1;if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let r=Array.from(e.entries()).every(([e,r])=>t.has(e)&&un(r,t.get(e),n));return n.delete(e),r}if(t instanceof Map)return!1;if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let r=Array.from(e),i=Array.from(t);if(r.every(e=>typeof e!=`object`))return n.delete(e),r.every(e=>t.has(e));let a=r.length===i.length;return n.delete(e),a}if(t instanceof Set)return!1;if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(t)&&!(e instanceof DataView)&&!(t instanceof DataView)){let n=e,r=t;if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==r[e])return!1;return!0}if(ArrayBuffer.isView(t)&&!(t instanceof DataView)&&!ArrayBuffer.isView(e))return!1;if(fn(e)&&fn(t))return e[Symbol.toStringTag]===t[Symbol.toStringTag]?typeof e.equals==`function`?e.equals(t):e.toString()===t.toString():!1;if(fn(t))return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let r=e.every((e,r)=>un(e,t[r],n));return n.delete(e),r}if(Array.isArray(t))return!1;if(typeof e==`object`){if(n.has(e))return n.get(e)===t;n.set(e,t);let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return n.delete(e),!1;let a=r.every(r=>r in t&&un(e[r],t[r],n));return n.delete(e),a}return!1}var dn=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function fn(e){if(typeof e!=`object`||!e)return!1;let t=e[Symbol.toStringTag];return typeof t==`string`&&dn.has(t)}var pn={direction:`asc`,nulls:`first`,stringSort:`locale`},mn=new WeakMap,hn=1;function gn(e){if(mn.has(e))return mn.get(e);let t=hn++;return mn.set(e,t),t}function V(e){return typeof e==`number`&&Number.isNaN(e)||e instanceof Date&&Number.isNaN(e.getTime())}var _n=(e,t,n)=>{let{nulls:r}=n;if(e==null&&t==null)return 0;if(e==null)return r===`first`?-1:1;if(t==null)return r===`first`?1:-1;let i=V(e),a=V(t);if(i&&a)return 0;if(i)return 1;if(a)return-1;if(typeof e==`string`&&typeof t==`string`&&n.stringSort===`locale`)return e.localeCompare(t,n.locale,n.localeOptions);if(Array.isArray(e)&&Array.isArray(t)){for(let r=0;r<Math.min(e.length,t.length);r++){let i=_n(e[r],t[r],n);if(i!==0)return i}return e.length-t.length}if(e instanceof Date&&t instanceof Date)return e.getTime()-t.getTime();if(fn(e)&&fn(t))return Tn(e,t);let o=typeof e==`object`,s=typeof t==`object`;if(o||s){if(o&&s)return gn(e)-gn(t);if(o)return 1;if(s)return-1}return e<t?-1:+(e>t)},vn=(e,t,n)=>_n(t,e,{...n,nulls:n.nulls===`first`?`last`:`first`});function yn(e){return(t,n)=>e.direction===`asc`?_n(t,n,e):vn(t,n,e)}var bn=yn({direction:`asc`,nulls:`first`,stringSort:`locale`});function xn(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}var Sn=128;function Cn(e){return typeof e!=`object`||!e?e:e instanceof Date?e.getTime():fn(e)?`__temporal__${e[Symbol.toStringTag]}__${e.toString()}`:(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)&&e.byteLength<=Sn?`__u8__${Array.from(e).join(`,`)}`:e}var wn=new Map;function Tn(e,t){let n=e[Symbol.toStringTag],r=t[Symbol.toStringTag];if(n!==r)throw TypeError(`Cannot order Temporal values of different types: ${n} vs ${r}`);let i=wn.get(n);if(i===void 0){let t=e.constructor.compare;i=typeof t==`function`?t:null,wn.set(n,i)}if(i===null)throw TypeError(`${n} has no defined ordering`);return i(e,t)}function En(e,t){return fn(e)&&fn(t)?Tn(e,t):e<t?-1:+(e>t)}function Dn(e,t){if(e===t)return!0;let n=typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array,r=typeof Buffer<`u`&&t instanceof Buffer||t instanceof Uint8Array;return n&&r?xn(e,t):!1}function On(e){return e==null}function kn(e,t){return V(e)||V(t)?V(e)&&V(t):Dn(e,t)}function An(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e==`string`||typeof e==`number`){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function jn(e,t){return e===`%Y-%m-%d`?t.toISOString().slice(0,10):t.toISOString()}function Mn(e){return e===!0}function H(e,t=!1){return Pn(e,t)}function Nn(e){return Pn(e,!0)}function Pn(e,t){switch(e.type){case`val`:{let t=e.value;return()=>t}case`ref`:return t?In(e):Fn(e);case`func`:return Ln(e,t);default:throw new Bt(e.type)}}function Fn(e){let[t,...n]=e.path;if(!t)throw new Vt;if(t===`$selected`){if(n.length===0)return e=>e.$selected;if(n.length===1){let e=n[0];return t=>t.$selected?.[e]}return e=>{let t=e.$selected;if(t===void 0)return;let r=t;for(let e of n){if(r==null)return r;r=r[e]}return r}}let r=t;if(n.length===0)return e=>e[r];if(n.length===1){let e=n[0];return t=>t[r]?.[e]}return e=>{let t=e[r];if(t===void 0)return;let i=t;for(let e of n){if(i==null)return i;i=i[e]}return i}}function In(e){let t=e.path;return e=>{let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}}function Ln(e,t){let n=e.args.map(e=>Pn(e,t));switch(e.name){case`eq`:{let e=n[0],t=n[1];return n=>{let r=Cn(e(n)),i=Cn(t(n));return On(r)||On(i)?null:kn(r,i)}}case`gt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return On(r)||On(i)?null:V(r)||V(i)?V(r)&&!V(i):En(r,i)>0}}case`gte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return On(r)||On(i)?null:V(r)||V(i)?V(r):En(r,i)>=0}}case`lt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return On(r)||On(i)?null:V(r)||V(i)?V(i)&&!V(r):En(r,i)<0}}case`lte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return On(r)||On(i)?null:V(r)||V(i)?V(i):En(r,i)<=0}}case`and`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!1)return!1;On(n)&&(t=!0)}return!t||null};case`or`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!0)return!0;On(n)&&(t=!0)}return t?null:!1};case`not`:{let e=n[0];return t=>{let n=e(t);return On(n)?null:!n}}case`in`:{let e=n[0],t=n[1];return n=>{let r=Cn(e(n)),i=t(n);return On(r)?null:Array.isArray(i)?i.some(e=>kn(Cn(e),r)):!1}}case`like`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return On(r)||On(i)?null:zn(r,i,!1)}}case`ilike`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return On(r)||On(i)?null:zn(r,i,!0)}}case`upper`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`?n.toUpperCase():n}}case`lower`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`?n.toLowerCase():n}}case`length`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`||Array.isArray(n)?n.length:0}}case`concat`:return e=>n.map(t=>{let n=t(e);try{return String(n??``)}catch{try{return JSON.stringify(n)||``}catch{return`[object]`}}}).join(``);case`coalesce`:return e=>{for(let t of n){let n=t(e);if(n!=null)return n}return null};case`caseWhen`:{let e=n.length%2==1,t=Math.floor(n.length/2);if(n.length<2)throw Error(`caseWhen() requires at least two arguments`);return r=>{for(let e=0;e<t;e++){let t=n[e*2];if(Rn(t(r))){let t=n[e*2+1];return t(r)}}return e?n[n.length-1](r):null}}case`add`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)+(i??0)}}case`subtract`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)-(i??0)}}case`multiply`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)*(i??0)}}case`divide`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n)??0;return i===0?null:(r??0)/i}}case`date`:{let e=n[0];return t=>{let n=An(e(t));return n?n.toISOString().slice(0,10):null}}case`datetime`:{let e=n[0];return t=>{let n=An(e(t));return n?n.toISOString():null}}case`strftime`:{let e=n[0],t=n[1];return n=>{let r=e(n);if(typeof r!=`string`)return null;let i=An(t(n));return i?jn(r,i):null}}case`isUndefined`:{let e=n[0];return t=>e(t)===void 0}case`isNull`:{let e=n[0];return t=>e(t)===null}default:throw new Ht(e.name)}}function Rn(e){return e==null||e===!1?!1:e===!0?!0:typeof e==`number`?e!==0&&!Number.isNaN(e):typeof e==`bigint`?e!==0n:!!e}function zn(e,t,n){if(typeof e!=`string`||typeof t!=`string`)return!1;let r=n?e.toLowerCase():e,i=(n?t.toLowerCase():t).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return i=i.replace(/%/g,`.*`),i=i.replace(/_/g,`.`),RegExp(`^${i}$`,`s`).test(r)}var Bn=class{constructor(e){this.originalIndex=e}lookup(e,t){let n=e===`gt`?`lt`:e===`gte`?`lte`:e===`lt`?`gt`:e===`lte`?`gte`:e;return this.originalIndex.lookup(n,t)}rangeQuery(e={}){return this.originalIndex.rangeQueryReversed(e)}rangeQueryReversed(e={}){return this.originalIndex.rangeQuery(e)}take(e,t,n){return this.originalIndex.takeReversed(e,t,n)}takeFromStart(e,t){return this.originalIndex.takeReversedFromEnd(e,t)}takeReversed(e,t,n){return this.originalIndex.take(e,t,n)}takeReversedFromEnd(e,t){return this.originalIndex.takeFromStart(e,t)}get orderedEntriesArray(){return this.originalIndex.orderedEntriesArrayReversed}get orderedEntriesArrayReversed(){return this.originalIndex.orderedEntriesArray}supports(e){return this.originalIndex.supports(e)}get supportsRangeOptimization(){return this.originalIndex.supportsRangeOptimization}matchesField(e){return this.originalIndex.matchesField(e)}matchesCompareOptions(e){return this.originalIndex.matchesCompareOptions(e)}matchesDirection(e){return this.originalIndex.matchesDirection(e)}getStats(){return this.originalIndex.getStats()}add(e,t){this.originalIndex.add(e,t)}remove(e,t){this.originalIndex.remove(e,t)}update(e,t,n){this.originalIndex.update(e,t,n)}build(e){this.originalIndex.build(e)}clear(){this.originalIndex.clear()}get keyCount(){return this.originalIndex.keyCount}equalityLookup(e){return this.originalIndex.equalityLookup(e)}inArrayLookup(e){return this.originalIndex.inArrayLookup(e)}get indexedKeysSet(){return this.originalIndex.indexedKeysSet}get valueMapData(){return this.originalIndex.valueMapData}};function Vn(e,t,n,r,i){let a=e;return{...e,$synced:a.$synced??r(),$origin:a.$origin??i(),$key:a.$key??t,$collectionId:a.$collectionId??n}}var Hn=[`$synced`,`$origin`,`$key`,`$collectionId`];function Un(e){return Hn.includes(e)}function Wn(e){return e.some(e=>Un(e))}function Gn(e,t,n){if(Wn(t))return;let r=n??{...pn,...e.compareOptions};for(let n of e.indexes.values())if(n.matchesField(t)&&n.matchesCompareOptions(r))return n.matchesDirection(r.direction)?n:new Bn(n)}function Kn(e){if(e.length===0)return new Set;if(e.length===1)return new Set(e[0]);let t=new Set(e[0]);for(let n=1;n<e.length;n++){let r=new Set;for(let i of t)e[n].has(i)&&r.add(i);t=r}return t}function qn(e){let t=new Set;for(let n of e)for(let e of n)t.add(e);return t}function Jn(e){return e!=null}function Yn(e){return{...pn,...e.compareOptions}.stringSort===`locale`}function Xn(e,t){switch(typeof e){case`number`:case`bigint`:case`boolean`:return!1;case`string`:return Yn(t);case`object`:return e!==null&&!(e instanceof Date);default:return!1}}function Zn(e,t,n){return!Xn(e,n)&&t.supportsRangeOptimization}function Qn(e,t){return $n(e,t)}function $n(e,t){if(e.type===`func`)switch(e.name){case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:return tr(e,t);case`and`:return nr(e,t);case`or`:return rr(e,t);case`in`:return ir(e,t)}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function er(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set};let n=new Map;for(let[t,r]of e.args.entries())if(r.type===`func`&&[`gt`,`gte`,`lt`,`lte`].includes(r.name)){let e=r;if(e.args.length===2){let r=e.args[0],i=e.args[1],a=null,o=null,s=e.name;if(r.type===`ref`&&i.type===`val`)a=r,o=i;else if(r.type===`val`&&i.type===`ref`)switch(a=i,o=r,s){case`gt`:s=`lt`;break;case`gte`:s=`lte`;break;case`lt`:s=`gt`;break;case`lte`:s=`gte`}if(a&&o){let e=a.path.join(`.`),r=o.value;n.has(e)||n.set(e,[]),n.get(e).push({operation:s,value:r,argIndex:t})}}}for(let[e,r]of n)if(r.length>=2){let n=Gn(t,e.split(`.`));if(n&&r.some(e=>!Zn(e.value,n,t)))continue;if(n&&n.supports(`gt`)&&n.supports(`lt`)){let e=yn({...pn,...t.compareOptions,direction:`asc`}),i,a,o=!1,s=!1,c=!0,l=!0,u=!1;for(let{operation:t,value:n}of r){if(!Jn(n)){u=!0;continue}switch(t){case`gt`:case`gte`:{let r=o?e(n,i):1;r>0?(i=n,o=!0,c=t===`gte`):r===0&&t===`gt`&&(c=!1);break}case`lt`:case`lte`:{let r=s?e(n,a):-1;r<0?(a=n,s=!0,l=t===`lte`):r===0&&t===`lt`&&(l=!1);break}}}let d={};return o&&(d.from=i,d.fromInclusive=c),s&&(d.to=a,d.toInclusive=l),{canOptimize:!0,matchingKeys:n.rangeQuery(d),isExact:o&&!u,coveredArgIndices:new Set(r.map(e=>e.argIndex))}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set}}function tr(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=e.args[0],r=e.args[1],i=null,a=null,o=e.name;if(n.type===`ref`&&r.type===`val`)i=n,a=r;else if(n.type===`val`&&r.type===`ref`)switch(i=r,a=n,o){case`gt`:o=`lt`;break;case`gte`:o=`lte`;break;case`lt`:o=`gt`;break;case`lte`:o=`gte`}if(i&&a){let e=i.path,n=Gn(t,e);if(n){let e=a.value,r=o;return!n.supports(r)||(o===`gt`||o===`gte`||o===`lt`||o===`lte`)&&!Zn(e,n,t)?{canOptimize:!1,matchingKeys:new Set,isExact:!1}:{canOptimize:!0,matchingKeys:n.lookup(r,e),isExact:o===`lt`||o===`lte`?!1:Jn(e)}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function nr(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=er(e,t),r=n.canOptimize?n.coveredArgIndices:new Set,i=[];n.canOptimize&&i.push(n);let a=!n.canOptimize||n.isExact;for(let[n,o]of e.args.entries()){if(r.has(n))continue;let e=$n(o,t);e.canOptimize?(i.push(e),e.isExact||(a=!1)):a=!1}return i.length>0?{canOptimize:!0,matchingKeys:Kn(i.map(e=>e.matchingKeys)),isExact:a}:{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function rr(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=[];for(let r of e.args){let e=$n(r,t);if(!e.canOptimize)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};n.push(e)}return{canOptimize:!0,matchingKeys:qn(n.map(e=>e.matchingKeys)),isExact:n.every(e=>e.isExact)}}function ir(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=e.args[0],r=e.args[1];if(n.type===`ref`&&r.type===`val`&&Array.isArray(r.value)){let e=n.path,i=r.value,a=Gn(t,e),o=i.every(e=>Jn(e));if(a){if(a.supports(`in`))return{canOptimize:!0,matchingKeys:a.lookup(`in`,i),isExact:o};if(a.supports(`eq`)){let e=new Set;for(let t of i){let n=a.lookup(`eq`,t);for(let t of n)e.add(t)}return{canOptimize:!0,matchingKeys:e,isExact:o}}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}var ar={enabled:!0,collectionSizeThreshold:1e3,slowQueryThresholdMs:10,onSuggestion:null};function or(){return ar.enabled&&!1}function sr(e){if(or()){if(ar.onSuggestion)try{ar.onSuggestion(e)}catch{}else console.warn(`[TanStack DB] Index suggestion for "${e.collectionId}":
8
+ ${e.message}
9
+ Field: ${e.fieldPath.join(`.`)}
10
+ Add index: collection.createIndex((row) => row.${e.fieldPath.join(`.`)})`)}}function cr(e,t,n){or()&&t>ar.collectionSizeThreshold&&sr({type:`collection-size`,collectionId:e,fieldPath:n,message:`Collection has ${t} items. Queries on "${n.join(`.`)}" may benefit from an index.`,collectionSize:t})}function lr(e){return e.config.autoIndex===`eager`}function ur(e,t,n,r,i){if(Wn(t)||!lr(n))return;let a=r??{...pn,...n.compareOptions};if(!Array.from(n.indexes.values()).find(e=>e.matchesField(t)&&e.matchesCompareOptions(a))){or()&&cr(n.id||`unknown`,n.size,t);try{n.createIndex(e=>{let n=e;for(let e of t)n=n[e];return n},{name:`auto:${t.join(`.`)}`,options:i?{compareFn:i,compareOptions:a}:{}})}catch(e){console.warn(`${n.id?`[${n.id}] `:``}Failed to create auto-index for field path "${t.join(`.`)}":`,e)}}}function dr(e,t){if(!lr(t))return;let n=fr(e);for(let{fieldName:e,fieldPath:r}of n)ur(e,r,t)}function fr(e){let t=[];function n(e){if(e.type!==`func`)return;let r=e;if(r.name===`and`){for(let e of r.args)n(e);return}if(![`eq`,`gt`,`gte`,`lt`,`lte`,`in`].includes(r.name)||r.args.length<1||r.args[0].type!==`ref`)return;let i=r.args[0].path;if(i.length===0)return;let a=i.join(`_`);t.push({fieldName:a,fieldPath:i})}return n(e),t}var pr=class extends Map{constructor(e,t){super(t),this.defaultValue=e}get(e){return this.has(e)?super.get(e):this.defaultValue()}update(e,t){let n=t(this.get(e));return this.set(e,n),n}},mr=3e4;function hr(e,t){if(t.length<=mr)e.push(...t);else for(let n=0;n<t.length;n+=mr){let r=t.slice(n,n+mr);e.push(...r)}}function gr(e,t,n){let r=0,i=e.length;for(;r<i;){let a=Math.floor((r+i)/2),o=n(e[a],t);if(o<0)r=a+1;else if(o>0)i=a;else return a}return r}var _r=new class{constructor(){this.objectIds=new WeakMap,this.nextId=0}getId(e){if(typeof e!=`object`||!e){let t=String(e),n=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n=(n<<5)-n+r,n&=n}return n}return this.objectIds.has(e)||this.objectIds.set(e,this.nextId++),this.objectIds.get(e)}getStringId(e){return e===null?`null`:e===void 0?`undefined`:typeof e==`object`?`obj_${this.getId(e)}`:`str_${String(e)}`}};function vr(e,t){let[n,r]=e,[i,a]=t;return{onlyInA:[...yr(n,Math.min(r,i)),...yr(Math.max(n,a),r)],onlyInB:[...yr(i,Math.min(a,n)),...yr(Math.max(i,r),a)]}}function yr(e,t){let n=[];for(let r=e;r<t;r++)n.push(r);return n}function br(e,t){return typeof e==typeof t?e<t?-1:+(e>t):typeof e==`string`?-1:1}function U(e){return xr(e,new Set)?JSON.stringify(Sr(e)):`~${JSON.stringify(Cr(e,new Set))}`}function xr(e,t){if(e===null)return!0;switch(typeof e){case`boolean`:case`string`:return!0;case`number`:return Number.isFinite(e);case`undefined`:case`bigint`:case`symbol`:case`function`:return!1}return Tr(e,t,()=>e instanceof Date||e instanceof RegExp||e instanceof Uint8Array||e instanceof Map||e instanceof Set?!1:Array.isArray(e)?e.every(e=>xr(e,t)):Object.keys(e).every(n=>xr(e[n],t)))}function Sr(e){return e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:Array.isArray(e)?e.map(Sr):Object.fromEntries(Object.keys(e).sort().map(t=>[t,Sr(e[t])]))}function Cr(e,t){if(e===void 0)return[`undefined`];if(e===null)return[`null`];switch(typeof e){case`boolean`:return[`boolean`,e];case`number`:return Number.isNaN(e)?[`number`,`NaN`]:e===1/0?[`number`,`Infinity`]:e===-1/0?[`number`,`-Infinity`]:[`number`,e===0?0:e];case`bigint`:return[`bigint`,e.toString()];case`string`:return[`string`,e];case`symbol`:case`function`:throw TypeError(`Cannot serialize ${typeof e} as a structural relation key`)}return Tr(e,t,()=>{if(e instanceof Date){let t=e.getTime();return Number.isNaN(t)?[`date`,`Invalid`]:[`date`,t]}if(e instanceof RegExp)return[`regexp`,e.source,e.flags];if(e instanceof Uint8Array)return[`bytes`,Array.from(e)];if(Array.isArray(e))return[`array`,e.map(e=>Cr(e,t))];if(e instanceof Map){let n=[...e.entries()].map(([e,n])=>[Cr(e,t),Cr(n,t)]);return n.sort((e,t)=>wr(JSON.stringify(e),JSON.stringify(t))),[`map`,n]}if(e instanceof Set){let n=[...e].map(e=>Cr(e,t));return n.sort((e,t)=>wr(JSON.stringify(e),JSON.stringify(t))),[`set`,n]}return[`object`,Object.keys(e).sort().map(n=>[n,Cr(e[n],t)])]})}function wr(e,t){return e<t?-1:+(e>t)}function Tr(e,t,n){if(t.has(e))throw TypeError(`Cannot serialize a cyclic structural relation key`);t.add(e);try{return n()}finally{t.delete(e)}}var Er=jr(),Dr=jr(),Or=jr(),kr=jr(),Ar=jr();function jr(){return Math.random()*(2**31-1)>>>0}var Mr=new ArrayBuffer(8),Nr=new DataView(Mr),Pr=new Uint8Array(Mr),Fr=class{constructor(){this.hash=Er,this.length=0,this.carry=0,this.carryBytes=0}_mix(e){e=Math.imul(e,3432918353),e=e<<15|e>>>17,e=Math.imul(e,461845907),this.hash^=e,this.hash=this.hash<<13|this.hash>>>19,this.hash=Math.imul(this.hash,5)+3864292196}writeByte(e){this.carry|=(e&255)<<8*this.carryBytes,this.carryBytes++,this.length++,this.carryBytes===4&&(this._mix(this.carry>>>0),this.carry=0,this.carryBytes=0)}update(e){switch(typeof e){case`symbol`:{this.update(Ar);let t=e.description;if(!t)return;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);this.writeByte(n&255),this.writeByte(n>>>8&255)}return}case`string`:this.update(Dr);for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);this.writeByte(n&255),this.writeByte(n>>>8&255)}return;case`number`:Nr.setFloat64(0,e,!0),this.writeByte(Pr[0]),this.writeByte(Pr[1]),this.writeByte(Pr[2]),this.writeByte(Pr[3]),this.writeByte(Pr[4]),this.writeByte(Pr[5]),this.writeByte(Pr[6]),this.writeByte(Pr[7]);return;case`bigint`:{let t=e;for(t<0n?(t=-t,this.update(kr)):this.update(Or);t>0n;)this.writeByte(Number(t&255n)),t>>=8n;e===0n&&this.writeByte(0);return}default:throw TypeError(`Unsupported input type: ${typeof e}`)}}digest(){if(this.carryBytes>0){let e=this.carry>>>0;e=Math.imul(e,3432918353),e=e<<15|e>>>17,e=Math.imul(e,461845907),this.hash^=e}return this.hash^=this.length,this.hash^=this.hash>>>16,this.hash=Math.imul(this.hash,2246822507),this.hash^=this.hash>>>13,this.hash=Math.imul(this.hash,3266489909),this.hash^=this.hash>>>16,this.hash>>>0}},Ir=jr(),Lr=jr(),Rr=jr(),zr=jr(),Br=jr(),Vr=jr(),Hr=jr(),Ur=jr(),Wr=jr(),Gr=jr(),Kr=jr(),qr=jr(),Jr=jr(),Yr=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function Xr(e){let t=e[Symbol.toStringTag];return typeof t==`string`&&Yr.has(t)}var Zr=128,Qr=new WeakMap;function $r(e){let t=new Fr;return ai(t,e),t.digest()}function ei(e){let t=Qr.get(e);if(t!==void 0)return t;let n;if(e instanceof Date)n=ti(e);else if(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array){if(e.byteLength<=Zr)n=ni(e);else return ci(e)}else if(e instanceof File)return ci(e);else if(Xr(e))n=ri(e);else{let t=e,r=Ur;e instanceof Array&&(r=Wr),e instanceof Map&&(r=Gr,t=[...e.entries()]),e instanceof Set&&(r=Kr,t=[...e.entries()]),n=ii(t,r)}return Qr.set(e,n),n}function ti(e){let t=new Fr;return t.update(Hr),t.update(e.getTime()),t.digest()}function ni(e){let t=new Fr;t.update(qr),t.update(e.byteLength);for(let n=0;n<e.byteLength;n++)t.writeByte(e[n]);return t.digest()}function ri(e){let t=new Fr;return t.update(Jr),t.update(e[Symbol.toStringTag]),t.update(e.toString()),t.digest()}function ii(e,t){let n=new Fr;n.update(t);let r=Object.keys(e);r.sort(li);for(let t of r)n.update(Br),n.update(t),ai(n,e[t]);return n.digest()}function ai(e,t){if(t===null){e.update(Rr);return}switch(typeof t){case`undefined`:e.update(zr);return;case`boolean`:e.update(t?Ir:Lr);return;case`number`:e.update(isNaN(t)?NaN:t===0?0:t);return;case`bigint`:case`string`:case`symbol`:e.update(t);return;case`object`:e.update(oi(t));return;case`function`:e.update(ci(t));return;default:console.warn(`Ignored input during hashing because it is of type ${typeof t} which is not supported`)}}function oi(e){let t=Qr.get(e);return t===void 0&&(t=ei(e)),t}var si=1;function ci(e){let t=Qr.get(e);return t===void 0&&(t=si^Vr,si++,Qr.set(e,t)),t}function li(e,t){return e.localeCompare(t)}var ui=class e{#e;constructor(e=[]){this.#e=e}toString(e=!1){return`MultiSet(${JSON.stringify(this.#e,null,e?2:void 0)})`}toJSON(){return JSON.stringify(Array.from(this.getInner()))}static fromJSON(t){return new e(JSON.parse(t))}map(t){return new e(this.#e.map(([e,n])=>[t(e),n]))}filter(t){return new e(this.#e.filter(([e,n])=>t(e)))}negate(){return new e(this.#e.map(([e,t])=>[e,-t]))}concat(t){let n=[];return hr(n,this.#e),hr(n,t.getInner()),new e(n)}consolidate(){if(this.#e.length>0){let e=this.#e[0]?.[0];if(Array.isArray(e)&&e.length===2)return this.#t()}return this.#n()}#t(){let t=new Map,n=new Map,r=e=>{if(e.length!==2)throw Error(`Expected tuple of length 2`);let[t,n]=e;return`${_r.getStringId(t)}|${_r.getStringId(n)}`};for(let[e,i]of this.#e){if(!Array.isArray(e)||e.length!==2)return this.#n();let[a,o]=e;if(typeof a!=`string`&&typeof a!=`number`)return this.#n();let s;s=Array.isArray(o)&&o.length===2?r(o):_r.getStringId(o);let c=a+`|`+s;t.set(c,(t.get(c)||0)+i),n.has(c)||n.set(c,e)}let i=[];for(let[e,r]of t)r!==0&&i.push([n.get(e),r]);return new e(i)}#n(){let t=new pr(()=>0),n=new Map,r=!1,i=!1,a=!1;for(let[e,t]of this.#e)if(typeof e==`string`)r=!0;else if(typeof e==`number`)i=!0;else{a=!0;break}let o=a||r&&i;for(let[e,r]of this.#e){let i=o?$r(e):e;o&&!n.has(i)&&n.set(i,e),t.update(i,e=>e+r)}let s=[];for(let[e,r]of t.entries())if(r!==0){let t=o?n.get(e):e;s.push([t,r])}return new e(s)}extend(t){let n=t instanceof e?t.getInner():t;hr(this.#e,n)}add(e,t){t!==0&&this.#e.push([e,t])}getInner(){return this.#e}},di=class{#e;constructor(e){this.#e=e}drain(){let e=[...this.#e].reverse();return this.#e.length=0,e}isEmpty(){return this.#e.length===0}},fi=class{#e=[];sendData(e){e instanceof ui||(e=new ui(e));for(let t of this.#e)t.unshift(e)}newReader(){let e=[];return this.#e.push(e),new di(e)}},pi=class{constructor(e,t,n){this.id=e,this.inputs=t,this.output=n}hasPendingWork(){return this.inputs.some(e=>!e.isEmpty())}},mi=class extends pi{constructor(e,t,n){super(e,[t],n),this.id=e}inputMessages(){return this.inputs[0].drain()}},hi=class extends pi{constructor(e,t,n,r){super(e,[t,n],r),this.id=e}inputAMessages(){return this.inputs[0].drain()}inputBMessages(){return this.inputs[1].drain()}},gi=class extends mi{run(){for(let e of this.inputMessages())this.output.sendData(this.inner(e))}},_i=class{#e=[];#t=0;#n=!1;constructor(){}#r(){if(this.#n)throw Error(`Graph already finalized`)}getNextOperatorId(){return this.#r(),this.#t++}newInput(){this.#r();let e=new fi;return new yi(this,e)}addOperator(e){this.#r(),this.#e.push(e)}finalize(){this.#r(),this.#n=!0}step(){if(!this.#n)throw Error(`Graph not finalized`);for(let e of this.#e)e.run()}pendingWork(){return this.#e.some(e=>e.hasPendingWork())}run(){for(;this.pendingWork();)this.step()}},vi=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}connectReader(){return this.#t.newReader()}get writer(){return this.#t}get graph(){return this.#e}pipe(...e){return e.reduce((e,t)=>t(e),this)}},yi=class extends vi{sendData(e){this.writer.sendData(e)}},bi=class extends gi{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.map(this.#e)}};function W(e){return t=>{let n=new vi(t.graph,new fi),r=new bi(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var xi=Symbol(`NO_PREFIX`),Si=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=Ti(e),r=this.get(n);if(Ei(r)){let[i,a]=r;if(Ti(i)!==n)throw Error(`Mismatching prefixes, this should never happen`);if(i===e||$r(i)===$r(e)){let r=a+t;r===0?this.delete(n):this.set(n,[e,r])}else{let a=new Ci;a.set($r(i),r),a.set($r(e),[e,t]),this.set(n,a)}}else r===void 0?this.set(n,[e,t]):r.addValue(e,t)&&this.delete(n);return this.size===0}},Ci=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=$r(e),r=this.get(n);if(r){let[,i]=r,a=i+t;a===0?this.delete(n):this.set(n,[e,a])}else this.set(n,[e,t]);return this.size===0}},wi=class e{#e;#t=new Map;constructor(){this.#e=new Map}static fromMultiSets(t){let n=new e;for(let e of t)for(let[t,r]of e.getInner()){let[e,i]=t;n.addValue(e,[i,r])}return n}toString(e=!1){return`Index(${JSON.stringify([...this.entries()],void 0,e?2:void 0)})`}get size(){return this.#e.size}has(e){return this.#e.has(e)}hasPresence(e){return(this.#t.get(e)||0)!==0}getConsolidatedMultiplicity(e){return this.#t.get(e)||0}getPresenceKeys(){return this.#t.keys()}get(e){return[...this.getIterator(e)]}*getIterator(e){let t=this.#e.get(e);if(Ei(t))yield t;else if(t===void 0)return;else if(t instanceof Ci)for(let e of t.values())yield e;else for(let e of t.values())if(Ei(e))yield e;else for(let t of e.values())yield t}*entries(){for(let e of this.#e.keys())for(let t of this.getIterator(e))yield[e,t]}*entriesIterators(){for(let e of this.#e.keys())yield[e,this.getIterator(e)]}addValue(e,t){let[n,r]=t;if(r===0)return;let i=(this.#t.get(e)||0)+r;i===0?this.#t.delete(e):this.#t.set(e,i);let a=this.#e.get(e);if(a===void 0){this.#e.set(e,t);return}if(Ei(a)){this.#n(e,a,n,r);return}if(a instanceof Ci){let i=Ti(n);if(i!==xi){let n=new Si;n.set(xi,a),n.set(i,t),this.#e.set(e,n)}else a.addValue(n,r)&&this.#e.delete(e)}else a.addValue(n,r)&&this.#e.delete(e)}#n(e,t,n,r){let[i,a]=t;if(i===n){let t=a+r;t===0?this.#e.delete(e):this.#e.set(e,[n,t]);return}let o=Ti(n),s=Ti(i);if(s===o&&(i===n||$r(i)===$r(n))){let t=a+r;t===0?this.#e.delete(e):this.#e.set(e,[n,t]);return}if(s===xi&&o===xi){let a=new Ci;a.set($r(i),t),a.set($r(n),[n,r]),this.#e.set(e,a)}else{let a=new Si;if(s===o){let e=new Ci;e.set($r(i),t),e.set($r(n),[n,r]),a.set(s,e)}else a.set(s,t),a.set(o,[n,r]);this.#e.set(e,a)}}append(e){for(let[t,n]of e.entries())this.addValue(t,n)}join(e){let t=[];if(this.size<=e.size)for(let[n,r]of this.entriesIterators()){if(!e.has(n))continue;let i=e.get(n);for(let[e,a]of r)for(let[r,o]of i)a!==0&&o!==0&&t.push([[n,[e,r]],a*o])}else for(let[n,r]of e.entriesIterators()){if(!this.has(n))continue;let e=this.get(n);for(let[i,a]of r)for(let[r,o]of e)o!==0&&a!==0&&t.push([[n,[r,i]],o*a])}return new ui(t)}};function Ti(e){return Array.isArray(e)&&(typeof e[0]==`string`||typeof e[0]==`number`||typeof e[0]==`bigint`)?e[0]:xi}function Ei(e){return Array.isArray(e)}var Di=class extends mi{#e=new wi;#t=new wi;#n;constructor(e,t,n,r){super(e,t,n),this.#n=r}run(){let e=new Set;for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let[t,i]=n;this.#e.addValue(t,[i,r]),e.add(t)}let t=[];for(let n of e){let e=this.#e.get(n),r=this.#t.get(n),i=this.#n(e),a=new Map,o=new Map;for(let[e,t]of i){let n=a.get(e)??0;a.set(e,n+t)}for(let[e,t]of r){let n=o.get(e)??0;o.set(e,n+t)}for(let[e,r]of o)a.has(e)||(t.push([[n,e],-r]),this.#t.addValue(n,[e,-r]));for(let[e,r]of a)o.has(e)||r!==0&&(t.push([[n,e],r]),this.#t.addValue(n,[e,r]));for(let[e,r]of a){let i=o.get(e);if(i!==void 0){let a=r-i;a!==0&&(t.push([[n,e],a]),this.#t.addValue(n,[e,a]))}}}t.length>0&&this.output.sendData(new ui(t))}};function Oi(e){return t=>{let n=new vi(t.graph,new fi),r=new Di(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}function ki(e){return`pipe`in e}function Ai(e,t={}){let n=Object.fromEntries(Object.entries(t).filter(([e,t])=>!ki(t)));return Object.fromEntries(Object.entries(t).filter(([e,t])=>ki(t))),t=>{let r=`__original_key__`;return t.pipe(W(t=>{let i=e(t),a=U(i),o={};o[r]=i;for(let[e,r]of Object.entries(n))o[e]=r.preMap(t);return[a,o]})).pipe(Oi(e=>{let t=0;for(let[n,r]of e)t+=r;if(t<=0)return[];let i={},a=e[0]?.[0]?.[r];i[r]=a;for(let[t,r]of Object.entries(n)){let n=e.map(([e,n])=>[e[t],n]);i[t]=r.reduce(n)}return[[i,1]]})).pipe(W(([e,t])=>{let i=t[r],a={};Object.assign(a,i);for(let[e,r]of Object.entries(n))a[e]=r.postMap?r.postMap(t[e]):t[e];return[e,a]}))}}function ji(e=e=>e){return{preMap:t=>e(t),reduce:e=>{let t=0;for(let[n,r]of e)t+=n*r;return t}}}function Mi(e=e=>e){return{preMap:t=>e(t)==null?0:1,reduce:e=>{let t=0;for(let[n,r]of e)t+=n*r;return t}}}function Ni(e=e=>e){return{preMap:t=>({sum:e(t),count:0}),reduce:e=>{let t=0,n=0;for(let[r,i]of e)t+=r.sum*i,n+=i;return{sum:t,count:n}},postMap:e=>e.sum/e.count}}function Pi(e){let t=e??(e=>e);return{preMap:e=>t(e),reduce:e=>{let t;for(let[n,r]of e)(!t||n&&n<t)&&(t=n);return t}}}function Fi(e){let t=e??(e=>e);return{preMap:e=>t(e),reduce:e=>{let t;for(let[n,r]of e)(!t||n&&n>t)&&(t=n);return t}}}function Ii(e=e=>e){return{preMap:t=>[e(t)],reduce:e=>{let t=[];for(let[n,r]of e)for(let e of n)for(let n=0;n<r;n++)t.push(e);return t.length===0?[]:(t.sort((e,t)=>e-t),t)},postMap:e=>{if(e.length===0)return 0;let t=Math.floor(e.length/2);return e.length%2==0?(e[t-1]+e[t])/2:e[t]}}}function Li(e=e=>e){return{preMap:t=>{let n=e(t),r=new Map;return r.set(n,1),r},reduce:e=>{let t=new Map;for(let[n,r]of e)for(let[e,i]of n.entries()){let n=t.get(e)||0;t.set(e,n+i*r)}return t},postMap:e=>{if(e.size===0)return 0;let t=0,n=0;for(let[r,i]of e.entries())i>n&&(n=i,t=r);return t}}}var Ri={sum:ji,count:Mi,avg:Ni,min:Pi,max:Fi,median:Ii,mode:Li},zi=class extends gi{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return this.#e(e),e}};function Bi(e){return t=>{let n=new vi(t.graph,new fi),r=new zi(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Vi=class extends gi{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.filter(this.#e)}};function Hi(e){return t=>{let n=new vi(t.graph,new fi),r=new Vi(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Ui=class extends hi{run(){for(let e of this.inputAMessages())this.output.sendData(e);for(let e of this.inputBMessages())this.output.sendData(e)}};function Wi(e){return t=>{if(t.graph!==e.graph)throw Error(`Cannot concat streams from different graphs`);let n=new vi(t.graph,new fi),r=new Ui(t.graph.getNextOperatorId(),t.connectReader(),e.connectReader(),n.writer);return t.graph.addOperator(r),n}}var Gi=class extends mi{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}run(){for(let e of this.inputMessages())this.#e(e),this.output.sendData(e)}};function Ki(e){return t=>{let n=new vi(t.graph,new fi),r=new Gi(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var qi=class extends mi{run(){let e=this.inputMessages();if(e.length===0)return;let t=new ui;for(let n of e)t.extend(n);let n=t.consolidate();n.getInner().length>0&&this.output.sendData(n)}};function Ji(){return e=>{let t=new vi(e.graph,new fi),n=new qi(e.graph.getNextOperatorId(),e.connectReader(),t.writer);return e.graph.addOperator(n),t}}var Yi=class extends hi{#e=new wi;#t=new wi;#n;constructor(e,t,n,r,i=`inner`){super(e,t,n,r),this.#n=i}run(){let e=wi.fromMultiSets(this.inputAMessages()),t=wi.fromMultiSets(this.inputBMessages());if(e.size===0&&t.size===0)return;let n=new ui;this.#n!==`anti`&&this.emitInnerResults(e,t,n),(this.#n===`left`||this.#n===`full`||this.#n===`anti`)&&this.emitLeftOuterResults(e,t,n),(this.#n===`right`||this.#n===`full`)&&this.emitRightOuterResults(e,t,n),this.#e.append(e),this.#t.append(t),n.getInner().length>0&&this.output.sendData(n)}emitInnerResults(e,t,n){e.size>0&&n.extend(e.join(this.#t)),t.size>0&&n.extend(this.#e.join(t)),e.size>0&&t.size>0&&n.extend(e.join(t))}emitLeftOuterResults(e,t,n){if(e.size>0){for(let[r,i]of e.entriesIterators())if(this.#t.getConsolidatedMultiplicity(r)+t.getConsolidatedMultiplicity(r)===0)for(let[e,t]of i)t!==0&&n.add([r,[e,null]],t)}if(t.size>0)for(let e of t.getPresenceKeys()){let r=this.#t.getConsolidatedMultiplicity(e),i=t.getConsolidatedMultiplicity(e);if(i===0)continue;let a=r+i;if(r===0==(a===0))continue;let o=r===0;for(let[t,r]of this.#e.getIterator(e))r!==0&&n.add([e,[t,null]],o?-r:+r)}}emitRightOuterResults(e,t,n){if(t.size>0){for(let[r,i]of t.entriesIterators())if(this.#e.getConsolidatedMultiplicity(r)+e.getConsolidatedMultiplicity(r)===0)for(let[e,t]of i)t!==0&&n.add([r,[null,e]],t)}if(e.size>0)for(let t of e.getPresenceKeys()){let r=this.#e.getConsolidatedMultiplicity(t),i=e.getConsolidatedMultiplicity(t);if(i===0)continue;let a=r+i;if(r===0==(a===0))continue;let o=r===0;for(let[e,r]of this.#t.getIterator(t))r!==0&&n.add([t,[null,e]],o?-r:+r)}}};function Xi(e,t=`inner`){return n=>{if(n.graph!==e.graph)throw Error(`Cannot join streams from different graphs`);let r=new vi(n.graph,new fi),i=new Yi(n.graph.getNextOperatorId(),n.connectReader(),e.connectReader(),r.writer,t);return n.graph.addOperator(i),r}}var Zi=class extends mi{#e;#t;constructor(e,t,n,r=e=>e){super(e,t,n),this.#e=r,this.#t=new Map}run(){let e=new Map;for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let t=$r(this.#e(n)),i=(e.get(t)?.[0]??this.#t.get(t)??0)+r;e.set(t,[i,n])}let t=[];for(let[n,[r,i]]of e.entries()){let e=this.#t.get(n)??0;r===0?this.#t.delete(n):this.#t.set(n,r),e<=0&&r>0?t.push([[$r(this.#e(i)),i[1]],1]):e>0&&r<=0&&t.push([[$r(this.#e(i)),i[1]],-1])}t.length>0&&this.output.sendData(new ui(t))}};function Qi(e=e=>e){return t=>{let n=new vi(t.graph,new fi),r=new Zi(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var $i=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,ea=new Map;function ta(e){let t=ea.get(e);if(t===void 0){t=new Uint8Array(256);for(let n=0;n<e.length;n++)t[e.charCodeAt(n)]=n;ea.set(e,t)}return t}function na(e,t,n,r){let i=n[0];if(t!=null&&e>=t)throw Error(e+` >= `+t);if(e.slice(-1)===i||t&&t.slice(-1)===i)throw Error(`trailing zero`);if(t){let a=0;for(;(e[a]||i)===t[a];)a++;if(a>0)return t.slice(0,a)+na(e.slice(a),t.slice(a),n,r)}let a=e?r[e.charCodeAt(0)]:0,o=t==null?n.length:r[t.charCodeAt(0)];return o-a>1?n[Math.round(.5*(a+o))]:t&&t.length>1?t.slice(0,1):n[a]+na(e.slice(1),null,n,r)}function ra(e,t){if(e.length!==ia(e[0],t))throw Error(`invalid integer part of order key: `+e)}function ia(e,t){if(t===void 0){let t=e.charCodeAt(0);if(t>=97&&t<=122)return t-97+2;if(t>=65&&t<=90)return 90-t+2}else{let n=t.indexOf(e);if(n!==-1){let e=t.length/2;return n<e?e-n+1:n-e+2}}throw Error(`invalid order key head: `+e)}function aa(e,t){let n=ia(e[0],t);if(n>e.length)throw Error(`invalid order key: `+e);return e.slice(0,n)}function oa(e,t,n){if(ua(e,t,n))throw Error(`invalid order key: `+e);let r=aa(e,n);if(e.slice(r.length).slice(-1)===t[0])throw Error(`invalid order key: `+e)}function sa(e,t,n,r){ra(e,r);let i=e[0],a=t[0],o=``;for(let r=e.length-1;r>=1;r--){let s=n[e.charCodeAt(r)]+1;if(s===t.length)o=a+o;else return i+e.slice(1,r)+t[s]+o}if(r===void 0){if(i===`Z`)return`a`+a;if(i===`z`)return null;let e=String.fromCharCode(i.charCodeAt(0)+1);return e+(e>`a`?o+a:o.slice(1))}let s=r.indexOf(i);if(s===r.length-1)return null;let c=r[s+1],l=ia(c,r)-ia(i,r);return c+(l>0?o+a:l<0?o.slice(1):o)}function ca(e,t,n,r){ra(e,r);let i=e[0],a=t[t.length-1],o=``;for(let r=e.length-1;r>=1;r--){let s=n[e.charCodeAt(r)]-1;if(s===-1)o=a+o;else return i+e.slice(1,r)+t[s]+o}if(r===void 0){if(i===`a`)return`Z`+a;if(i===`A`)return null;let e=String.fromCharCode(i.charCodeAt(0)-1);return e+(e<`Z`?o+a:o.slice(1))}let s=r.indexOf(i);if(s===0)return null;let c=r[s-1],l=ia(c,r)-ia(i,r);return c+(l>0?o+a:l<0?o.slice(1):o)}var la=new Map;function ua(e,t,n=``){let r=la.get(n);r===void 0&&(r=new Map,la.set(n,r));let i=t.charCodeAt(0),a=r.get(i);return a===void 0&&(a=n===``?`A`+t[0].repeat(26):n[0]+t[0].repeat(n.length/2),r.set(i,a)),e===a}function da(e){for(let t=1;t<e.length;t++)if(e.charCodeAt(t-1)>=e.charCodeAt(t))return!1;return!0}function fa(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}var pa=new Set;function ma(e){if(!pa.has(e)){if(e.length<2||!da(e))throw Error(`digits must be at least 2 characters in strictly ascending character code order: `+e);if(!fa(e))throw Error(`digits must be single-byte (char code 0-255): `+e);pa.add(e)}}var ha=new Set;function ga(e){if(!ha.has(e)){if(e.length<2||e.length%2!=0||!da(e))throw Error(`intDigits must be an even number of at least 2 characters in strictly ascending character code order: `+e);if(!fa(e))throw Error(`intDigits must be single-byte (char code 0-255): `+e);ha.add(e)}}function _a(e,t,n=$i,r=void 0){ma(n),r!==void 0&&ga(r);let i=ta(n);if(e!=null&&oa(e,n,r),t!=null&&oa(t,n,r),e!=null&&t!=null&&e>t){let n=e;e=t,t=n}if(e==null){if(t==null)return(r===void 0?`a`:r[r.length/2])+n[0];let e=aa(t,r),a=t.slice(e.length);if(ua(e,n,r))return e+na(``,a,n,i);if(e<t)return e;let o=ca(e,n,i,r);if(o==null)throw Error(`cannot decrement any more`);return o}if(t==null){let t=aa(e,r),a=e.slice(t.length);return sa(t,n,i,r)??t+na(a,null,n,i)}let a=aa(e,r),o=e.slice(a.length),s=aa(t,r),c=t.slice(s.length);if(a===s)return a+na(o,c,n,i);let l=sa(a,n,i,r);if(l==null)throw Error(`cannot increment any more`);return l<t?l:a+na(o,null,n,i)}function va(e,t){return[e,t]}function ya(e){return e[0]}function ba(e){return e[1]}function xa(e){return([t,n],[r,i])=>{let a=e(n,i);return a===0?br(t,r):a}}var Sa=class{#e=[];#t;#n;#r;constructor(e,t,n){this.#n=e,this.#r=e+t,this.#t=n}get size(){let e=this.#n,t=this.#r-this.#n,n=this.#e.length-e;return Math.max(0,Math.min(t,n))}move({offset:e,limit:t}){let n=this.#n,r=this.#r-this.#n,i=[this.#n,this.#r===1/0?this.#n+this.size:this.#r];this.#n=e??n,this.#r=this.#n+(t??r);let{onlyInA:a,onlyInB:o}=vr(i,[this.#n,this.#r===1/0?Math.max(this.#n+this.size,i[1]):this.#r]),s=[];o.forEach(e=>{let t=this.#e[e];t&&s.push(t)});let c=[];return a.forEach(e=>{let t=this.#e[e];t&&c.push(t)}),{moveIns:s,moveOuts:c,changes:a.length+o.length>0}}insert(e){let t={moveIn:null,moveOut:null},n=this.#i(e),r=va(e,_a(n===0?null:ba(this.#e[n-1]),n===this.#e.length?null:ba(this.#e[n])));if(this.#e.splice(n,0,r),n<this.#r){let e=Math.max(n,this.#n);e<this.#e.length&&(t.moveIn=this.#e[e],this.#r<this.#e.length&&(t.moveOut=this.#e[this.#r]))}return t}delete(e){let t={moveIn:null,moveOut:null},n=this.#i(e),[r]=this.#e.splice(n,1);if(n<this.#r){if(t.moveOut=r,n<this.#n){let e=this.#n-1;t.moveOut=e<this.#e.length?this.#e[e]:null}let e=this.#r-1;e<this.#e.length&&(t.moveIn=this.#e[e])}return t}#i(e){return gr(this.#e,va(e,``),(e,t)=>this.#t(ya(e),ya(t)))}},Ca=class{#e=new Map;#t;constructor(e){this.#t=e}get size(){return this.#t.size}get isEmpty(){return this.#e.size===0&&this.#t.size===0}processElement(e,t,n){let{oldMultiplicity:r,newMultiplicity:i}=this.#n(e,n);return r<=0&&i>0?this.#t.insert([e,t]):r>0&&i<=0?this.#t.delete([e,t]):{moveIn:null,moveOut:null}}move(e){if(!(this.#t instanceof Sa))throw Error(`Cannot move B+-tree implementation of TopK with fractional index`);return this.#t.move(e)}#n(e,t){if(t===0){let t=this.#e.get(e)??0;return{oldMultiplicity:t,newMultiplicity:t}}let n=this.#e.get(e)??0,r=n+t;return r===0?this.#e.delete(e):this.#e.set(e,r),{oldMultiplicity:n,newMultiplicity:r}}};function wa(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],1])}}function Ta(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],-1])}}var Ea=class extends mi{#e;constructor(e,t,n,r,i){super(e,t,n);let a=i.limit??1/0,o=i.offset??0,s=this.createTopK(o,a,xa(r));this.#e=new Ca(s),i.setSizeCallback?.(()=>this.#e.size),i.setWindowFn?.(this.moveTopK.bind(this))}createTopK(e,t,n){return new Sa(e,t,n)}moveTopK({offset:e,limit:t}){let n=[],r=this.#e.move({offset:e,limit:t});r.moveIns.forEach(e=>wa(e,n)),r.moveOuts.forEach(e=>Ta(e,n)),r.changes&&this.output.sendData(new ui(n))}run(){let e=[];for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let[t,i]=n;this.processElement(t,i,r,e)}e.length>0&&this.output.sendData(new ui(e))}processElement(e,t,n,r){let i=this.#e.processElement(e,t,n);wa(i.moveIn,r),Ta(i.moveOut,r)}};function Da(e,t){let n=t||{};return t=>{let r=new vi(t.graph,new fi),i=new Ea(t.graph.getNextOperatorId(),t.connectReader(),r.writer,e,n);return t.graph.addOperator(i),r}}var Oa=class extends mi{#e=new Map;#t;#n;#r;#i;constructor(e,t,n,r,i){super(e,t,n),this.#t=i.groupKeyFn,this.#i=i.limit??1/0,this.#r=i.offset??0,this.#n=xa(r),i.setSizeCallback?.(()=>this.#a()),i.setWindowFn?.(this.#c.bind(this))}createTopK(e,t,n){return new Sa(e,t,n)}#a(){let e=0;for(let t of this.#e.values())e+=t.size;return e}#o(e){let t=this.#e.get(e);return t||(t=new Ca(this.createTopK(this.#r,this.#i,this.#n)),this.#e.set(e,t)),t}#s(e,t){t.isEmpty&&this.#e.delete(e)}#c({offset:e,limit:t}){e!==void 0&&(this.#r=e),t!==void 0&&(this.#i=t);let n=[],r=!1;for(let e of this.#e.values()){let t=e.move({offset:this.#r,limit:this.#i});t.moveIns.forEach(e=>wa(e,n)),t.moveOuts.forEach(e=>Ta(e,n)),t.changes&&(r=!0)}r&&this.output.sendData(new ui(n))}run(){let e=[];for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let[t,i]=n;this.#l(t,i,r,e)}e.length>0&&this.output.sendData(new ui(e))}#l(e,t,n,r){let i=this.#t(e,t),a=this.#o(i),o=a.processElement(e,t,n);wa(o.moveIn,r),Ta(o.moveOut,r),this.#s(i,a)}};function ka(e,t){return n=>{let r=new vi(n.graph,new fi),i=new Oa(n.graph.getNextOperatorId(),n.connectReader(),r.writer,e,t);return n.graph.addOperator(i),r}}function Aa(e,t,n){let r=n?.limit??1/0,i=n?.offset??0,a=n?.setSizeCallback,o=n?.setWindowFn,s=n?.comparator??((e,t)=>e===t?0:e<t?-1:1);return n=>n.pipe(e((e,n)=>s(t(e),t(n)),{limit:r,offset:i,setSizeCallback:a,setWindowFn:o}),Ji())}function ja(e,t){return Aa(Da,e,t)}function Ma(e,t){let n=t.limit??1/0,r=t.offset??0,i=t.setSizeCallback,a=t.setWindowFn,o=t.groupKeyFn,s=t.comparator??((e,t)=>e===t?0:e<t?-1:1);return t=>t.pipe(ka((t,n)=>s(e(t),e(n)),{limit:n,offset:r,setSizeCallback:i,setWindowFn:a,groupKeyFn:o}),Ji())}var Na=`__virtual_synced__`,Pa=`__virtual_has_local__`,Fa=`__group_key_`;function Ia(e,t,n){let r=t;e.__correlationKey=r[n]?.__correlationKey,r.__parentContext!=null&&(e.__parentContext=r.__parentContext)}function La(e){return e.__parentContext==null?e.__correlationKey:[e.__correlationKey,e.__parentContext]}function Ra(e){let t=e.__parentContext;return{...typeof t==`object`&&t?t:{},$selected:e.$selected}}function za(e,t){let n=e.__parentContext;return{...typeof n==`object`&&n?n:{},$selected:t}}function Ba(e){let t=!1,n=!0,r=!1;for(let[i,a]of Object.entries(e)){if(i===`$selected`||typeof a!=`object`||!a)continue;let e=a,o=`$synced`in e,s=`$origin`in e;!o&&!s||(t=!0,e.$synced===!1&&(n=!1),e.$origin===`local`&&(r=!0))}return{synced:!t||n,hasLocal:r}}var{sum:Va,count:Ha,avg:Ua,min:Wa,max:Ga}=Ri;function Ka(e,t){let n=new Map,r=[...e];if(!t)return{selectToGroupByIndex:n,groupByExpressions:r};for(let[e,i]of Object.entries(t)){if(i.type===`agg`||Qa(i))continue;let t=r.findIndex(e=>Ja(i,e));if(t===-1)throw new $t(e);n.set(e,t)}return{selectToGroupByIndex:n,groupByExpressions:r}}function qa(e,t,n,r,i,a,o){let s={[Na]:{preMap:([,e])=>Ba(e).synced,reduce:e=>{for(let[t,n]of e)if(!t&&n>0)return!1;return!0}},[Pa]:{preMap:([,e])=>Ba(e).hasLocal,reduce:e=>{for(let[t,n]of e)if(t&&n>0)return!0;return!1}}};if(t.length===0){let t=s,c={},l={value:0};if(r){for(let[e,n]of Object.entries(r))if(n.type===`agg`)t[e]=Ya(n);else if(Qa(n)){let{transformed:r,extracted:i}=$a(n,l);for(let[e,n]of Object.entries(i))t[e]=Ya(n);c[e]=no(r)}}if(e=e.pipe(Ai(([,e])=>{let t={__singleGroup:!0};return o&&Ia(t,e,o),t},t)),e=e.pipe(W(([,e])=>{let t={...e.$selected||{}};if(r){for(let[n,i]of Object.entries(r))i.type===`agg`&&(t[n]=e[n]);Za(t,e,c)}let n=o?e.__correlationKey:void 0,i=o?La(e):void 0,s=i===void 0?`single_group`:`single_group_${U(i)}`,l={...e,$selected:t},u=e[Na],d=e[Pa];return l.$synced=u??!0,l.$origin=d?`local`:`remote`,l.$key=s,l.$collectionId=a??l.$collectionId,o&&n!==void 0&&(l[o]={__correlationKey:n}),[s,l]})),n&&n.length>0)for(let t of n){let n=H(Xa(Me(t),r||{},`$selected`));e=e.pipe(Hi(([,e])=>{let t=Ra(e);return Mn(n(t))}))}if(i&&i.length>0)for(let t of i)e=e.pipe(Hi(([,e])=>{let n=Ra(e);return Mn(t(n))}));return e}let c=Ka(t,r),l=t.map(e=>H(e)),u=([,e])=>{let n={...e};delete n.$selected;let r={};for(let e=0;e<t.length;e++){let t=l[e],i=t(n);r[`__key_${e}`]=i}return o&&Ia(r,e,o),r},d=s,f={},p={value:0};if(r){for(let[e,n]of Object.entries(r))if(n.type===`agg`)d[e]=Ya(n);else if(Qa(n)){let{transformed:r,extracted:i}=$a(n,p);for(let[e,t]of Object.entries(i))d[e]=Ya(t);f[e]=no(eo(r,t))}}if(e=e.pipe(Ai(u,d)),e=e.pipe(W(([,e])=>{let n=e.$selected||{},i={};if(r){for(let[t,a]of Object.entries(r))if(a.type===`agg`)i[t]=e[t];else if(!f[t]){let r=c.selectToGroupByIndex.get(t);i[t]=r===void 0?n[t]:e[`__key_${r}`]}Za(i,e,f,t.length)}else for(let n=0;n<t.length;n++)i[`__key_${n}`]=e[`__key_${n}`];let s=o?e.__correlationKey:void 0,l=o?La(e):void 0,u=[];for(let n=0;n<t.length;n++)u.push(e[`__key_${n}`]);l!==void 0&&u.push(l);let d=u.length===1?u[0]:U(u),p={...e,$selected:i},m=e[Na],h=e[Pa];return p.$synced=m??!0,p.$origin=h?`local`:`remote`,p.$key=d,p.$collectionId=a??p.$collectionId,o&&s!==void 0&&(p[o]={__correlationKey:s}),[d,p]})),n&&n.length>0)for(let t of n){let n=H(Xa(Me(t),r||{}));e=e.pipe(Hi(([,e])=>{let t=Ra(e);return n(t)}))}if(i&&i.length>0)for(let t of i)e=e.pipe(Hi(([,e])=>{let n=Ra(e);return Mn(t(n))}));return e}function Ja(e,t){if(!e||!t||e.type!==t.type)return!1;switch(e.type){case`ref`:return!e.path||!t.path||e.path.length!==t.path.length?!1:e.path.every((e,n)=>e===t.path[n]);case`val`:return e.value===t.value;case`func`:return e.name===t.name&&e.args?.length===t.args?.length&&(e.args||[]).every((e,n)=>Ja(e,t.args[n]));case`agg`:return e.name===t.name&&e.args?.length===t.args?.length&&(e.args||[]).every((e,n)=>Ja(e,t.args[n]));default:return!1}}function Ya(e){let t=H(e.args[0]),n=([,e])=>{let n=t(e);return typeof n==`number`?n:n==null?0:Number(n)},r=([,e])=>{let n=t(e);return typeof n==`number`||typeof n==`string`||typeof n==`bigint`||n instanceof Date?n:n==null?0:Number(n)},i=([,e])=>t(e);switch(e.name.toLowerCase()){case`sum`:return Va(n);case`count`:return Ha(i);case`avg`:return Ua(n);case`min`:return Wa(r);case`max`:return Ga(r);default:throw new en(e.name)}}function Xa(e,t,n=`$selected`){switch(e.type){case`agg`:{let r=e;for(let[e,i]of Object.entries(t))if(i.type===`agg`&&so(r,i))return new z([n,e]);throw new tn(r.name)}case`func`:{let n=e,r=n.args.map(e=>Xa(e,t));return new Te(n.name,r)}case`ref`:return e;case`val`:return e;default:throw new nn(e.type)}}function Za(e,t,n,r=0){for(let n of Object.keys(t))n.startsWith(`__agg_`)&&(e[n]=t[n]);for(let n=0;n<r;n++)e[`${Fa}${n}`]=t[`__key_${n}`];for(let[r,i]of Object.entries(n))e[r]=i(za(t,e));for(let t of Object.keys(e))(t.startsWith(`__agg_`)||t.startsWith(Fa))&&delete e[t]}function Qa(e){return oo(e)?e.branches.some(e=>Qa(e.condition)||Qa(e.value))||e.defaultValue!==void 0&&Qa(e.defaultValue):ao(e)?Object.values(e).some(e=>Qa(e)):ke(e)?e.type===`agg`||e.type===`func`&&`args`in e&&e.args.some(e=>Qa(e)):!1}function $a(e,t){if(e.type===`includesSubquery`)return{transformed:e,extracted:{}};if(e.type===`agg`){let n=`__agg_${t.value++}`;return{transformed:new z([`$selected`,n]),extracted:{[n]:e}}}if(e.type===`func`){let n={},r=e.args.map(e=>{let r=$a(e,t);return Object.assign(n,r.extracted),r.transformed});return{transformed:new Te(e.name,r),extracted:n}}if(oo(e)){let n={},r=e.branches.map(e=>{let r=$a(e.condition,t),i=$a(e.value,t);return Object.assign(n,r.extracted,i.extracted),{condition:r.transformed,value:i.transformed}}),i=e.defaultValue===void 0?void 0:$a(e.defaultValue,t);return i&&Object.assign(n,i.extracted),{transformed:new Oe(r,i?.transformed),extracted:n}}if(ao(e)){let n={},r={};for(let[i,a]of Object.entries(e)){let e=$a(a,t);Object.assign(n,e.extracted),r[i]=e.transformed}return{transformed:r,extracted:n}}return{transformed:e,extracted:{}}}function eo(e,t){if(oo(e))return new Oe(e.branches.map(e=>({condition:to(e.condition,t),value:eo(e.value,t)})),e.defaultValue===void 0?void 0:eo(e.defaultValue,t));if(ao(e)){let n={};for(let[r,i]of Object.entries(e))n[r]=eo(i,t);return n}return!ke(e)||e.type===`includesSubquery`||e.type===`agg`?e:to(e,t)}function to(e,t){if(e.type===`ref`){let n=t.findIndex(t=>Ja(e,t));return n===-1?e:new z([`$selected`,`${Fa}${n}`])}return e.type===`func`?new Te(e.name,e.args.map(e=>to(e,t))):e}function no(e){return oo(e)?io(e):e.type===`includesSubquery`?()=>null:ao(e)?ro(e):ke(e)?H(e):()=>e}function ro(e){let t=Object.entries(e).map(([e,t])=>{if(e.startsWith(`__SPREAD_SENTINEL__`)){let n=e.slice(19),r=n.lastIndexOf(`__`),i=r>=0?n.slice(0,r):n;return{key:e,spread:!0,value:H(typeof t==`object`&&`type`in t&&t.type===`ref`?t:new z(i.split(`.`)))}}return{key:e,spread:!1,value:no(t)}});return e=>{let n={};for(let r of t){let t=r.value(e);r.spread?t&&typeof t==`object`&&Object.assign(n,t):n[r.key]=t}return n}}function io(e){let t=e.branches.map(e=>({condition:H(e.condition),value:no(e.value)})),n=e.defaultValue===void 0?void 0:no(e.defaultValue);return e=>{for(let n of t)if(Rn(n.condition(e)))return n.value(e);return n===void 0?null:n(e)}}function ao(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!e.__refProxy&&!ke(e)}function oo(e){return e instanceof Oe||typeof e==`object`&&!!e&&e.type===`conditionalSelect`}function so(e,t){return e.name===t.name&&e.args.length===t.args.length&&e.args.every((e,n)=>Ja(e,t.args[n]))}function co(e,t,n,r,i,a,o,s,c,l){let u=n.map(e=>({compiledExpression:H(Xa(e.expression,r,`$selected`)),compareOptions:lo(e,i)})),d=e=>{let t=e;return n.length>1?u.map(e=>e.compiledExpression(t)):n.length===1?u[0].compiledExpression(t):null},f=(e,t)=>{if(n.length>1){let r=e,i=t;for(let e=0;e<n.length;e++){let t=u[e],n=yn(t.compareOptions)(r[e],i[e]);if(n!==0)return n}return r.length-i.length}if(n.length===1){let n=u[0];return yn(n.compareOptions)(e,t)}return bn(e,t)},p,m;if(s&&!l&&e.from.type!==`unionFrom`&&e.from.type!==`unionAll`){let t,r,o,l=e.from.alias,u,d=n[0],h=d.expression;if(h.type===`ref`){let n=Ie(e,h,i);if(n){r=n.collection,u=n.sourceId;let i=n.path[0],a=lo(d,r);if(i){let e=yn(a);ur(i,n.path,r,a,e)}if(o=H(new z(n.path),!0),t=Gn(r,n.path,a),t?.supports(`gt`)||(t=void 0),!t){let e=r.id,t=n.path.join(`.`);console.warn(`[TanStack DB]${e?` [${e}]`:``} orderBy with limit requires an index on "${t}" for efficient lazy loading. Falling back to loading all data. Consider creating an index on the collection with collection.createIndex((row) => row.${t}) or enable auto-indexing with autoIndex: 'eager' and a defaultIndexType.`)}l=h.path.length>1?String(h.path[0]):e.from.alias,u??=Ae(e).find(e=>e.alias===l&&e.collection===r)?.sourceId}}if(o&&u){let r=n.every(e=>e.expression.type===`ref`)?n.map(t=>{let n=t.expression,r=Ie(e,n,i);return H(r?new z(r.path):t.expression,!0)}):void 0;m={sourceId:u,alias:l,offset:c??0,limit:s,comparator:(e,t)=>{if(n.length===1){let n=e&&o(e),r=t&&o(t);return f(n,r)}if(r){let n=e=>e&&r.map(t=>t(e));return f(n(e),n(t))}return 0},valueExtractorForRawRow:e=>{if(n.length===1)return o(e);if(r)return r.map(t=>t(e))},firstColumnValueExtractor:o,index:t,orderBy:n},a[u]=m,t&&(p=e=>{a[u].dataNeeded=()=>{let t=e();return Math.max(0,m.limit-t)}})}}return l?t.pipe(Ma(d,{limit:s,offset:c,comparator:f,setSizeCallback:p,groupKeyFn:l,setWindowFn:e=>{o(t=>{e(t),m&&(m.offset=t.offset??m.offset,m.limit=t.limit??m.limit)})}})):t.pipe(ja(d,{limit:s,offset:c,comparator:f,setSizeCallback:p,setWindowFn:e=>{o(t=>{e(t),m&&(m.offset=t.offset??m.offset,m.limit=t.limit??m.limit)})}}))}function lo(e,t){return e.compareOptions.stringSort===void 0?{...t.compareOptions,direction:e.compareOptions.direction,nulls:e.compareOptions.nulls}:e.compareOptions}function uo(e,t={}){let n=t=>{let n=[];for(let[r,i]of e.entries())(t?.(i)??!0)&&n.push({type:`insert`,key:r,value:i});return n};if(t.limit!==void 0&&!t.orderBy)throw Error(`limit cannot be used without orderBy`);if(t.orderBy){let n=t.where?fo(t.where):void 0,r=mo(e,t.orderBy,t.limit,n,t.optimizedOnly);if(r===void 0)return;let i=[];for(let t of r){let n=e.get(t);n!==void 0&&i.push({type:`insert`,key:t,value:n})}return i}if(!t.where)return n();try{let r=t.where,i=Qn(r,e);if(i.canOptimize){let t=i.isExact?void 0:fo(r),n=[];for(let r of i.matchingKeys){let i=e.get(r);i!==void 0&&(t?.(i)??!0)&&n.push({type:`insert`,key:r,value:i})}return n}return t.optimizedOnly?void 0:n(fo(r))}catch(r){console.warn(`${e.id?`[${e.id}] `:``}Error processing where clause, falling back to full scan:`,r);let i=fo(t.where);return t.optimizedOnly?void 0:n(i)}}function fo(e){let t=Nn(e);return e=>{try{return Mn(t(e))}catch{return!1}}}function po(e,t){let n=fo(t.whereExpression);return t=>{let r=[];for(let e of t)if(e.type===`insert`)n(e.value)&&r.push(e);else if(e.type===`update`){let t=n(e.value),i=e.previousValue?n(e.previousValue):!1;t&&i?r.push(e):t&&!i?r.push({...e,type:`insert`}):!t&&i&&r.push({...e,type:`delete`,value:e.previousValue})}else n(e.value)&&r.push(e);return r.length>0||t.length===0?(e(r),!0):!1}}function mo(e,t,n,r,i){if(t.length===1){let i=t[0],a=i.expression;if(a.type===`ref`){let t=a.path,o=lo(i,e);ur(t[0],t,e,o);let s=Gn(e,t,o);if(s&&s.supports(`gt`))return s.takeFromStart(n??s.keyCount,t=>{let n=e.get(t);return n===void 0?!1:r?.(n)??!0})}}if(i)return;let a=[];for(let[t,n]of e.entries())(r?.(n)??!0)&&a.push({key:t,value:n});a.sort((e,n)=>{for(let r of t){let t=yn(r.compareOptions)(ho(e.value,r.expression),ho(n.value,r.expression));if(t!==0)return t}return 0});let o=a.map(e=>e.key);return n===void 0?o:o.slice(0,n)}function ho(e,t){if(t.type===`ref`){let n=t,r=e;for(let e of n.path)r=r?.[e];return r}return t.type===`val`?t.value:Nn(t)(e)}var go=class{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,t){let n=0,r=this.sortedKeys.length;if(!this.comparator){for(;n<r;){let t=Math.floor((n+r)/2),i=this.sortedKeys[t],a=br(e,i);if(a<0)r=t;else if(a>0)n=t+1;else return t}return n}for(;n<r;){let i=Math.floor((n+r)/2),a=this.sortedKeys[i],o=this.map.get(a),s=this.comparator(t,o);if(s<0)r=i;else if(s>0)n=i+1;else{let t=br(e,a);if(t<0)r=i;else if(t>0)n=i+1;else return i}}return n}set(e,t){if(this.map.has(e)){let t=this.map.get(e),n=this.indexOf(e,t);this.sortedKeys.splice(n,1)}let n=this.indexOf(e,t);return this.sortedKeys.splice(n,0,e),this.map.set(e,t),this}get(e){return this.map.get(e)}delete(e){if(this.map.has(e)){let t=this.map.get(e),n=this.indexOf(e,t);return this.sortedKeys.splice(n,1),this.map.delete(e)}return!1}has(e){return this.map.has(e)}clear(){this.map.clear(),this.sortedKeys=[]}get size(){return this.map.size}*[Symbol.iterator](){for(let e of this.sortedKeys)yield[e,this.map.get(e)]}entries(){return this[Symbol.iterator]()}keys(){return this.sortedKeys[Symbol.iterator]()}values(){return(function*(){for(let e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(let t of this.sortedKeys)e(this.map.get(t),t,this.map)}},_o=`__tanstack_db_direct`,vo=class{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.hydrationSeedKeys=new Set,this.hydratedKeys=new Set,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.pendingOptimisticUpserts=new Map,this.pendingOptimisticDeletes=new Set,this.pendingOptimisticDirectUpserts=new Set,this.pendingOptimisticDirectDeletes=new Set,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.virtualPropsCache=new WeakMap,this.size=0,this.syncedKeys=new Set,this.preSyncVisibleState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{let e=!1;for(let t of this.transactions.values())if(t.state===`persisting`){e=!0;break}let{committedSyncedTransactions:t,uncommittedSyncedTransactions:n,hasTruncateSync:r,hasImmediateSync:i,layoutChanged:a}=this.pendingSyncedTransactions.reduce((e,t)=>(t.committed?(e.committedSyncedTransactions.push(t),e.layoutChanged||=t.layoutChanged,t.truncate&&(e.hasTruncateSync=!0),t.immediate&&(e.hasImmediateSync=!0)):e.uncommittedSyncedTransactions.push(t),e),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1,layoutChanged:!1});if(!e||r||i){for(let e of t)e.applicationStarted=!0;this.isCommittingSyncTransactions=!0;let e=r?t.find(e=>e.truncate)?.optimisticSnapshot:null,i,o,s=new Set;for(let e of t){for(let t of e.operations)s.add(t.key);for(let[t]of e.rowMetadataWrites)s.add(t)}let c=new Set(s);for(let e of this.pendingOptimisticDirectUpserts)c.add(e);for(let e of this.pendingOptimisticDirectDeletes)c.add(e);let l=this.snapshotRowOriginsForKeys(c),u=new Map(this.optimisticUpserts),d=new Set(this.optimisticDeletes),f=this.preSyncVisibleState;if(f.size===0){f=new Map;for(let e of s){let t=this.get(e);t!==void 0&&f.set(e,t)}}let p=[],m=this.config.sync.rowUpdateMode||`partial`,h=new Map;for(let e of this.transactions.values())if(e.state===`completed`)for(let t of e.mutations)this.isThisCollection(t.collection)&&t.optimistic&&h.set(t.key,{type:t.type,value:t.modified});for(let n of t){if(n.truncate){let t=new Set([...this.syncedData.keys(),...e?.upserts.keys()||[]]);for(let n of t){if(e?.deletes.has(n))continue;let t=e?.upserts.get(n)||this.syncedData.get(n);t!==void 0&&p.push({type:`delete`,key:n,value:t})}i=new Set(this.pendingLocalChanges),o=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState();for(let e of s)f.delete(e);this._events.emit(`truncate`,{type:`truncate`,collection:this.collection})}for(let e of n.operations){let t=e.key;this.syncedKeys.add(t);let r=this.isLocalOnly||this.pendingLocalChanges.has(t)||this.pendingLocalOrigins.has(t)||i?.has(t)===!0||o?.has(t)===!0?`local`:`remote`;switch(e.type){case`insert`:this.syncedData.set(t,e.value),this.rowOrigins.set(t,r),this.pendingLocalChanges.delete(t),this.pendingLocalOrigins.delete(t),this.pendingOptimisticUpserts.delete(t),this.pendingOptimisticDeletes.delete(t),this.pendingOptimisticDirectUpserts.delete(t),this.pendingOptimisticDirectDeletes.delete(t);break;case`update`:if(m===`partial`){let n=Object.assign({},this.syncedData.get(t),e.value);this.syncedData.set(t,n)}else this.syncedData.set(t,e.value);this.rowOrigins.set(t,r),this.pendingLocalChanges.delete(t),this.pendingLocalOrigins.delete(t),this.pendingOptimisticUpserts.delete(t),this.pendingOptimisticDeletes.delete(t),this.pendingOptimisticDirectUpserts.delete(t),this.pendingOptimisticDirectDeletes.delete(t);break;case`delete`:this.syncedData.delete(t),this.syncedMetadata.delete(t),this.rowOrigins.delete(t),this.pendingLocalChanges.delete(t),this.pendingLocalOrigins.delete(t),this.pendingOptimisticUpserts.delete(t),this.pendingOptimisticDeletes.delete(t),this.pendingOptimisticDirectUpserts.delete(t),this.pendingOptimisticDirectDeletes.delete(t)}n.preserveHydrationSeedKeys||(this.hydrationSeedKeys.delete(t),this.hydratedKeys.delete(t))}for(let[e,t]of n.rowMetadataWrites){if(t.type===`delete`){this.syncedMetadata.delete(e);continue}this.syncedMetadata.set(e,t.value)}for(let[e,t]of n.collectionMetadataWrites){if(t.type===`delete`){this.syncedCollectionMetadata.delete(e);continue}this.syncedCollectionMetadata.set(e,t.value)}}if(r){let n=new Set;for(let e of t)for(let t of e.operations)(t.type===`insert`||t.type===`update`)&&n.add(t.key);let r=new Map(e.upserts),i=new Set(e.deletes);for(let[e,t]of r)if(!i.has(e)){if(n.has(e)){let n=!1;for(let r=p.length-1;r>=0;r--){let i=p[r];if(i.key===e&&i.type===`insert`){i.value=t,n=!0;break}}n||p.push({type:`insert`,key:e,value:t})}else p.push({type:`insert`,key:e,value:t})}if(p.length>0&&i.size>0){let e=[];for(let t of p)t.type===`insert`&&i.has(t.key)||e.push(t);p.length=0,p.push(...e)}this.lifecycle.status!==`ready`&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,r&&e){for(let[t,n]of e.upserts)this.optimisticUpserts.set(t,n);for(let t of e.deletes)this.optimisticDeletes.add(t)}for(let e of this.transactions.values())if(![`completed`,`failed`].includes(e.state)){for(let t of e.mutations)if(this.isThisCollection(t.collection)&&t.optimistic)switch(t.type){case`insert`:case`update`:this.optimisticUpserts.set(t.key,t.modified),this.optimisticDeletes.delete(t.key);break;case`delete`:this.optimisticUpserts.delete(t.key),this.optimisticDeletes.add(t.key)}}for(let e of this.pendingOptimisticDirectUpserts)if(!s.has(e)){if(s.add(e),!f.has(e)){let t=u.get(e);t!==void 0&&f.set(e,t)}this.pendingOptimisticUpserts.delete(e),this.pendingLocalOrigins.delete(e)}for(let e of this.pendingOptimisticDirectDeletes)s.has(e)||s.add(e),this.pendingOptimisticDeletes.delete(e),this.pendingLocalOrigins.delete(e);this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear();for(let e of s){let t=f.get(e),n=this.get(e),r=this.getVirtualPropsSnapshotForState(e,{rowOrigins:l,optimisticUpserts:u,optimisticDeletes:d,completedOptimisticKeys:h}),i=this.getVirtualPropsSnapshotForState(e),a=r.$synced!==i.$synced||r.$origin!==i.$origin,o=t===void 0?void 0:Vn(t,e,this.collection.id,()=>r.$synced,()=>r.$origin),s=h.get(e),c=!1;s&&(s.type===`delete`&&t!==void 0&&n===void 0&&B(s.value,t)||n!==void 0&&B(s.value,n))&&(c=!0);let m=a&&t!==void 0&&n!==void 0&&B(t,n);if(!(c&&!m)){if(t===void 0&&n!==void 0){let t=h.get(e);if(t){let i=t.value,a=Vn(i,e,this.collection.id,()=>r.$synced,()=>r.$origin);p.push({type:`update`,key:e,value:n,previousValue:a})}else p.push({type:`insert`,key:e,value:n})}else t!==void 0&&n===void 0?p.push({type:`delete`,key:e,value:o??t}):t!==void 0&&n!==void 0&&(!B(t,n)||m)&&p.push({type:`update`,key:e,value:n,previousValue:o??t})}}this.size=this.calculateSize(),p.length>0&&this.indexes.updateIndexes(p),this.changes.emitEvents(p,!0,a),this.pendingSyncedTransactions=n,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||=!0;for(let e of t)e.applied.resolve()}},this.config=e,this.transactions=new go((e,t)=>e.compareCreatedAt(t)),this.syncedData=new go(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this._events=e.events}isRowSynced(e){return this.isLocalOnly?!0:!this.optimisticUpserts.has(e)&&!this.optimisticDeletes.has(e)}getRowOrigin(e){return this.isLocalOnly||this.optimisticUpserts.has(e)||this.optimisticDeletes.has(e)?`local`:this.rowOrigins.get(e)??`remote`}createVirtualPropsSnapshot(e,t){return{$synced:t?.$synced??this.isRowSynced(e),$origin:t?.$origin??this.getRowOrigin(e),$key:t?.$key??e,$collectionId:t?.$collectionId??this.collection.id}}getVirtualPropsSnapshotForState(e,t){if(this.isLocalOnly)return this.createVirtualPropsSnapshot(e,{$synced:!0,$origin:`local`});let n=t?.optimisticUpserts??this.optimisticUpserts,r=t?.optimisticDeletes??this.optimisticDeletes,i=n.has(e)||r.has(e)||t?.completedOptimisticKeys?.has(e)===!0;return this.createVirtualPropsSnapshot(e,{$synced:!i,$origin:i?`local`:(t?.rowOrigins??this.rowOrigins).get(e)??`remote`})}snapshotRowOriginsForKeys(e){let t=new Map;for(let n of e){let e=this.rowOrigins.get(n);e!==void 0&&t.set(n,e)}return t}enrichWithVirtualPropsSnapshot(e,t){let n=e,r=n.$synced??t.$synced,i=n.$origin??t.$origin,a=n.$key??t.$key,o=n.$collectionId??t.$collectionId,s=this.virtualPropsCache.get(e);if(s&&s.synced===r&&s.origin===i&&s.key===a&&s.collectionId===o)return s.enriched;let c={...e,$synced:r,$origin:i,$key:a,$collectionId:o};return this.virtualPropsCache.set(e,{synced:r,origin:i,key:a,collectionId:o,enriched:c}),c}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.enrichWithVirtualPropsSnapshot(e,this.createVirtualPropsSnapshot(t))}enrichChangeMessage(e){let{__virtualProps:t}=e,n=t?.value?this.enrichWithVirtualPropsSnapshot(e.value,t.value):this.enrichWithVirtualProps(e.value,e.key),r=e.previousValue?t?.previousValue?this.enrichWithVirtualPropsSnapshot(e.previousValue,t.previousValue):this.enrichWithVirtualProps(e.previousValue,e.key):void 0;return{key:e.key,type:e.type,value:n,previousValue:r,metadata:e.metadata}}getWithVirtualProps(e){let t=this.get(e);if(t!==void 0)return this.enrichWithVirtualProps(t,e)}get(e){let{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;if(!t.has(e))return n.has(e)?n.get(e):r.get(e)}has(e){let{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;return t.has(e)?!1:n.has(e)?!0:r.has(e)}*keys(){let{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(let n of e.keys())t.has(n)||(yield n);for(let r of n.keys())!e.has(r)&&!t.has(r)&&(yield r)}*values(){for(let e of this.keys()){let t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(let e of this.keys()){let t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){for(let[e,t]of this.entries())yield[e,t]}forEach(e){let t=0;for(let[n,r]of this.entries())e(r,n,t++)}map(e){let t=[],n=0;for(let[r,i]of this.entries())t.push(e(i,r,n++));return t}isThisCollection(e){return e===this.collection}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;let t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes),r=this.rowOrigins;for(let e of this.transactions.values()){let t=e.metadata[_o]===!0;if(e.state===`completed`){for(let n of e.mutations)if(this.isThisCollection(n.collection)&&(this.pendingLocalOrigins.add(n.key),n.optimistic))switch(n.type){case`insert`:case`update`:this.pendingOptimisticUpserts.set(n.key,n.modified),this.pendingOptimisticDeletes.delete(n.key),t?(this.pendingOptimisticDirectUpserts.add(n.key),this.pendingOptimisticDirectDeletes.delete(n.key)):(this.pendingOptimisticDirectUpserts.delete(n.key),this.pendingOptimisticDirectDeletes.delete(n.key));break;case`delete`:this.pendingOptimisticUpserts.delete(n.key),this.pendingOptimisticDeletes.add(n.key),t?(this.pendingOptimisticDirectUpserts.delete(n.key),this.pendingOptimisticDirectDeletes.add(n.key)):(this.pendingOptimisticDirectUpserts.delete(n.key),this.pendingOptimisticDirectDeletes.delete(n.key))}}else if(e.state===`failed`)for(let t of e.mutations)this.isThisCollection(t.collection)&&(this.pendingLocalOrigins.delete(t.key),t.optimistic&&(this.pendingOptimisticUpserts.delete(t.key),this.pendingOptimisticDeletes.delete(t.key),this.pendingOptimisticDirectUpserts.delete(t.key),this.pendingOptimisticDirectDeletes.delete(t.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();let i=new Set;for(let e of this.pendingSyncedTransactions)for(let t of e.operations)i.add(t.key);let a=[];for(let[e,t]of this.pendingOptimisticUpserts)i.has(e)||this.pendingOptimisticDirectUpserts.has(e)?this.optimisticUpserts.set(e,t):a.push(e);for(let e of a)this.pendingOptimisticUpserts.delete(e),this.pendingLocalOrigins.delete(e);let o=[];for(let e of this.pendingOptimisticDeletes)i.has(e)||this.pendingOptimisticDirectDeletes.has(e)?this.optimisticDeletes.add(e):o.push(e);for(let e of o)this.pendingOptimisticDeletes.delete(e),this.pendingLocalOrigins.delete(e);let s=[];for(let e of this.transactions.values())[`completed`,`failed`].includes(e.state)||s.push(e);for(let e of s)for(let t of e.mutations)if(this.isThisCollection(t.collection)&&(this.pendingLocalChanges.add(t.key),t.optimistic))switch(t.type){case`insert`:case`update`:this.optimisticUpserts.set(t.key,t.modified),this.optimisticDeletes.delete(t.key);break;case`delete`:this.optimisticUpserts.delete(t.key),this.optimisticDeletes.add(t.key)}this.size=this.calculateSize();let c=[];this.collectOptimisticChanges(t,n,r,c);let l=c.filter(t=>!!(!this.recentlySyncedKeys.has(t.key)||e));if(this.pendingSyncedTransactions.length>0&&!e){let t=new Set;for(let e of this.pendingSyncedTransactions)for(let n of e.operations)t.add(n.key);let n=l.filter(e=>!(e.type===`delete`&&t.has(e.key)&&!s.some(t=>t.mutations.some(t=>this.isThisCollection(t.collection)&&t.key===e.key))));n.length>0&&this.indexes.updateIndexes(n),this.changes.emitEvents(n,e)}else l.length>0&&this.indexes.updateIndexes(l),this.changes.emitEvents(l,e)}calculateSize(){let e=this.syncedData.size,t=Array.from(this.optimisticDeletes).filter(e=>this.syncedData.has(e)&&!this.optimisticUpserts.has(e)).length,n=Array.from(this.optimisticUpserts.keys()).filter(e=>!this.syncedData.has(e)).length;return e-t+n}collectOptimisticChanges(e,t,n,r){let i=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(let a of i){let i=this.get(a),o=this.getPreviousValue(a,e,t),s=this.getVirtualPropsSnapshotForState(a,{rowOrigins:n,optimisticUpserts:e,optimisticDeletes:t}),c=this.getVirtualPropsSnapshotForState(a);o!==void 0&&i===void 0?r.push({type:`delete`,key:a,value:o,__virtualProps:{value:s}}):o===void 0&&i!==void 0?r.push({type:`insert`,key:a,value:i,__virtualProps:{value:c}}):o!==void 0&&i!==void 0&&o!==i&&r.push({type:`update`,key:a,value:i,previousValue:o,__virtualProps:{value:c,previousValue:s}})}}getPreviousValue(e,t,n){if(!n.has(e))return t.has(e)?t.get(e):this.syncedData.get(e)}cancelPendingSyncedTransaction(e){if(e.applicationStarted)return;let t=this.pendingSyncedTransactions.indexOf(e);if(t===-1)return;this.pendingSyncedTransactions.splice(t,1),e.applied.reject(new an);let n=new Set;for(let e of this.pendingSyncedTransactions)for(let t of e.operations)n.add(t.key);for(let t of e.operations){let e=t.key;n.has(e)||(this.recentlySyncedKeys.delete(e),this.preSyncVisibleState.delete(e))}this.pendingSyncedTransactions.length===0?(this.preSyncVisibleState.clear(),this.recentlySyncedKeys.clear(),this.changes.emitEvents([],!0)):this.recomputeOptimisticState(!1)}scheduleTransactionCleanup(e){if(e.state===`completed`){this.transactions.delete(e.id);return}e.isPersisted.promise.then(()=>{this.transactions.delete(e.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;let e=new Set;for(let t of this.pendingSyncedTransactions)for(let n of t.operations)e.add(n.key);for(let t of e)this.recentlySyncedKeys.add(t);for(let t of e)if(!this.preSyncVisibleState.has(t)){let e=this.get(t);e!==void 0&&this.preSyncVisibleState.set(t,e)}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){for(let e of this.pendingSyncedTransactions)e.applied.reject(new an);this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingOptimisticUpserts.clear(),this.pendingOptimisticDeletes.clear(),this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.syncedKeys.clear(),this.hasReceivedFirstCommit=!1}};function yo(e){return typeof e==`object`&&!!e&&typeof e.hasPendingGraphRun==`function`}var bo=new class{constructor(){this.contexts=new Map,this.clearListeners=new Set}getOrCreateContext(e){let t=this.contexts.get(e);return t||(t={queue:[],jobs:new Map,dependencies:new Map,completed:new Set},this.contexts.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:r}){if(e===void 0){r();return}let i=this.getOrCreateContext(e);if(i.jobs.has(t)||i.queue.push(t),i.jobs.set(t,r),n){let e=new Set(n);e.delete(t),i.dependencies.set(t,e)}else i.dependencies.has(t)||i.dependencies.set(t,new Set);i.completed.delete(t)}flush(e){let t=this.contexts.get(e);if(!t)return;let{queue:n,jobs:r,dependencies:i,completed:a}=t;for(;n.length>0;){let t=!1,o=n.length;for(let s=0;s<o;s++){let o=n.shift(),s=r.get(o);if(!s){i.delete(o),a.delete(o);continue}let c=i.get(o),l=!c;if(c){l=!0;for(let t of c){if(t===o)continue;let n=yo(t)&&t.hasPendingGraphRun(e);if(r.has(t)&&!a.has(t)||!r.has(t)&&n){l=!1;break}}}l?(r.delete(o),i.delete(o),s(),a.add(o),t=!0):n.push(o)}if(!t)throw Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}flushAll(){for(let e of Array.from(this.contexts.keys()))this.flush(e)}clear(e){this.contexts.delete(e),this.clearListeners.forEach(t=>t(e))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}hasPendingJobs(e){let t=this.contexts.get(e);return!!t&&t.jobs.size>0}clearJob(e,t){let n=this.contexts.get(e);n&&(n.jobs.delete(t),n.dependencies.delete(t),n.completed.delete(t),n.queue=n.queue.filter(e=>e!==t),n.jobs.size===0&&this.contexts.delete(e))}},xo;function So(){return xo}function Co(e){if(xo!==void 0)return e();let t=Symbol(`collection-publication`);xo=t;try{let n=e();return bo.flush(t),n}catch(e){throw bo.clear(t),e}finally{xo=void 0}}function wo(){let e=new Map;function t(n){let r=n.join(`.`);if(e.has(r))return e.get(r);let i=new Proxy({},{get(e,r,i){if(r===`__refProxy`)return!0;if(r===`__path`)return n;if(r!==`__type`)return typeof r==`symbol`?Reflect.get(e,r,i):t([...n,String(r)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__type`||Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return e.set(r,i),i}return t([])}function To(e){let t=new Map,n=0;function r(e){let i=e.join(`.`);if(t.has(i))return t.get(i);let a=new Proxy({},{get(t,n,i){if(n===`__refProxy`)return!0;if(n===`__path`)return e;if(n!==`__type`)return typeof n==`symbol`?Reflect.get(t,n,i):r([...e,String(n)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__type`||Reflect.has(e,t)},ownKeys(t){let r=++n,i=`__SPREAD_SENTINEL__${e.join(`.`)}__${r}`;return Object.prototype.hasOwnProperty.call(t,i)||Object.defineProperty(t,i,{enumerable:!0,configurable:!0,value:!0}),Reflect.ownKeys(t)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return t.set(i,a),a}return new Proxy({},{get(t,n,i){if(n===`__refProxy`)return!0;if(n===`__path`)return[];if(n===`__type`)return;if(typeof n==`symbol`)return Reflect.get(t,n,i);let a=String(n);if(e.includes(a)||e.includes(`*`))return r([a])},has(t,n){return n===`__refProxy`||n===`__path`||n===`__type`||typeof n==`string`&&e.includes(n)?!0:Reflect.has(t,n)},ownKeys(t){return[...e,`__refProxy`,`__path`,`__type`]},getOwnPropertyDescriptor(t,n){if(n===`__refProxy`||n===`__path`||n===`__type`)return{enumerable:!1,configurable:!0};if(typeof n==`string`&&e.includes(n))return{enumerable:!0,configurable:!0}}})}function Eo(e){let t=To(e),n=new Map;function r(e){let t=e.join(`.`);if(n.has(t))return n.get(t);let i=new Proxy({},{get(t,n,i){if(n===`__refProxy`)return!0;if(n===`__path`)return[`$selected`,...e];if(n!==`__type`)return typeof n==`symbol`?Reflect.get(t,n,i):r([...e,String(n)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__type`||Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return n.set(t,i),i}let i=r([]);return new Proxy(t,{get(e,t,n){return t===`$selected`?i:Reflect.get(e,t,n)},has(e,t){return t===`$selected`||Reflect.has(e,t)},ownKeys(e){return[...Reflect.ownKeys(e),`$selected`]},getOwnPropertyDescriptor(e,t){return t===`$selected`?{enumerable:!0,configurable:!0,value:i}:Reflect.getOwnPropertyDescriptor(e,t)}})}function G(e){if(Do(e))return new z(e.__path);if(e&&typeof e==`object`&&(e.__brand===`ToArrayWrapper`||e.__brand===`ConcatToArrayWrapper`||e.__brand===`CaseWhenWrapper`||e.__brand===`MaterializeWrapper`)){let t=e.__brand===`ToArrayWrapper`?`toArray()`:e.__brand===`ConcatToArrayWrapper`?`concat(toArray())`:e.__brand===`CaseWhenWrapper`?`caseWhen()`:`materialize()`;throw Error(`${t} cannot be used inside expressions (e.g., coalesce(), eq(), not()). Use ${t} directly as a select field value instead.`)}return e&&typeof e==`object`&&`type`in e&&(e.type===`func`||e.type===`ref`||e.type===`val`||e.type===`agg`)?e:new we(e)}function Do(e){return e&&typeof e==`object`&&e.__refProxy===!0}function Oo(e,t){return new Te(`eq`,[G(e),G(t)])}function ko(e,t){return new Te(`gt`,[G(e),G(t)])}function Ao(e,t){return new Te(`gte`,[G(e),G(t)])}function jo(e,t){return new Te(`lt`,[G(e),G(t)])}function Mo(e,t,...n){return new Te(`and`,[e,t,...n].map(e=>G(e)))}function No(e,t,...n){return new Te(`or`,[e,t,...n].map(e=>G(e)))}function Po(e,t){return new Te(`in`,[G(e),G(t)])}var Fo=class{constructor(e){this.query=e,this.__brand=`ToArrayWrapper`}},Io=class{constructor(e){this.query=e,this.__brand=`ConcatToArrayWrapper`}},Lo=class{constructor(e){this.args=e,this.__brand=`CaseWhenWrapper`}},Ro=class{constructor(e){this.query=e,this.__brand=`MaterializeWrapper`}},zo=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t)}}once(e,t){let n=this.on(e,e=>{t(e),n()});return n}off(e,t){this.listeners.get(e)?.delete(t)}waitFor(e,t){return new Promise((n,r)=>{let i,a=this.on(e,e=>{i&&=(clearTimeout(i),void 0),n(e),a()});t&&(i=setTimeout(()=>{i=void 0,a(),r(Error(`Timeout waiting for event ${String(e)}`))},t))})}emitInner(e,t){this.listeners.get(e)?.forEach(e=>{try{e(t)}catch(e){queueMicrotask(()=>{throw e})}})}clearListeners(){this.listeners.clear()}};function Bo(e,t){if(t.length===0||e.length===0)return;if(e.length===1){let{expression:n,compareOptions:r}=e[0];return(r.direction===`asc`?ko:jo)(n,new we(t[0]))}let n=[];for(let r=0;r<e.length&&r<t.length;r++){let i=e[r],a=t[r],o=[];for(let n=0;n<r;n++){let r=e[n],i=t[n];o.push(Oo(r.expression,new we(i)))}let s=(i.compareOptions.direction===`asc`?ko:jo)(i.expression,new we(a));if(o.length===0)n.push(s);else{let e=[...o,s];n.push(e.reduce((e,t)=>Mo(e,t)))}}return n.length===1?n[0]:n.reduce((e,t)=>No(e,t))}var Vo=class extends zo{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.subsetDemands=[],this.requestedSubsetWhere=new WeakMap,this.sentKeys=new Set,this.publishedRows=new Map,this.stalePublishedRows=new Map,this.limitedSnapshotRowCount=0,this._status=`ready`,this.pendingLoadSubsetPromises=new Set,n.onUnsubscribe&&this.on(`unsubscribed`,n.onUnsubscribe),n.onLoadSubsetError&&this.on(`loadSubset:error`,n.onLoadSubsetError),n.whereExpression&&dr(n.whereExpression,this.collection);let r=e=>{this.trackPublishedRows(e),this.trackSentKeys(e),t(e)};this.callback=r,this.filteredCallback=n.whereExpression?po(this.callback,n):e=>(this.callback(e),!0),this.truncateCleanup=this.collection.on(`truncate`,()=>{this.handleTruncate()})}get status(){return this._status}get lastError(){return this._lastError}handleTruncate(){let e=[...this.subsetDemands],t=this.collection._sync.syncLoadSubsetFn!==null;if(e.length===0||!t){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0;return}let n={pending:new Set,failed:!1,setupComplete:!1},r=this.truncateReplaySession;r||(r={publicationState:{loadedInitialState:this.loadedInitialState,snapshotSent:this.snapshotSent,sentKeys:new Set(this.sentKeys),publishedRows:new Map(this.publishedRows),limitedSnapshotRowCount:this.limitedSnapshotRowCount,lastSentKey:this.lastSentKey},buffer:[],attempts:new Set,currentAttempt:n},this.truncateReplaySession=r),r.attempts.add(n),r.currentAttempt=n;for(let t of e)t.abortController?.abort();this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,queueMicrotask(()=>{if(this.truncateReplaySession===r){for(let t of e){if(!this.subsetDemands.includes(t))continue;let e=()=>this.truncateReplaySession===r&&r.currentAttempt===n,i=this.createSubsetAcquisition(t),a;try{a=this.loadSubset(i.options,e)}catch{i.abortController.abort(),i.removeRequestAbortListener?.(),n.failed=!0;continue}if(this.observeLoadSubsetResult(a,i.options,!0,()=>e()&&!i.options.signal?.aborted),a instanceof Promise){let e={promise:a};n.pending.add(e),a.then(()=>this.settleTruncateReplay(r,n,e),()=>{this.subsetDemands.includes(t)&&!i.options.signal?.aborted&&(n.failed=!0),this.settleTruncateReplay(r,n,e)})}try{this.replaceSubsetAcquisition(t,i)}catch(e){i.abortController.abort(),i.removeRequestAbortListener?.();try{this.collection._sync.unloadSubset(i.options)}catch{}this.recordLoadSubsetError(t.options,e,!0),n.failed=!0}}n.setupComplete=!0,this.checkTruncateReplayComplete(r)}})}settleTruncateReplay(e,t,n){this.truncateReplaySession===e&&(t.pending.delete(n),this.checkTruncateReplayComplete(e))}checkTruncateReplayComplete(e){if(this.truncateReplaySession===e){for(let t of e.attempts)if(!t.setupComplete||t.pending.size>0)return;e.currentAttempt.failed?this.abandonTruncateReplay(e):this.flushTruncateReplay(e)}}abandonTruncateReplay(e){if(this.truncateReplaySession!==e)return;let t=e.publicationState;this.loadedInitialState=t.loadedInitialState,this.snapshotSent=t.snapshotSent,this.sentKeys=new Set(t.sentKeys),this.publishedRows=new Map(t.publishedRows),this.stalePublishedRows=new Map(t.publishedRows),this.limitedSnapshotRowCount=t.limitedSnapshotRowCount,this.lastSentKey=t.lastSentKey,this.truncateReplaySession=void 0}flushTruncateReplay(e){if(this.truncateReplaySession!==e)return;this.truncateReplaySession=void 0;let t=[...this.stalePublishedRows].map(([e,t])=>({type:`delete`,key:e,value:t}));this.stalePublishedRows.clear();let n=[...e.buffer.flat(),...t],r=this.subsetDemands.map(e=>e.requestOptions.where?fo(e.requestOptions.where):void 0),i=this.createPublicationDiff(e.publicationState.publishedRows,n,e=>r.some(t=>t?.(e)??!0));if(i.length>0&&this.filteredCallback(i),this.sentKeys=new Set(this.publishedRows.keys()),this.orderByIndex){this.limitedSnapshotRowCount=this.sentKeys.size;let e=this.orderByIndex.takeFromStart(this.sentKeys.size,e=>this.sentKeys.has(e));this.lastSentKey=e.at(-1)}}createPublicationDiff(e,t,n){let r=new Map(e);for(let e of t)e.type===`delete`?r.delete(e.key):r.set(e.key,e.value);for(let[e,t]of r)n(t)||r.delete(e);let i=[];for(let[t,n]of e){let e=r.get(t);e===void 0?i.push({type:`delete`,key:t,value:n}):B(e,n)||i.push({type:`update`,key:t,value:e,previousValue:n})}for(let[t,n]of r)e.has(t)||i.push({type:`insert`,key:t,value:n});return i}get isBufferingForTruncate(){return this.truncateReplaySession!==void 0}setOrderByIndex(e){this.orderByIndex=e}hasOrderByIndex(){return this.orderByIndex!==void 0}setStatus(e){if(this._status===e)return;let t=this._status;this._status=e,this.emitInner(`status:change`,{type:`status:change`,subscription:this,previousStatus:t,status:e});let n=`status:${e}`;this.emitInner(n,{type:n,subscription:this,previousStatus:t,status:e})}observeLoadSubsetResult(e,t,n,r=()=>!0){if(!(e instanceof Promise))return;n&&(this.pendingLoadSubsetPromises.add(e),this.setStatus(`loadingSubset`));let i=()=>{n&&(this.pendingLoadSubsetPromises.delete(e),this.pendingLoadSubsetPromises.size===0&&this.setStatus(`ready`))};e.then(i,e=>{r()&&this.recordLoadSubsetError(t,e),i()})}loadSubset(e,t=()=>!0){try{return this.collection._sync.loadSubset(e)}catch(n){throw t()&&this.recordLoadSubsetError(e,n),n}}createSubsetAcquisition(e){let t=new AbortController,n=e.requestOptions.signal,r;if(n?.aborted)t.abort(n.reason);else if(n){let e=()=>t.abort(n.reason);n.addEventListener(`abort`,e,{once:!0}),r=()=>n.removeEventListener(`abort`,e)}return{options:{...e.requestOptions,signal:t.signal},abortController:t,removeRequestAbortListener:r}}replaceSubsetAcquisition(e,t){let n=e.options,r=e.removeRequestAbortListener;this.collection._sync.unloadSubset(n),r?.(),e.options=t.options,e.abortController=t.abortController,e.removeRequestAbortListener=t.removeRequestAbortListener}releaseSubsetDemand(e){e.abortController?.abort();try{this.collection._sync.unloadSubset(e.options)}finally{e.removeRequestAbortListener?.()}}startSubsetDemand(e){let t={requestOptions:e,options:e},n=this.createSubsetAcquisition(t);try{let e=this.loadSubset(n.options);return t.options=n.options,t.abortController=n.abortController,t.removeRequestAbortListener=n.removeRequestAbortListener,this.subsetDemands.push(t),{demand:t,result:e}}catch(e){throw n.abortController.abort(),n.removeRequestAbortListener?.(),e}}recordLoadSubsetError(e,t,n=!1){e.signal?.aborted&&!n||(this._lastError=t,this.emitInner(`loadSubset:error`,{type:`loadSubset:error`,subscription:this,options:e,error:t}))}hasLoadedInitialState(){return this.loadedInitialState}hasSentAtLeastOneSnapshot(){return this.snapshotSent}emitEvents(e){let t=this.filterAndFlipChanges(e);return e.length>0&&t.length===0?!1:this.isBufferingForTruncate?(t.length>0&&this.truncateReplaySession.buffer.push(t),!1):this.filteredCallback(t)}requestSnapshot(e){if(this.loadedInitialState)return!1;let t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if(`where`in e){let n=e.where;if(t.where){let e=t.where;t.where=Mo(e,n)}else t.where=n}}else this.loadedInitialState=!0;let n={where:t.where,signal:e?.signal,subscription:this,orderBy:e?.orderBy,limit:e?.limit},{demand:r,result:i}=this.startSubsetDemand(n);e?.where&&this.requestedSubsetWhere.set(n,e.where),e?.onLoadSubsetResult?.(i),this.observeLoadSubsetResult(i,r.options,e?.trackLoadSubsetPromise??!0);let a;if(e?.onUnoptimized?(a=this.collection.currentStateAsChanges({...t,optimizedOnly:!0}),a===void 0&&(e.onUnoptimized(),a=this.collection.currentStateAsChanges({...t,optimizedOnly:!1}))):a=this.collection.currentStateAsChanges(t),a===void 0)return!1;let o=a.filter(e=>!this.sentKeys.has(e.key));for(let e of o)this.sentKeys.add(e.key);return this.snapshotSent=!0,this.callback(o),!0}releaseSnapshot(e){let t=this.subsetDemands.findIndex(t=>t.requestOptions.where===e||this.requestedSubsetWhere.get(t.requestOptions)===e);if(t===-1)return;let[n]=this.subsetDemands.splice(t,1);n&&this.releaseSubsetDemand(n)}requestLimitedSnapshot({orderBy:e,limit:t,minValues:n,offset:r,trackLoadSubsetPromise:i=!0,onLoadSubsetResult:a}){if(!t)throw Error(`limit is required`);if(!this.orderByIndex)throw Error(`Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.`);let o=n!==void 0&&n.length>0,s=n?.[0],c=this.orderByIndex,l=this.options.whereExpression,u=l?fo(l):void 0,d=e=>{if(e!==void 0&&this.sentKeys.has(e))return!1;let t=this.collection.get(e);return t===void 0?!1:u?.(t)??!0},f=s,p=[],m=[];if(o){let{expression:n}=e[0],r=this.collection.currentStateAsChanges({where:Oo(n,new we(s))});if(r){let e=r.map(e=>e.key).filter(e=>!this.sentKeys.has(e)&&d(e));m.push(...e);let n=c.take(t-m.length,s,d);m.push(...n)}else m=c.take(t,s,d)}else m=c.takeFromStart(t,d);let h=()=>Math.max(t-p.length,0),g=()=>m.length===0,_=e[0].expression,v=_.type===`ref`?H(new z(_.path),!0):null;for(;h()>0&&!g();){let e=new Set;for(let t of m){let n=this.collection.get(t);p.push({type:`insert`,key:t,value:n}),f=v?v(n):n,e.add(t)}m=c.take(h(),f,d)}let y=this.limitedSnapshotRowCount;for(let e of p)this.sentKeys.add(e.key);this.callback(p),this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,y+p.length),p.length>0&&(this.lastSentKey=p[p.length-1].key);let b;if(n!==void 0&&n.length>0){let t=Bo(e,n);if(t){let{expression:r}=e[0],i=n[0],a;if(i instanceof Date){let e=new Date(i.getTime()+1);a=Mo(Ao(r,new we(i)),jo(r,new we(e)))}else a=Oo(r,new we(i));b={whereFrom:t,whereCurrent:a,lastKey:this.lastSentKey}}}let x={where:l,limit:t,orderBy:e,cursor:b,offset:r??y,subscription:this},{demand:S,result:C}=this.startSubsetDemand(x);a?.(C),this.observeLoadSubsetResult(C,S.options,i)}filterAndFlipChanges(e){if(e=this.reconcileStalePublishedChanges(e),this.loadedInitialState||this.skipFiltering)return e;let t=this.isBufferingForTruncate,n=[];for(let r of e){let e=r;if(!this.sentKeys.has(r.key)){if(r.type===`update`)e={...r,type:`insert`,previousValue:void 0},this.sentKeys.add(r.key);else if(r.type===`delete`){if(!t)continue}else this.sentKeys.add(r.key)}else if(r.type===`insert`)continue;else r.type===`delete`&&this.sentKeys.delete(r.key);n.push(e)}return n}reconcileStalePublishedChanges(e){if(this.stalePublishedRows.size===0)return e;let t=[];for(let n of e){let e=this.stalePublishedRows.get(n.key);if(e===void 0){t.push(n);continue}this.stalePublishedRows.delete(n.key),n.type===`delete`?t.push({...n,value:e,previousValue:void 0}):B(e,n.value)||t.push({...n,type:`update`,previousValue:e})}return t}trackPublishedRows(e){for(let t of e)t.type===`delete`?this.publishedRows.delete(t.key):this.publishedRows.set(t.key,t.value)}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering)){for(let t of e)t.type===`delete`?this.sentKeys.delete(t.key):this.sentKeys.add(t.key);this.orderByIndex&&(this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,this.sentKeys.size))}}markAllStateAsSeen(){this.skipFiltering=!0}unsubscribe(){let e;try{this.truncateCleanup?.()}catch(t){e=t}this.truncateCleanup=void 0,this.truncateReplaySession=void 0,this.stalePublishedRows.clear();for(let t of this.subsetDemands)try{this.releaseSubsetDemand(t)}catch(t){e??=t}this.subsetDemands=[];try{this.emitInner(`unsubscribed`,{type:`unsubscribed`,subscription:this})}catch(t){e??=t}finally{this.clearListeners()}if(e!==void 0)throw e}},Ho=class{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1,this.publicationDeferralDepth=0,this.discardDeferredPublications=!1,this.deferredPublications=[],this.layoutChangeListeners=new Set,this.stateRevision=0,this.layoutRevision=0}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){Co(()=>{for(let e of this.changeSubscriptions)e.emitEvents([])})}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,t=!1,n=!1){if(e.length>0&&this.stateRevision++,n&&this.layoutRevision++,this.shouldBatchEvents&&!t){this.batchedEvents.push(...e);return}let r=e;if(t&&(this.batchedEvents.length>0&&(r=[...this.batchedEvents,...e]),this.batchedEvents=[],this.shouldBatchEvents=!1),this.publicationDeferralDepth>0){this.deferredPublications.push({changes:r,layoutChanged:n});return}this.publishEvents(r,n)}deferPublication(){this.publicationDeferralDepth++;let e=!1,t=t=>{if(e||(e=!0,this.publicationDeferralDepth===0)||(this.discardDeferredPublications||=t,this.publicationDeferralDepth--,this.publicationDeferralDepth>0))return;let n=this.deferredPublications;if(this.deferredPublications=[],this.discardDeferredPublications){this.discardDeferredPublications=!1;return}this.publishEvents(n.flatMap(({changes:e})=>e),n.some(({layoutChanged:e})=>e))};return{publish:()=>t(!1),discard:()=>t(!0)}}publishEvents(e,t){if(e.length===0&&!t)return;let n=e.map(e=>this.enrichChangeWithVirtualProps(e));Co(()=>{if(e.length===0)for(let e of this.layoutChangeListeners)e();for(let e of this.changeSubscriptions)e.emitEvents(n)})}subscribeLayoutChanges(e){return this.layoutChangeListeners.add(e),()=>this.layoutChangeListeners.delete(e)}subscribeChanges(e,t={}){if(t.where&&t.whereExpression)throw Error(`Cannot specify both 'where' and 'whereExpression' options. Use one or the other.`);let{where:n,...r}=t,i=r.whereExpression;n&&(i=G(n(wo()))),this.addSubscriber();let a;try{a=new Vo(this.collection,e,{...r,whereExpression:i,onUnsubscribe:()=>{this.removeSubscriber(),a&&this.changeSubscriptions.delete(a)}}),t.onStatusChange&&a.on(`status:change`,t.onStatusChange),t.includeInitialState?a.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetResult:t.onLoadSubsetResult}):t.includeInitialState===!1&&a.markAllStateAsSeen(),this.changeSubscriptions.add(a)}catch(e){if(a)try{a.unsubscribe()}catch{}else this.removeSubscriber();throw e}return a}addSubscriber(){let e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer();try{(this.lifecycle.status===`cleaned-up`||this.lifecycle.status===`idle`)&&this.sync.startSync()}catch(t){throw this.activeSubscribersCount=e,this.activeSubscribersCount===0&&this.lifecycle.startGCTimer(),t}this.events.emitSubscribersChange(this.activeSubscribersCount,e)}removeSubscriber(){let e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new Ye;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1,this.deferredPublications=[],this.publicationDeferralDepth=0}},Uo=e=>setTimeout(()=>{e({didTimeout:!0,timeRemaining:()=>50})},0),Wo=e=>{clearTimeout(e)},Go=typeof window<`u`&&`requestIdleCallback`in window?(e,t)=>window.requestIdleCallback(e,t):(e,t)=>Uo(e),Ko=typeof window<`u`&&`cancelIdleCallback`in window?e=>window.cancelIdleCallback(e):Wo,qo=class e{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return e.instance||=new e,e.instance}schedule(e,t,n){let r=Date.now()+t;this.tasks.set(e,{executeAt:r,callback:n}),this.microtaskScheduled||(this.microtaskScheduled=!0,Promise.resolve().then(()=>{this.microtaskScheduled=!1,this.updateTimeout()}))}cancel(e){this.tasks.delete(e)}updateTimeout(){if(this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.tasks.size===0)return;let e=1/0;for(let t of this.tasks.values())t.executeAt<e&&(e=t.executeAt);let t=Math.max(0,e-Date.now());this.timeoutId=setTimeout(()=>this.process(),t)}process(){this.timeoutId=null;let e=Date.now();for(let[t,n]of this.tasks.entries())if(e>=n.executeAt){this.tasks.delete(t);try{n.callback()}catch(e){console.error(`Error in CleanupQueue task:`,e)}}this.tasks.size>0&&this.updateTimeout()}static resetInstance(){e.instance&&=(e.instance.timeoutId!==null&&clearTimeout(e.instance.timeoutId),null)}};qo.instance=null;var Jo=qo,Yo=class{constructor(e,t){this.status=`idle`,this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.config=e,this.id=t}setDeps(e){this.indexes=e.indexes,this.events=e.events,this.changes=e.changes,this.sync=e.sync,this.state=e.state}validateStatusTransition(e,t){if(e!==t&&!{idle:[`loading`,`error`,`cleaned-up`],loading:[`ready`,`error`,`cleaned-up`],ready:[`cleaned-up`,`error`],error:[`ready`,`cleaned-up`,`idle`],"cleaned-up":[`loading`,`error`]}[e].includes(t))throw new qe(e,t,this.id)}setStatus(e,t=!1){if(e===`ready`&&!t)throw new Ge(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);let n=this.status;this.status=e,this.events.emitStatusChange(e,n)}validateCollectionUsable(e){switch(this.status){case`error`:throw new Ke(e,this.id);case`cleaned-up`:this.sync.startSync()}}markReady(){if(this.validateStatusTransition(this.status,`ready`),this.status===`loading`||this.status===`error`){if(this.syncError=void 0,this.setStatus(`ready`,!0),!this.hasBeenReady){this.hasBeenReady=!0,this.hasReceivedFirstCommit||=!0;let e=[...this.onFirstReadyCallbacks];this.onFirstReadyCallbacks=[],e.forEach(e=>e())}this.changes.changeSubscriptions.size>0&&this.changes.emitEmptyReadyEvent()}}markError(e){this.validateStatusTransition(this.status,`error`),this.syncError=e,this.setStatus(`error`)}getSyncError(){return this.syncError}startGCTimer(){let e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||Jo.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Jo.getInstance().cancel(this),this.idleCallbackId!==null&&(Ko(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Ko(this.idleCallbackId),this.idleCallbackId=Go(e=>{this.changes.activeSubscribersCount===0?this.performCleanup(e)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(e){if(!e||e.timeRemaining()>0||e.didTimeout){this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),Jo.getInstance().cancel(this),this.hasBeenReady=!1,this.syncError=void 0;let e=[...this.onFirstReadyCallbacks];return this.onFirstReadyCallbacks=[],e.forEach(e=>{try{e()}catch(e){console.error(`${this.config.id?`[${this.config.id}] `:``}Error in onFirstReady callback during cleanup:`,e)}}),this.setStatus(`cleaned-up`),this.changes.activeSubscribersCount===0&&this.events.cleanup(),!0}return this.scheduleIdleCleanup(),!1}onFirstReady(e){return this.hasBeenReady?(e(),()=>{}):(this.onFirstReadyCallbacks.push(e),()=>{let t=this.onFirstReadyCallbacks.indexOf(e);t!==-1&&this.onFirstReadyCallbacks.splice(t,1)})}cleanup(){this.idleCallbackId!==null&&(Ko(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}};function Xo(){let e,t,n=!0;return{promise:new Promise((r,i)=>{e=e=>{n=!1,r(e)},t=e=>{n=!1,i(e)}}),resolve:e,reject:t,isPending:()=>n}}var Zo=Symbol(`liveQueryInternal`),Qo=class{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.loadSubsetOperations=new Set,this.syncStartDeferred=!1,this.syncStartRequested=!1,this.deferredLoadSubsets=[],this.syncEpoch=0,this.loadSubsetSession=0,this.config=e,this.id=t,this.syncMode=e.syncMode??`eager`}setDeps(e){this.collection=e.collection,this.state=e.state,this.lifecycle=e.lifecycle,this._events=e.events}markLayoutChange(){this.getActivePendingSyncTransaction().layoutChanged=!0}startSync(){if(this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`)return;if(this.syncStartDeferred){this.syncStartRequested=!0;return}let e=++this.syncEpoch,t=()=>e===this.syncEpoch;this.lifecycle.setStatus(`loading`);try{let e=$o(this.config.sync.sync({collection:this.collection,begin:e=>{if(!t())return;let n=Xo();n.promise.catch(()=>void 0),this.state.pendingSyncedTransactions.push({committed:!1,applicationStarted:!1,layoutChanged:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:e?.immediate,applied:n})},write:e=>{if(!t())return;let n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!n)throw new _t;if(n.committed)throw new vt;let r;r=`key`in e?e.key:this.config.getKey(e.value),this.state.pendingLocalChanges.has(r)&&this.state.pendingLocalOrigins.add(r);let i=e.type;if(e.type===`insert`){let t=this.state.syncedData.has(r),a=n.deletedKeys.has(r),o=n.truncate===!0;if(t&&!a&&!o){let t=this.state.syncedData.get(r);if(t!==void 0&&B(t,e.value)||this.state.hydrationSeedKeys.has(r))i=`update`;else{let e=this.config.utils?.[Zo];throw new tt(r,this.id,{hasCustomGetKey:e?.hasCustomGetKey??!1,hasJoins:e?.hasJoins??!1,hasDistinct:e?.hasDistinct??!1})}}}let a={...e,type:i,key:r};n.operations.push(a),i===`delete`?(n.deletedKeys.add(r),n.rowMetadataWrites.set(r,{type:`delete`})):i===`insert`?a.metadata===void 0?n.rowMetadataWrites.set(r,{type:`delete`}):n.rowMetadataWrites.set(r,{type:`set`,value:a.metadata}):a.metadata!==void 0&&n.rowMetadataWrites.set(r,{type:`set`,value:a.metadata})},commit:e=>{if(!t())return!0;let n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!n)throw new yt;if(n.committed)throw new bt;if(e?.aborted)return this.state.cancelPendingSyncedTransaction(n),n.applied.promise;n.committed=!0;let r=()=>{this.state.cancelPendingSyncedTransaction(n)};if(e?.addEventListener(`abort`,r,{once:!0}),this.state.commitPendingTransactions(),!n.applied.isPending())return e?.removeEventListener(`abort`,r),!0;let i=n.applied.promise;if(e){let t=()=>{e.removeEventListener(`abort`,r)};i.then(t,t)}return i},markReady:()=>{t()&&this.lifecycle.markReady()},markError:e=>{t()&&this.lifecycle.markError(e)},truncate:()=>{if(!t())return;let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new _t;if(e.committed)throw new vt;e.operations=[],e.deletedKeys.clear(),e.rowMetadataWrites.clear(),e.truncate=!0,e.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi(t)}));if(this.syncCleanupFn=e?.cleanup??null,this.syncLoadSubsetFn=e?.loadSubset??null,this.syncUnloadSubsetFn=e?.unloadSubset??null,this.syncMode===`on-demand`&&!this.syncLoadSubsetFn)throw new Be(`Collection "${this.id}" is configured with syncMode "on-demand" but the sync function did not return a loadSubset handler. Either provide a loadSubset handler or use syncMode "eager".`)}catch(e){throw this.lifecycle.markError(e),e}}deferStart(){return this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`?!1:(this.syncStartDeferred=!0,!0)}resumeStart(){if(!this.syncStartDeferred)return;this.syncStartDeferred=!1;let e=this.syncStartRequested||this.deferredLoadSubsets.length>0;this.syncStartRequested=!1;let t=this.deferredLoadSubsets;this.deferredLoadSubsets=[];try{e&&this.startSync()}catch(e){for(let{deferred:n}of t)n.reject(e);throw e}for(let{options:e,deferred:n}of t)try{let t=this.syncLoadSubsetFn?.(e)??!0;t instanceof Promise?t.then(()=>n.resolve(void 0),e=>n.reject(e)):n.resolve(void 0)}catch(e){n.reject(e)}}getActivePendingSyncTransaction(){let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new _t;if(e.committed)throw new vt;return e}createSyncMetadataApi(e){return{row:{get:t=>{if(!e())return;let n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],r=n?.rowMetadataWrites.get(t);if(r)return r.type===`delete`?void 0:r.value;if(!n?.truncate)return this.state.syncedMetadata.get(t)},set:(t,n)=>{e()&&this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:`set`,value:n})},delete:t=>{e()&&this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:`delete`})}},collection:{get:t=>{if(!e())return;let n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(t);return n?n.type===`delete`?void 0:n.value:this.state.syncedCollectionMetadata.get(t)},set:(t,n)=>{e()&&this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:`set`,value:n})},delete:t=>{e()&&this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:`delete`})},list:t=>{if(!e())return[];let n=new Map(this.state.syncedCollectionMetadata),r=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(r)for(let[e,t]of r.collectionMetadataWrites)t.type===`delete`?n.delete(e):n.set(e,t.value);return Array.from(n.entries()).filter(([e])=>!t||e.startsWith(t)).map(([e,t])=>({key:e,value:t}))}}}}preload(){if(this.preloadPromise)return this.preloadPromise;this.syncMode===`on-demand`&&console.warn(`${this.id?`[${this.id}] `:``}Calling .preload() on a collection with syncMode "on-demand" is a no-op. In on-demand mode, data is only loaded when queries request it. Instead, create a live query and call .preload() on that to load the specific data you need. See https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync for more details.`);let e=new Promise((e,t)=>{if(this.lifecycle.status===`ready`){e();return}if(this.lifecycle.status===`error`){t(this.getPreloadError());return}let n=!1,r=!1,i=()=>{},a=()=>{},o=()=>{n||(n=!0,i(),a(),e())},s=e=>{n||(n=!0,i(),a(),t(e))};if(a=this.lifecycle.onFirstReady(o),i=this.collection.on(`status:error`,()=>{r||s(this.getPreloadError())}),this.lifecycle.status===`idle`||this.lifecycle.status===`cleaned-up`){r=!0;try{this.startSync()}catch(e){s(e);return}finally{r=!1}this.collection.status===`error`&&s(this.getPreloadError())}});return this.preloadPromise=e,e.then(void 0,()=>{this.preloadPromise===e&&(this.preloadPromise=null)}),e}getPreloadError(){let e=this.lifecycle.getSyncError();return e===void 0?new Je:e}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}waitForCurrentLoadSubset(){return this.pendingLoadSubsetPromises.size===0||this.waitForPendingLoadSubset()}beginLoadSubsetOperation(){let e={pending:new Set,waiting:!1,completed:!1,hasError:!1};return this.activeLoadSubsetOperation=e,this.loadSubsetOperations.add(e),{wait:()=>this.waitForLoadSubsetOperation(e),cancel:()=>{e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0)}}}waitForLoadSubsetOperation(e){return e.waiting=!0,e.pending.size===0?(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),!e.hasError||Promise.reject(e.error)):(e.deferred=Xo(),e.deferred.promise)}settleLoadSubsetOperation(e,t,n){e.completed||(e.pending.delete(t),!n.ok&&!e.hasError&&(e.hasError=!0,e.error=n.error),!(!e.waiting||e.pending.size>0)&&queueMicrotask(()=>{e.completed||e.pending.size>0||(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),e.hasError?e.deferred.reject(e.error):e.deferred.resolve())}))}trackLoadSubsetOperationPromise(e){let t=this.activeLoadSubsetOperation;!t||t.pending.has(e)||(t.pending.add(e),e.then(()=>this.settleLoadSubsetOperation(t,e,{ok:!0}),n=>this.settleLoadSubsetOperation(t,e,{ok:!1,error:n})))}async waitForPendingLoadSubset(){do await Promise.all([...this.pendingLoadSubsetPromises]);while(this.pendingLoadSubsetPromises.size>0)}trackLoadPromise(e){let t=this.loadSubsetSession,n=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),this.trackLoadSubsetOperationPromise(e),n&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:`start`});let r=()=>{if(t!==this.loadSubsetSession)return;let n=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),n&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:`end`})};e.then(r,r)}loadSubset(e){if(e.signal?.aborted||this.syncMode===`eager`)return!0;if(this.syncStartDeferred){this.syncStartRequested=!0;let t=Xo();return this.deferredLoadSubsets.push({options:e,deferred:t}),this.trackLoadPromise(t.promise),t.promise}if(this.syncLoadSubsetFn){let t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){if(this.syncStartDeferred){this.deferredLoadSubsets=this.deferredLoadSubsets.filter(t=>t.options!==e||(t.deferred.resolve(void 0),!1));return}this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}cleanup(){this.syncEpoch++,this.loadSubsetSession++;try{this.syncCleanupFn&&=(this.syncCleanupFn(),null)}catch(e){queueMicrotask(()=>{if(e instanceof Error){let t=new rn(this.id,e);throw t.cause=e,t.stack=e.stack,t}throw new rn(this.id,e)})}this.preloadPromise=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.syncStartDeferred=!1,this.syncStartRequested=!1;let e=this.pendingLoadSubsetPromises.size>0;this.pendingLoadSubsetPromises.clear(),e&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:`end`}),this.activeLoadSubsetOperation=void 0;for(let e of this.loadSubsetOperations)e.completed||(e.completed=!0,e.pending.clear(),e.deferred?.resolve());this.loadSubsetOperations.clear();let t=this.deferredLoadSubsets;this.deferredLoadSubsets=[];for(let{deferred:e}of t)e.resolve(void 0)}};function $o(e){if(typeof e==`function`)return{cleanup:e};if(typeof e==`object`)return e}var es=1;function ts(e,t){return e===t?0:e<t?-1:1}function ns(e){return{kind:`constructor`,...e.name?{name:e.name}:{}}}function rs(e){if(e==null)return e;switch(typeof e){case`string`:case`boolean`:return e;case`number`:return Number.isFinite(e)?e:null;case`bigint`:return{__type:`bigint`,value:e.toString()};case`function`:case`symbol`:return;case`undefined`:return}if(Array.isArray(e))return e.map(e=>rs(e)??null);if(e instanceof Date)return{__type:`date`,value:e.toISOString()};if(e instanceof Set)return{__type:`set`,values:Array.from(e).map(e=>rs(e)??null).sort((e,t)=>ts(is(e),is(t)))};if(e instanceof Map)return{__type:`map`,entries:Array.from(e.entries()).map(([e,t])=>({key:rs(e)??null,value:rs(t)??null})).sort((e,t)=>ts(is(e.key),is(t.key)))};if(e instanceof RegExp)return{__type:`regexp`,value:e.toString()};let t={},n=Object.entries(e).sort(([e],[t])=>ts(e,t));for(let[e,r]of n){let n=rs(r);n!==void 0&&(t[e]=n)}return t}function is(e){return e===null?`null`:Array.isArray(e)?`[${e.map(is).join(`,`)}]`:typeof e==`object`?`{${Object.keys(e).sort((e,t)=>ts(e,t)).map(t=>`${JSON.stringify(t)}:${is(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function as(e,t,n,r,i){let a=ns(r),o=rs(t)??null,s=rs(i);return{signatureVersion:es,signature:is(rs({signatureVersion:es,expression:o,options:s??null})??null),indexId:e,name:n,expression:t,resolver:a,...s===void 0?{}:{options:s}}}function os(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>os(e));let t={};for(let[n,r]of Object.entries(e))t[n]=os(r);return t}function ss(e){return JSON.parse(JSON.stringify(e))}var cs=class{constructor(){this.indexes=new Map,this.indexMetadata=new Map,this.indexCounter=0}setDeps(e){this.state=e.state,this.lifecycle=e.lifecycle,this.defaultIndexType=e.defaultIndexType,this.events=e.events}createIndex(e,t={}){this.lifecycle.validateCollectionUsable(`createIndex`);let n=++this.indexCounter,r=G(e(wo())),i=t.indexType??this.defaultIndexType;if(!i)throw new Be(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection:
11
+ import { BasicIndex } from '@tanstack/db'
12
+ createCollection({ defaultIndexType: BasicIndex, ... })`);let a=new i(n,r,t.name,t.options);a.build(this.state.entries()),this.indexes.set(n,a);let o=as(n,r,t.name,i,t.options);return this.indexMetadata.set(n,o),this.events.emitIndexAdded(o),a}removeIndex(e){this.lifecycle.validateCollectionUsable(`removeIndex`);let t=typeof e==`number`?e:e.id,n=this.indexes.get(t);if(!n||typeof e!=`number`&&n!==e)return!1;this.indexes.delete(t);let r=this.indexMetadata.get(t);return this.indexMetadata.delete(t),r&&this.events.emitIndexRemoved(r),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,t)=>e.indexId-t.indexId).map(e=>({...e,expression:ss(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:os(e.options)}}))}updateIndexes(e){for(let t of this.indexes.values())for(let n of e)switch(n.type){case`insert`:t.add(n.key,n.value);break;case`update`:n.previousValue?t.update(n.key,n.previousValue,n.value):t.add(n.key,n.value);break;case`delete`:t.remove(n.key,n.value)}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}},ls=new Set([`find`,`findLast`,`findIndex`,`findLastIndex`,`filter`,`map`,`flatMap`,`forEach`,`some`,`every`,`reduce`,`reduceRight`]),us=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]),ds=new Set([`set`,`delete`,`clear`,`add`]),fs=new Set([`entries`,`keys`,`values`,`forEach`]);function ps(e){return typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof RegExp)&&!fn(e)}function ms(e,t,n,r){if(ls.has(e))return function(...i){let a=i[0];if(typeof a!=`function`)return t.apply(n.copy_,i);let o=(e,t)=>{if(ps(e)){let{proxy:i}=r(e,{tracker:n,prop:String(t)});return i}return e},s=function(e,t,n){let r=o(e,t);return a.call(this,r,t,n)};if(e===`reduce`||e===`reduceRight`)return t.apply(n.copy_,[function(e,t,n,r){let i=o(t,n);return a.call(this,e,i,n,r)},...i.slice(1)]);let c=t.apply(n.copy_,[s,...i.slice(1)]);if((e===`find`||e===`findLast`)&&c&&typeof c==`object`){let e=n.copy_.indexOf(c);if(e!==-1)return o(c,e)}return e===`filter`&&Array.isArray(c)?c.map(e=>{let t=n.copy_.indexOf(e);return t===-1?e:o(e,t)}):c}}function hs(e,t){return function(){let n=e.copy_,r=0;return{next(){if(r>=n.length)return{done:!0,value:void 0};let i=n[r],a=i;if(ps(i)){let{proxy:n}=t(i,{tracker:e,prop:String(r)});a=n}return r++,{done:!1,value:a}},[Symbol.iterator](){return this}}}}function gs(e,t,n){return function(...r){let i=e.apply(t.copy_,r);return n(t),i}}function _s(e,t,n,r,i,a,o){if(fs.has(e)||t===Symbol.iterator)return function(...s){let c=n.apply(i.copy_,s);if(e===`forEach`){let e=s[0];if(typeof e==`function`)return n.apply(r,[function(t,n,r){let a=e.call(this,t,n,r);return o(i),a},...s.slice(1)])}if(e===`entries`||e===`values`||e===Symbol.iterator.toString()||t===Symbol.iterator){let n=c,o=new Map;if(e===`values`&&r instanceof Map)for(let[e,t]of i.copy_.entries())o.set(t,e);let s=new Map;if(r instanceof Set)for(let e of i.copy_.values())s.set(e,e);return{next(){let c=n.next();if(!c.done&&c.value&&typeof c.value==`object`){if(e===`entries`&&Array.isArray(c.value)&&c.value.length===2){if(c.value[1]&&typeof c.value[1]==`object`){let e=c.value[0],t={tracker:i,prop:e,updateMap:t=>{i.copy_ instanceof Map&&i.copy_.set(e,t)}},{proxy:n}=a(c.value[1],t);c.value[1]=n}}else if(e===`values`||e===Symbol.iterator.toString()||t===Symbol.iterator){if(e===`values`&&r instanceof Map){let e=o.get(c.value);if(e!==void 0){let t={tracker:i,prop:e,updateMap:t=>{i.copy_ instanceof Map&&i.copy_.set(e,t)}},{proxy:n}=a(c.value,t);c.value=n}}else if(r instanceof Set){let e=c.value,t={tracker:i,prop:e,updateSet:t=>{i.copy_ instanceof Set&&(i.copy_.delete(e),i.copy_.add(t),s.set(e,t))}},{proxy:n}=a(c.value,t);c.value=n}else{let e=Symbol(`iterator-value`),{proxy:t}=a(c.value,{tracker:i,prop:e});c.value=t}}}return c},[Symbol.iterator](){return this}}}return c}}function K(...e){let t=typeof window<`u`&&typeof localStorage<`u`;(t&&localStorage.getItem(`DEBUG`)===`true`||!t&&typeof process<`u`&&{}.DEBUG===`true`)&&console.log(`[proxy]`,...e)}function vs(e,t=new WeakMap){if(typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(Array.isArray(e)){let n=[];return t.set(e,n),e.forEach((e,r)=>{n[r]=vs(e,t)}),n}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)){let n=Object.getPrototypeOf(e).constructor,r=new n(e.length);t.set(e,r);for(let t=0;t<e.length;t++)r[t]=e[t];return r}if(e instanceof Map){let n=new Map;return t.set(e,n),e.forEach((e,r)=>{n.set(r,vs(e,t))}),n}if(e instanceof Set){let n=new Set;return t.set(e,n),e.forEach(e=>{n.add(vs(e,t))}),n}if(fn(e))return e;let n={};t.set(e,n);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=vs(e[r],t));let r=Object.getOwnPropertySymbols(e);for(let i of r)n[i]=vs(e[i],t);return n}var ys=0;function bs(){return ys+=1,ys}function xs(e,t){let n=new Map;function r(e,t){if(K(`Object ID:`,e.constructor.name),n.has(e))return n.get(e);{let r=xs(e,t);return n.set(e,r),r}}let i=new Map,a={copy_:vs(e),originalObject:vs(e),proxyCount:bs(),modified:!1,assigned_:{},parent:t,target:e};K(`createChangeProxy called for target`,e,a.proxyCount);function o(e){e.modified||=!0,e.parent&&(K(`propagating change to parent`),`updateMap`in e.parent?e.parent.updateMap(e.copy_):`updateSet`in e.parent?e.parent.updateSet(e.copy_):(e.parent.tracker.copy_[e.parent.prop]=e.copy_,e.parent.tracker.assigned_[e.parent.prop]=!0),o(e.parent.tracker))}function s(e){if(K(`checkIfReverted called with assigned keys:`,Object.keys(e.assigned_)),Object.keys(e.assigned_).length===0&&Object.getOwnPropertySymbols(e.assigned_).length===0)return K(`No assigned properties, returning true`),!0;for(let t in e.assigned_)if(e.assigned_[t]===!0){let n=e.copy_[t],r=e.originalObject[t];if(K(`Checking property ${String(t)}, current:`,n,`original:`,r),!B(n,r))return K(`Property ${String(t)} is different, returning false`),!1}else if(e.assigned_[t]===!1)return K(`Property ${String(t)} was deleted, returning false`),!1;let t=Object.getOwnPropertySymbols(e.assigned_);for(let n of t)if(e.assigned_[n]===!0){let t=e.copy_[n],r=e.originalObject[n];if(!B(t,r))return K(`Symbol property is different, returning false`),!1}else if(e.assigned_[n]===!1)return K(`Symbol property was deleted, returning false`),!1;return K(`All properties match original values, returning true`),!0}function c(e,t){K(`checkParentStatus called for child prop:`,t);let n=s(e);K(`Parent checkIfReverted returned:`,n),n&&(K(`Parent is fully reverted, clearing tracking`),e.modified=!1,e.assigned_={},e.parent&&(K(`Continuing up the parent chain`),c(e.parent.tracker,e.parent.prop)))}function l(e){if(K(`createObjectProxy`,e),i.has(e))return K(`proxyCache found match`),i.get(e);let n=new Proxy(e,{get(e,t){K(`get`,e,t);let n=a.copy_[t]??a.originalObject[t],s=a.originalObject[t];if(K(`value (at top of proxy get)`,n),Object.getOwnPropertyDescriptor(e,t)?.get)return n;if(typeof n==`function`){if(Array.isArray(e)){let e=t.toString();if(us.has(e))return gs(n,a,o);let i=ms(e,n,a,r);if(i)return i;if(t===Symbol.iterator)return hs(a,r)}if(e instanceof Map||e instanceof Set){let i=t.toString();if(ds.has(i))return gs(n,a,o);let s=_s(i,t,n,e,a,r,o);if(s)return s}return n.bind(e)}if(ps(n)){let{proxy:e}=r(s,{tracker:a,prop:String(t)});return i.set(n,e),e}return n},set(e,n,r){let i=a.copy_[n];if(K(`set called for property ${String(n)}, current:`,i,`new:`,r),B(i,r))K(`Value unchanged, not tracking`);else{let e=a.originalObject[n],i=B(r,e);if(K(`value:`,r,`original:`,e,`isRevertToOriginal:`,i),i){K(`Reverting property ${String(n)} to original value`),delete a.assigned_[n.toString()],K(`Updating copy with original value for ${String(n)}`),a.copy_[n]=vs(e),K(`Checking if all properties reverted`);let r=s(a);K(`All reverted:`,r),r?(K(`All properties reverted, clearing tracking`),a.modified=!1,a.assigned_={},t&&(K(`Updating parent for property:`,t.prop),c(t.tracker,t.prop))):(K(`Some properties still changed, keeping modified flag`),a.modified=!0)}else K(`Setting new value for property ${String(n)}`),a.copy_[n]=r,a.assigned_[n.toString()]=!0,K(`Marking object and ancestors as modified`,a),o(a)}return!0},defineProperty(e,t,n){let r=Reflect.defineProperty(e,t,n);return r&&`value`in n&&(a.copy_[t]=vs(n.value),a.assigned_[t.toString()]=!0,o(a)),r},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(e,t)},preventExtensions(e){return Reflect.preventExtensions(e)},isExtensible(e){return Reflect.isExtensible(e)},deleteProperty(e,t){K(`deleteProperty`,e,t);let n=typeof t==`symbol`?t.toString():t;if(n in e){let r=n in a.originalObject,i=Reflect.deleteProperty(e,t);return i&&(r?(a.assigned_[n]=!1,o(a)):(delete a.assigned_[n],Object.keys(a.assigned_).length===0&&Object.getOwnPropertySymbols(a.assigned_).length===0?a.modified=!1:a.modified=!0)),i}return!0}});return i.set(e,n),n}return{proxy:l(a.copy_),getChanges:()=>{if(K(`getChanges called, modified:`,a.modified),K(a),!a.modified)return K(`Object not modified, returning empty object`),{};if(typeof a.copy_!=`object`||Array.isArray(a.copy_)||Object.keys(a.assigned_).length===0)return a.copy_;let e={};for(let t in a.copy_)a.assigned_[t]===!0&&t in a.copy_&&(e[t]=a.copy_[t]);return K(`Returning copy:`,e),e}}}function Ss(e){let t=e.map(e=>xs(e));return{proxies:t.map(e=>e.proxy),getChanges:()=>t.map(e=>e.getChanges())}}function Cs(e,t){let{proxy:n,getChanges:r}=xs(e);return t(n),r()}function ws(e,t){let{proxies:n,getChanges:r}=Ss(e);return t(n),r()}var Ts=new class{constructor(){this.transactions=[],this.transactionStack=[],this.sequenceNumber=0}createTransaction(e){let t=new Ns(e,this,this.sequenceNumber++);return this.transactions.push(t),t}getActiveTransaction(){return this.transactionStack.at(-1)}getActiveTransactionForCollection(){let e=this.getActiveTransaction();if(e)return e;if(this!==Ts)return Ts.claimActiveTransaction(this)}claimActiveTransaction(e){let t=this.getActiveTransaction();if(!t)return;let n=Os(t);if(n===e)return t;if(n!==this)throw Error(`A transaction created with createTransaction() cannot mutate collections from multiple DbClient instances. Use dbClient.createTransaction() for explicit client scope.`);return this.removeTransaction(t),e.transactions.push(t),e.transactionStack.push(t),t.sequenceNumber=e.sequenceNumber++,Es.set(t,e),t}registerTransaction(e){bo.clear(e.id),this.transactionStack.push(e)}unregisterTransaction(e){try{bo.flush(e.id)}finally{this.transactionStack=this.transactionStack.filter(t=>t.id!==e.id)}}removeTransaction(e){let t=this.transactions.findIndex(t=>t.id===e.id);t!==-1&&this.transactions.splice(t,1)}rollbackConflictingTransactions(e,t){for(let n of[...this.transactions])n!==e&&n.state===`pending`&&n.mutations.some(e=>t.has(e.globalKey))&&n.rollback({isSecondaryRollback:!0})}clear(){let e=new Set([...this.transactions.map(e=>e.id),...this.transactionStack.map(e=>e.id)]);for(let t of e)bo.clear(t);this.transactions=[],this.transactionStack=[]}},Es=new WeakMap,Ds=new WeakMap;function Os(e){let t=Es.get(e);if(!t)throw Error(`Transaction is not associated with a TransactionScope.`);return t}function ks(e){let t=Ds.get(e);if(!t)throw Error(`Transaction is not associated with an ambient scope.`);return t}function As(e,t){switch(`${e.type}-${t.type}`){case`insert-update`:return{...e,type:`insert`,original:{},modified:t.modified,changes:{...e.changes,...t.changes},key:e.key,globalKey:e.globalKey,metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata},mutationId:t.mutationId,updatedAt:t.updatedAt};case`insert-delete`:return null;case`update-delete`:return t;case`update-update`:return{...t,original:e.original,changes:{...e.changes,...t.changes},metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata}};case`delete-delete`:case`insert-insert`:return t;default:{let n=`${e.type}-${t.type}`;throw Error(`Unhandled mutation combination: ${n}`)}}}function js(e){return Ts.createTransaction(e)}function Ms(){return Ts.getActiveTransaction()}var Ns=class{constructor(e,t,n){if(e.mutationFn===void 0)throw new pt;this.id=e.id??Le(),this.mutationFn=e.mutationFn,this.state=`pending`,this.mutations=[],this.isPersisted=Xo(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=n,this.metadata=e.metadata??{},Es.set(this,t),Ds.set(this,t)}setState(e){this.state=e,(e===`completed`||e===`failed`)&&Os(this).removeTransaction(this)}mutate(e){if(this.state!==`pending`)throw new mt;let t=Os(this),n=new Set([t,ks(this)]);for(let e of n)e.registerTransaction(this);try{e()}finally{n.add(Os(this));for(let e of n)e.unregisterTransaction(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){let t=new Map;for(let e of this.mutations)t.set(e.globalKey,e);for(let n of e){let e=t.get(n.globalKey);if(e){let r=As(e,n);r===null?t.delete(n.globalKey):t.set(n.globalKey,r)}else t.set(n.globalKey,n)}this.mutations.length=0;for(let e of t.values())this.mutations.push(e)}rollback(e){let t=e?.isSecondaryRollback??!1;if(this.state===`completed`)throw new ht;if(this.setState(`failed`),!t){let e=new Set(this.mutations.map(e=>e.globalKey));Os(this).rollbackConflictingTransactions(this,e)}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){let e=new Set;for(let t of this.mutations)e.has(t.collection.id)||(t.collection._state.onTransactionStateChange(),t.collection._state.pendingSyncedTransactions.length>0&&t.collection._state.commitPendingTransactions(),e.add(t.collection.id))}async commit(){if(this.state!==`pending`)throw new gt;if(this.setState(`persisting`),this.mutations.length===0)return this.setState(`completed`),this.isPersisted.resolve(this),this;try{await this.mutationFn({transaction:this}),this.setState(`completed`),this.touchCollection(),this.isPersisted.resolve(this)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.error={message:t.message,error:t},this.rollback(),t}return this}compareCreatedAt(e){let t=this.createdAt.getTime()-e.createdAt.getTime();return t===0?this.sequenceNumber-e.sequenceNumber:t}},Ps=class{constructor(e,t){this.insert=(e,t)=>{this.lifecycle.validateCollectionUsable(`insert`);let n=this.state,r=this.getActiveTransaction();if(!r&&!this.config.onInsert)throw new lt;let i=Array.isArray(e)?e:[e],a=[],o=new Set;if(i.forEach(e=>{let n=this.validateData(e,`insert`),r=this.config.getKey(n);if(this.state.has(r)||o.has(r))throw new et(r);o.add(r);let i=this.generateGlobalKey(r,e),s={mutationId:Le(),original:{},modified:n,changes:Object.fromEntries(Object.keys(e).map(e=>[e,n[e]])),globalKey:i,key:r,metadata:t?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:t?.optimistic??!0,type:`insert`,createdAt:new Date,updatedAt:new Date,collection:this.collection};a.push(s)}),r)return r.applyMutations(a),n.transactions.set(r.id,r),n.scheduleTransactionCleanup(r),n.recomputeOptimisticState(!0),r;{let e=this.createTransaction({metadata:{[_o]:!0},mutationFn:async e=>await this.config.onInsert({transaction:e.transaction,collection:this.collection})});return e.applyMutations(a),this.markPendingLocalOrigins(a),e.commit().catch(()=>void 0),n.transactions.set(e.id,e),n.scheduleTransactionCleanup(e),n.recomputeOptimisticState(!0),e}},this.delete=(e,t)=>{let n=this.state;this.lifecycle.validateCollectionUsable(`delete`);let r=this.getActiveTransaction();if(!r&&!this.config.onDelete)throw new dt;if(Array.isArray(e)&&e.length===0)throw new ot;let i=Array.isArray(e)?e:[e],a=[];for(let e of i){if(!this.state.has(e))throw new st(e);let r=this.generateGlobalKey(e,this.state.get(e)),i={mutationId:Le(),original:this.state.get(e),modified:this.state.get(e),changes:this.state.get(e),globalKey:r,key:e,metadata:t?.metadata,syncMetadata:n.syncedMetadata.get(e)||{},optimistic:t?.optimistic??!0,type:`delete`,createdAt:new Date,updatedAt:new Date,collection:this.collection};a.push(i)}if(r)return r.applyMutations(a),n.transactions.set(r.id,r),n.scheduleTransactionCleanup(r),n.recomputeOptimisticState(!0),r;let o=this.createTransaction({autoCommit:!0,metadata:{[_o]:!0},mutationFn:async e=>this.config.onDelete({transaction:e.transaction,collection:this.collection})});return o.applyMutations(a),this.markPendingLocalOrigins(a),o.commit().catch(()=>void 0),n.transactions.set(o.id,o),n.scheduleTransactionCleanup(o),n.recomputeOptimisticState(!0),o},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}setTransactionScope(e){this.transactionScope=e}getActiveTransaction(){return this.transactionScope?this.transactionScope.getActiveTransactionForCollection():Ms()}createTransaction(e){return this.transactionScope?this.transactionScope.createTransaction(e):js(e)}ensureStandardSchema(e){if(e&&`~standard`in e)return e;throw new Ue}validateData(e,t,n){if(!this.config.schema)return e;let r=this.ensureStandardSchema(this.config.schema);if(t===`update`&&n){let i=this.state.get(n);if(i&&e&&typeof e==`object`&&typeof i==`object`){let n=Object.assign({},i,e),a=r[`~standard`].validate(n);if(a instanceof Promise)throw new We;if(`issues`in a&&a.issues)throw new ze(t,a.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));let o=a.value,s=Object.keys(e);return Object.fromEntries(s.map(e=>[e,o[e]]))}}let i=r[`~standard`].validate(e);if(i instanceof Promise)throw new We;if(`issues`in i&&i.issues)throw new ze(t,i.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));return i.value}generateGlobalKey(e,t){if(typeof e!=`string`&&typeof e!=`number`)throw e===void 0?new Qe(t):new $e(e,t);return`KEY::${this.id}/${e}`}markPendingLocalOrigins(e){for(let t of e)this.state.pendingLocalOrigins.add(t.key)}update(e,t,n){if(e===void 0)throw new nt;let r=this.state;this.lifecycle.validateCollectionUsable(`update`);let i=this.getActiveTransaction();if(!i&&!this.config.onUpdate)throw new ut;let a=Array.isArray(e),o=a?e:[e];if(a&&o.length===0)throw new rt;let s=typeof t==`function`?t:n,c=typeof t==`function`?{}:t,l=o.map(e=>{let t=this.state.get(e);if(!t)throw new it(e);return t}),u;u=a?ws(l,s):[Cs(l[0],s)];let d=o.map((e,t)=>{let n=u[t];if(!n||Object.keys(n).length===0)return null;let i=l[t],a=this.validateData(n,`update`,e),o=Object.assign({},i,a),s=this.config.getKey(i),d=this.config.getKey(o);if(s!==d)throw new at(s,d);let f=this.generateGlobalKey(d,o);return{mutationId:Le(),original:i,modified:o,changes:Object.fromEntries(Object.keys(n).map(e=>[e,o[e]])),globalKey:f,key:e,metadata:c.metadata,syncMetadata:r.syncedMetadata.get(e)||{},optimistic:c.optimistic??!0,type:`update`,createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(d.length===0){let e=this.createTransaction({mutationFn:async()=>{}});return e.commit().catch(()=>void 0),r.scheduleTransactionCleanup(e),e}if(i)return i.applyMutations(d),r.transactions.set(i.id,i),r.scheduleTransactionCleanup(i),r.recomputeOptimisticState(!0),i;let f=this.createTransaction({metadata:{[_o]:!0},mutationFn:async e=>this.config.onUpdate({transaction:e.transaction,collection:this.collection})});return f.applyMutations(d),this.markPendingLocalOrigins(d),f.commit().catch(()=>void 0),r.transactions.set(f.id,f),r.scheduleTransactionCleanup(f),r.recomputeOptimisticState(!0),f}},Fs=class extends zo{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t){this.emit(`status:change`,{type:`status:change`,collection:this.collection,previousStatus:t,status:e});let n=`status:${e}`;this.emit(n,{type:n,collection:this.collection,previousStatus:t,status:e})}emitSubscribersChange(e,t){this.emit(`subscribers:change`,{type:`subscribers:change`,collection:this.collection,previousSubscriberCount:t,subscriberCount:e})}emitIndexAdded(e){this.emit(`index:added`,{type:`index:added`,collection:this.collection,index:e})}emitIndexRemoved(e){this.emit(`index:removed`,{type:`index:removed`,collection:this.collection,index:e})}cleanup(){this.clearListeners()}};function Is(e){let t=new Ls(e);return t.utils=e.utils?e.utils:{},t}var Ls=class{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(e,t)=>this._mutations.insert(e,t),this.delete=(e,t)=>this._mutations.delete(e,t),!e)throw new Ve;if(!e.sync)throw new He;if(this.id=e.id?e.id:Le(),this.config={...e,autoIndex:e.autoIndex??`off`},this.config.autoIndex===`eager`&&!e.defaultIndexType)throw new Be(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it:
13
+ import { BasicIndex } from '@tanstack/db'
14
+ createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);this._changes=new Ho,this._events=new Fs,this._indexes=new cs,this._lifecycle=new Yo(e,this.id),this._mutations=new Ps(e,this.id),this._state=new vo(e),this._sync=new Qo(e,this.id),this.comparisonOpts=Rs(e),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events,state:this._state}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:e.defaultIndexType,events:this._events}),this._lifecycle.setDeps({changes:this._changes,events:this._events,indexes:this._indexes,state:this._state,sync:this._sync}),this._mutations.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this._changes,indexes:this._indexes,events:this._events}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this._events}),e.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get subscriberCount(){return this._changes.activeSubscribersCount}get _stateRevision(){return this._changes.stateRevision}get _layoutRevision(){return this._changes.layoutRevision}_subscribeLayoutChanges(e){return this._changes.subscribeLayoutChanges(e)}_markLayoutChange(){this._sync.markLayoutChange()}_deferPublication(){return this._changes.deferPublication()}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status===`ready`}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}_setTransactionScope(e){this._mutations.setTransactionScope(e)}_hasHydratedKey(e){return this._state.hydratedKeys.has(e)}_deferSyncStart(){return this._sync.deferStart()}_resumeSyncStart(){this._sync.resumeStart()}preload(){return this._sync.preload()}get(e){return this._state.getWithVirtualProps(e)}has(e){return this._state.has(e)}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){for(let e of this._state.keys()){let t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(let e of this._state.keys()){let t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let t=0;for(let[n,r]of this.entries())e(r,n,t++)}map(e){let t=[],n=0;for(let[r,i]of this.entries())t.push(e(i,r,n++));return t}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,t={}){return this._indexes.createIndex(e,t)}removeIndex(e){return this._indexes.removeIndex(e)}getIndexMetadata(){return this._indexes.getIndexMetadataSnapshot()}get indexes(){return this._indexes.indexes}validateData(e,t,n){return this._mutations.validateData(e,t,n)}get compareOptions(){return{...this.comparisonOpts}}update(e,t,n){return this._mutations.update(e,t,n)}get state(){let e=new Map;for(let[t,n]of this.entries())e.set(t,n);return e}stateWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.state):this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.toArray):this.preload().then(()=>this.toArray)}currentStateAsChanges(e={}){return uo(this,e)}subscribeChanges(e,t={}){return this._changes.subscribeChanges(e,t)}on(e,t){return this._events.on(e,t)}once(e,t){return this._events.once(e,t)}off(e,t){this._events.off(e,t)}waitFor(e,t){return this._events.waitFor(e,t)}async cleanup(){return this._lifecycle.cleanup(),Promise.resolve()}};function Rs(e){if(e.defaultStringCollation){let t=e.defaultStringCollation;return{stringSort:t.stringSort??`locale`,locale:t.stringSort===`locale`?t.locale:void 0,localeOptions:t.stringSort===`locale`?t.localeOptions:void 0}}return{stringSort:`locale`}}var zs=Symbol.for(`@tanstack/db.collectionOptions`);function Bs(e){return typeof e==`object`&&!!e&&e[zs]===!0}var Vs=new WeakMap;function Hs(e){return e.utils?.[Zo]?.getBuilder?.()}function Us(e,t){Vs.set(e,t)}function Ws(e){return Vs.get(e)}function Gs(e){if(e.from.type===`unionAll`)return{optimizedQuery:{...e,from:new Ce(e.from.queries.map(e=>Gs(e).optimizedQuery))},sourceWhereClauses:new Map};let t=Ks(e),n=e,r,i=0;for(;i<10&&!B(n,r);)r=n,n=Ys(n),i++;return{optimizedQuery:Zs(n),sourceWhereClauses:t}}function Ks(e){let t=new Map;if(!e.where||e.where.length===0)return t;let n=ic(tc(e.where).map(e=>rc(e))),r=Js(e);for(let[i,a]of n.singleSource)qs(e,i)&&!r.has(i)&&t.set(i,a);return t}function qs(e,t){for(let n of uc(e.from))if(n.alias===t)return n.type===`collectionRef`;if(e.join){for(let n of e.join)if(n.from.alias===t)return n.from.type===`collectionRef`}return!1}function Js(e){let t=new Set;if(e.join){let n=new Set(uc(e.from).map(e=>e.alias));for(let r of e.join){let e=r.from.alias;if((r.type===`left`||r.type===`full`)&&t.add(e),r.type===`right`||r.type===`full`)for(let e of n)t.add(e);n.add(e)}}return t}function Ys(e){return Xs({...e,from:lc(e.from),join:e.join?.map(e=>({...e,from:e.from.type===`queryRef`?new xe(Ys(e.from.query),e.from.alias):e.from}))})}function Xs(e){if(!e.where||e.where.length===0||e.from.type===`unionFrom`)return e;if(!e.join||e.join.length===0){if(e.where.length>1){let t=wc(tc(e.where));return{...e,where:[t]}}return e}let t=ac(e,ic(tc(e.where.filter(e=>!Ne(e))).map(e=>rc(e)))),n=e.where.filter(e=>Ne(e));return n.length>0&&(t.where=[...t.where||[],...n]),t}function Zs(e){return{...e,from:Qs(e.from),join:e.join?.map(e=>({...e,from:$s(e.from)}))}}function Qs(e){if(e.type===`unionFrom`)return new Se(e.sources.map(e=>Qs(e)));if(e.type===`unionAll`)return new Ce(e.queries.map(e=>Zs(e)));if(e.type===`collectionRef`)return e;let t=Zs(e.query);if(ec(t)){let n=Qs(t.from);if(n.type===`collectionRef`)return new be(n.collection,e.alias);if(n.type===`queryRef`)return new xe(n.query,e.alias)}return new xe(t,e.alias)}function $s(e){return Qs(e)}function ec(e){return(!e.where||e.where.length===0)&&!e.select&&(!e.groupBy||e.groupBy.length===0)&&(!e.having||e.having.length===0)&&(!e.orderBy||e.orderBy.length===0)&&(!e.join||e.join.length===0)&&e.limit===void 0&&e.offset===void 0&&!e.fnSelect&&(!e.fnWhere||e.fnWhere.length===0)&&(!e.fnHaving||e.fnHaving.length===0)}function tc(e){let t=[];for(let n of e){let e=je(n);t.push(...nc(e))}return t}function nc(e){if(e.type===`func`&&e.name===`and`){let t=[];for(let n of e.args)t.push(...nc(n));return t}return[e]}function rc(e){let t=new Set,n=!1;function r(e){switch(e.type){case`ref`:if(e.path&&e.path.length>0){let r=e.path[0];r&&(t.add(r),e.path.length===1&&(n=!0))}break;case`func`:e.args&&e.args.forEach(r);break;case`val`:break;case`agg`:e.args&&e.args.forEach(r)}}return r(e),{expression:e,touchedSources:t,hasNamespaceOnlyRef:n}}function ic(e){let t=new Map,n=[];for(let r of e)if(r.touchedSources.size===1&&!r.hasNamespaceOnlyRef){let e=Array.from(r.touchedSources)[0];t.has(e)||t.set(e,[]),t.get(e).push(r.expression)}else(r.touchedSources.size>1||r.hasNamespaceOnlyRef)&&n.push(r.expression);let r=new Map;for(let[e,n]of t)r.set(e,wc(n));return{singleSource:r,multiSource:n.length>0?wc(n):void 0}}function ac(e,t){let n=new Set,r=Js(e),i=new Map;for(let[e,n]of t.singleSource)r.has(e)||i.set(e,n);let a=fc(e.from,i,n),o=e.join?e.join.map(e=>({...e,from:pc(e.from,i,n)})):void 0,s=[];t.multiSource&&s.push(t.multiSource);let c=r.size>0;for(let[e,r]of t.singleSource)n.has(e)?c&&s.push(Pe(r)):s.push(r);let l=s.length>1?[wc(s.flatMap(e=>nc(je(e))))]:s;return{select:e.select,groupBy:e.groupBy?[...e.groupBy]:void 0,having:e.having?[...e.having]:void 0,orderBy:e.orderBy?[...e.orderBy]:void 0,limit:e.limit,offset:e.offset,distinct:e.distinct,fnSelect:e.fnSelect,fnWhere:e.fnWhere?[...e.fnWhere]:void 0,fnHaving:e.fnHaving?[...e.fnHaving]:void 0,from:a,join:o,where:l.length>0?l:[]}}function oc(e){return{from:sc(e.from),select:e.select,join:e.join?e.join.map(e=>({type:e.type,left:e.left,right:e.right,from:cc(e.from)})):void 0,where:e.where?[...e.where]:void 0,groupBy:e.groupBy?[...e.groupBy]:void 0,having:e.having?[...e.having]:void 0,orderBy:e.orderBy?[...e.orderBy]:void 0,limit:e.limit,offset:e.offset,fnSelect:e.fnSelect,fnWhere:e.fnWhere?[...e.fnWhere]:void 0,fnHaving:e.fnHaving?[...e.fnHaving]:void 0}}function sc(e){return e.type===`collectionRef`?new be(e.collection,e.alias):e.type===`queryRef`?new xe(oc(e.query),e.alias):e.type===`unionAll`?new Ce(e.queries.map(e=>oc(e))):new Se(e.sources.map(e=>sc(e)))}function cc(e){return sc(e)}function lc(e){return e.type===`queryRef`?new xe(Ys(e.query),e.alias):e.type===`unionFrom`?new Se(e.sources.map(e=>lc(e))):e.type===`unionAll`?new Ce(e.queries.map(e=>Ys(e))):e}function uc(e){return e.type===`unionFrom`?e.sources:e.type===`unionAll`?[]:[e]}function dc(e){return uc(e.from)[0]?.alias}function fc(e,t,n){if(e.type===`unionFrom`)return new Se(e.sources.map(e=>pc(e,t,n)));if(e.type===`unionAll`)return new Ce(e.queries.map(e=>oc(e)));let r=t.get(e.alias);if(!r)return e.type===`collectionRef`?new be(e.collection,e.alias):new xe(oc(e.query),e.alias);if(e.type===`collectionRef`){let t={from:new be(e.collection,e.alias),where:[r]};return n.add(e.alias),new xe(t,e.alias)}if(!yc(e.query,r,e.alias)||Cc(e.query,r,e.alias))return new xe(oc(e.query),e.alias);let i=e.query.where||[],a={...oc(e.query),where:[...i,r]};return n.add(e.alias),new xe(a,e.alias)}function pc(e,t,n){return fc(e,t,n)}function mc(e,t,n){return e.select?bc(e.select)||Sc(e.select,t,n):!1}function hc(e){return e.groupBy&&e.groupBy.length>0}function gc(e){return e.having&&e.having.length>0}function _c(e){return e.orderBy&&e.orderBy.length>0&&(e.limit!==void 0||e.offset!==void 0)}function vc(e){return e.fnSelect||e.fnWhere&&e.fnWhere.length>0||e.fnHaving&&e.fnHaving.length>0}function yc(e,t,n){return!(mc(e,t,n)||hc(e)||gc(e)||_c(e)||vc(e))}function bc(e){for(let t of Object.values(e))if(typeof t==`object`){let e=t;if(e.type===`agg`||!(`type`in e)&&bc(e))return!0}return!1}function xc(e){let t=[];if(typeof e!=`object`||!e)return t;switch(e.type){case`ref`:t.push(e);break;case`func`:case`agg`:for(let n of e.args??[])t.push(...xc(n))}return t}function Sc(e,t,n){let r=new Set;for(let[t,n]of Object.entries(e))t.startsWith(`__SPREAD_SENTINEL__`)||n instanceof z||r.add(t);let i=xc(t);for(let e of i){let t=e.path;if(!Array.isArray(t)||t.length<2)continue;let i=t[0],a=t[1];if(i===n&&r.has(a))return!0}return!1}function Cc(e,t,n){let r=xc(t);if(r.every(e=>e.path[0]!==n))return!1;if(e.fnSelect)return!0;let i=e.select;if(!i)return!1;for(let t of r){let r=t.path;if(r.length<2||r[0]!==n)continue;let a=i[r[1]];if(!a)continue;if(!(a instanceof z)||a.path.length<2)return!0;let[o,s]=a.path,c=dc(e);if(o!==n&&o!==c||s!==r[1])return!0}return!1}function wc(e){if(e.length===0)throw new sn;return e.length===1?e[0]:new Te(`and`,e)}var Tc=`unionAll clause`,Ec=class e{constructor(e={},t){this.resolveCollection=t,this.query={},this.query={...e}}_clone(t){return new e(t,this.resolveCollection)}_createRefForSource(e,t){let n=this._createRefsForSource(e,t);if(n.length!==1)throw new St(t);return n[0]}_createRefsForSource(t,n){if(typeof t==`string`)throw new Tt(n,`string`);let r;try{r=Object.keys(t)}catch{throw new Tt(n,t===null?`null`:`undefined`)}if(Array.isArray(t))throw new Tt(n,`array`);if(r.length===0)throw new Tt(n,`empty object`);if(n!==Tc&&r.length!==1)throw new St(n);let i=[];for(let a of r){let r=t[a],o;if(r instanceof Ls)o=new be(r,a);else if(Bs(r)){if(!this.resolveCollection)throw Error(`Cannot use collection descriptor "${a}" as a query source without a DbClient resolver. In React, wrap your tree in <DbProvider>.`);o=new be(this.resolveCollection(r),a)}else if(r instanceof e){let e=r._getQuery();if(!e.from)throw new Ct(n);o=new xe(e,a)}else throw new wt(a);i.push([a,o])}return i}from(e){let[,t]=this._createRefForSource(e,`from clause`);return this._clone({...this.query,from:t})}unionAll(t,...n){if(t instanceof e)return this._clone({...this.query,from:new Ce([t,...n].map(e=>e._getQuery()))});let r=this._createRefsForSource(t,Tc),i=r.length===1?r[0][1]:new Se(r.map(e=>e[1]));return this._clone({...this.query,from:i})}join(e,t,n=`left`){let[r,i]=this._createRefForSource(e,`join clause`),a=t(To([...this._getCurrentAliases(),r])),o,s;if(a.type===`func`&&a.name===`eq`&&a.args.length===2)o=a.args[0],s=a.args[1];else throw new Et;let c={from:i,type:n,left:o,right:s},l=this.query.join||[];return this._clone({...this.query,join:[...l,c]})}leftJoin(e,t){return this.join(e,t,`left`)}rightJoin(e,t){return this.join(e,t,`right`)}innerJoin(e,t){return this.join(e,t,`inner`)}fullJoin(e,t){return this.join(e,t,`full`)}where(e){let t=e(To(this._getCurrentAliases())),n=Do(t)?G(t):t;if(!ke(n))throw new Ot(Dc(n));let r=this.query.where||[];return this._clone({...this.query,where:[...r,n]})}having(e){let t=this._getCurrentAliases(),n=e(this.query.select||this.query.fnSelect?Eo(t):To(t)),r=Do(n)?G(n):n;if(!ke(r))throw new Ot(Dc(r));let i=this.query.having||[];return this._clone({...this.query,having:[...i,r]})}select(e){let t=this._getCurrentAliases(),n=e(To(t));Do(n)&&n.__path.length===1&&(n={[`__SPREAD_SENTINEL__${n.__path[0]}__0`]:!0});let r=Ac(n,t);return this._clone({...this.query,select:r,fnSelect:void 0})}orderBy(e,t=`asc`){let n=this._getCurrentAliases(),r=e(this.query.select||this.query.fnSelect?Eo(n):To(n)),i=typeof t==`string`?{direction:t,nulls:`first`}:{direction:t.direction??`asc`,nulls:t.nulls??`first`,stringSort:t.stringSort,locale:t.stringSort===`locale`?t.locale:void 0,localeOptions:t.stringSort===`locale`?t.localeOptions:void 0},a=e=>({expression:G(e),compareOptions:i}),o=Array.isArray(r)?r.map(e=>a(e)):[a(r)],s=this.query.orderBy||[];return this._clone({...this.query,orderBy:[...s,...o]})}groupBy(e){let t=e(To(this._getCurrentAliases())),n=Array.isArray(t)?t.map(e=>G(e)):[G(t)],r=this.query.groupBy||[];return this._clone({...this.query,groupBy:[...r,...n]})}limit(e){return this._clone({...this.query,limit:e})}offset(e){return this._clone({...this.query,offset:e})}distinct(){return this._clone({...this.query,distinct:!0})}findOne(){return this._clone({...this.query,singleResult:!0})}_getCurrentAliases(){let e=[];if(this.query.from&&(this.query.from.type===`unionFrom`?e.push(...this.query.from.sources.map(e=>e.alias)):this.query.from.type===`unionAll`?e.push(`*`):e.push(this.query.from.alias)),this.query.join)for(let t of this.query.join)e.push(t.from.alias);return e}get fn(){let e=this;return{select(t){return e._clone({...e.query,select:void 0,fnSelect:t})},where(t){return e._clone({...e.query,fnWhere:[...e.query.fnWhere||[],t]})},having(t){return e._clone({...e.query,fnHaving:[...e.query.fnHaving||[],t]})}}}_getQuery(){if(!this.query.from)throw new Dt;return this.query}};function Dc(e){return e===null?`null`:e===void 0?`undefined`:typeof e==`object`?`object`:typeof e}function Oc(e){return e===void 0?G(null):e instanceof Ee||e instanceof Te||e instanceof z||e instanceof we?e:G(e)}function kc(e){return typeof e==`object`&&!!e&&!ke(e)&&!e.__refProxy}function Ac(e,t=[],n){if(e instanceof Ec){if(!n)throw Error(`Conditional include branch is missing a field name`);return Rc(e,n,t,`collection`)}if(e instanceof Fo){if(!(e.query instanceof Ec))throw Error(`toArray() must wrap a subquery builder`);if(!n)throw Error(`Conditional toArray() branch is missing a field name`);return Rc(e.query,n,t,`array`)}if(e instanceof Io){if(!(e.query instanceof Ec))throw Error(`concat(toArray(...)) must wrap a subquery builder`);if(!n)throw Error(`Conditional concat(toArray(...)) branch is missing a field name`);return Rc(e.query,n,t,`concat`)}if(e instanceof Lo)return jc(e,t,n);if(!kc(e))return Oc(e);let r={};for(let[n,i]of Object.entries(e)){if(typeof n==`string`&&n.startsWith(`__SPREAD_SENTINEL__`)){r[n]=i;continue}if(i instanceof Ec){r[n]=Rc(i,n,t,`collection`);continue}if(i instanceof Fo){if(!(i.query instanceof Ec))throw Error(`toArray() must wrap a subquery builder`);r[n]=Rc(i.query,n,t,`array`);continue}if(i instanceof Io){if(!(i.query instanceof Ec))throw Error(`concat(toArray(...)) must wrap a subquery builder`);r[n]=Rc(i.query,n,t,`concat`);continue}if(i instanceof Ro){if(!(i.query instanceof Ec))throw Error(`materialize() must wrap a subquery builder`);let e=i.query._getQuery().singleResult?`singleton`:`array`;r[n]=Rc(i.query,n,t,e);continue}if(i instanceof Lo){r[n]=jc(i,t,n);continue}r[n]=Ac(i,t,n)}return r}function jc(e,t,n){let r=e.args;if(r.length<2)throw Error(`caseWhen() requires at least two arguments`);let i=r.length%2==1,a=Math.floor(r.length/2),o=[];for(let e=0;e<a;e++)o.push({condition:G(r[e*2]),value:Ac(r[e*2+1],t,n)});return new Oe(o,i?Ac(r[r.length-1],t,n):void 0)}function Mc(e){let t=[];switch(e.type){case`ref`:t.push(e);break;case`func`:case`agg`:for(let n of e.args)t.push(...Mc(n))}return t}function Nc(e){return e instanceof z||e instanceof Te||e instanceof Ee?Mc(e):e instanceof Oe?[...e.branches.flatMap(e=>[...Mc(e.condition),...Nc(e.value)]),...e.defaultValue===void 0?[]:Nc(e.defaultValue)]:e instanceof De?[e.correlationField,...e.parentProjection??[],...Pc(e.query)]:kc(e)?Object.values(e).flatMap(Nc):[]}function Pc(e){let t=new Set(zc(e)),n=[],r=e=>{n.push(...Mc(e))},i=e=>{r(typeof e==`object`&&`expression`in e?e.expression:e)};for(let t of e.where??[])i(t);for(let t of e.join??[])r(t.left),r(t.right),t.from.type===`queryRef`&&n.push(...Pc(t.from.query));for(let t of e.groupBy??[])r(t);for(let t of e.having??[])i(t);for(let{expression:t}of e.orderBy??[])r(t);if(e.select&&n.push(...Nc(e.select)),e.from.type===`queryRef`)n.push(...Pc(e.from.query));else if(e.from.type===`unionFrom`)for(let t of e.from.sources)t.type===`queryRef`&&n.push(...Pc(t.query));else if(e.from.type===`unionAll`)for(let t of e.from.queries)n.push(...Pc(t));let a=new Set;return n.filter(e=>{let n=e.path.length>1?e.path[0]:void 0,r=e.path.join(`.`);return n==null||n===`$selected`||t.has(n)||a.has(r)?!1:(a.add(r),!0)})}function Fc(e,t){let n=[],r=e=>{n.push(...Mc(e))},i=e=>{r(typeof e==`object`&&`expression`in e?e.expression:e)};for(let t of e.where??[])i(t);for(let i of e.join??[])r(i.left),r(i.right),i.from.type===`queryRef`&&n.push(...Fc(i.from.query,t));for(let t of e.groupBy??[])r(t);for(let t of e.having??[])i(t);for(let{expression:t}of e.orderBy??[])r(t);if(e.select&&n.push(...Nc(e.select)),e.from.type===`queryRef`)n.push(...Fc(e.from.query,t));else if(e.from.type===`unionFrom`)for(let r of e.from.sources)r.type===`queryRef`&&n.push(...Fc(r.query,t));else if(e.from.type===`unionAll`)for(let r of e.from.queries)n.push(...Fc(r,t));let a=new Set;return n.filter(e=>{let n=e.path.join(`.`);return e.path[0]==null||!t.includes(e.path[0])||a.has(n)?!1:(a.add(n),!0)})}function Ic(e){return[...new Set(Pc(e).map(e=>e.path[0]).filter(e=>e!==void 0))]}function Lc(e,t){return Mc(typeof e==`object`&&`expression`in e?e.expression:e).some(e=>e.path[0]!=null&&t.includes(e.path[0]))}function Rc(e,t,n,r){let i=e._getQuery(),a=zc(i),o=[...new Set([...n,...Ic(i)])],s,c,l=-1,u=-1;if(i.where)for(let e=0;e<i.where.length;e++){let t=i.where[e],n=typeof t==`object`&&`expression`in t?t.expression:t;if(n.type===`func`&&n.name===`eq`&&n.args.length===2){let t=Vc(n.args[0],n.args[1],o,a);if(t){s=t.parentRef,c=t.childRef,l=e;break}}if(n.type===`func`&&n.name===`and`&&n.args.length>=2){for(let t=0;t<n.args.length;t++){let r=n.args[t];if(r.type===`func`&&r.name===`eq`&&r.args.length===2){let n=Vc(r.args[0],r.args[1],o,a);if(n){s=n.parentRef,c=n.childRef,l=e,u=t;break}}}if(s)break}}if(!s||!c||l===-1)throw Error(`Includes subquery for "${t}" must have a WHERE clause with an eq() condition that correlates a parent field with a child field. Example: .where(({child}) => eq(child.parentId, parent.id))`);let d=[...i.where];if(u>=0){let e=d[l],t=(typeof e==`object`&&`expression`in e?e.expression:e).args.filter((e,t)=>t!==u);if(t.length===1){let n=typeof e==`object`&&`expression`in e&&e.residual;d[l]=n?{expression:t[0],residual:!0}:t[0]}else{let n=new Te(`and`,t),r=typeof e==`object`&&`expression`in e&&e.residual;d[l]=r?{expression:n,residual:!0}:n}}else d.splice(l,1);let f=[],p=[];for(let e of d)Lc(e,o)?p.push(e):f.push(e);let m=Fc({...i,where:d},o),h=m.length>0?m:void 0,g={...i,where:f.length>0?f:void 0},_=g.select,v=_===void 0||kc(_),y=g,b;if(r===`concat`&&(_===void 0||v))throw Error(`concat(toArray(...)) for "${t}" requires the subquery to select a scalar value`);if(!v){if(r===`collection`)throw Error(`Includes subquery for "${t}" must select an object when materializing as a Collection`);b=_e,y={...g,select:{[b]:_}}}return new De(y,s,c,t,p.length>0?p:void 0,h,r,b)}function zc(e){let t=new Set(Bc(e.from));if(e.join)for(let n of e.join)t.add(n.from.alias);return[...t]}function Bc(e){return e.type===`unionFrom`?e.sources.map(e=>e.alias):e.type===`unionAll`?e.queries.flatMap(e=>zc(e)):[e.alias]}function Vc(e,t,n,r){if(e.type===`ref`&&t.type===`ref`){let i=e.path[0],a=t.path[0];if(i&&a&&n.includes(i)&&r.includes(a))return{parentRef:e,childRef:t};if(i&&a&&n.includes(a)&&r.includes(i))return{parentRef:t,childRef:e}}}function Hc(e){return Uc(e(new Ec))}function Uc(e){return e._getQuery()}function Wc(e,t,n,r,i,a){if(t.type===`unionFrom`)return qc(e,r);if(t.type===`queryRef`&&Gc(t.query.from))return Qc(Kc(t.query,n,r));if(!i)return[];let o=$c(r);if(!o)return[];let s=Ie(e,o,i);if(!s)return[];let c=s.alias||a[n]||n,l=Xc(e,t,{alias:c,collection:s.collection});return l?[{sourceId:l.sourceId,alias:c,collection:s.collection,path:s.path}]:[]}function Gc(e){return e.type===`unionFrom`?!0:e.type===`queryRef`?Gc(e.query.from):e.type===`unionAll`&&e.queries.some(e=>Gc(e.from))}function Kc(e,t,n){if(!n||typeof n!=`object`||!(`type`in n))return[];let r=n;if(r.type===`func`&&r.name===`coalesce`)return Qc(r.args.flatMap(n=>Kc(e,t,n)));let i=$c(r);return!i||i.path[0]!==t?[]:Jc(e,new z(i.path.slice(1)))}function qc(e,t){if(!t||typeof t!=`object`||!(`type`in t))return[];let n=t;return n.type===`ref`?Jc(e,n):n.type===`func`&&n.name===`coalesce`?Qc(n.args.flatMap(t=>qc(e,t))):[]}function Jc(e,t){if(t.path.length===0)return[];if(t.path.length===1){let n=t.path[0],r=e.select?.[n];return r?qc(e,r):[]}let[n,...r]=t.path,i=Yc(e,n);return i?i.type===`collectionRef`?[{sourceId:i.sourceId,alias:i.alias,collection:i.collection,path:r}]:i.query.limit||i.query.offset?[]:Kc(i.query,i.alias,t):[]}function Yc(e,t){if(e.join){for(let n of e.join)if(n.from.alias===t)return n.from}let n=e.from;return(n.type===`unionFrom`?n.sources:n.type===`unionAll`?[]:[n]).find(e=>e.alias===t)}function Xc(e,t,n){let r=Zc(e,n.alias,n.collection);if(r)return r;if(t.type===`collectionRef`&&t.collection===n.collection&&t.alias===n.alias)return t}function Zc(e,t,n){let r=[...e.from.type===`unionFrom`?e.from.sources:e.from.type===`unionAll`?[]:[e.from],...e.join?.map(e=>e.from)??[]];for(let e of r){if(e.type===`collectionRef`&&e.alias===t&&e.collection===n)return e;if(e.type===`queryRef`){let r=Zc(e.query,t,n);if(r)return r}}if(e.from.type===`unionAll`)for(let r of e.from.queries){let e=Zc(r,t,n);if(e)return e}}function Qc(e){let t=new Set,n=[];for(let r of e){let e=`${r.sourceId}:${r.path.join(`.`)}`;t.has(e)||(t.add(e),n.push(r))}return n}function $c(e){if(e instanceof z)return e;if(e&&typeof e==`object`&&`type`in e&&e.type===`ref`&&Array.isArray(e.path))return new z(e.path)}var el=`__tanstack_parent_route_cross__`;function tl(e,t,n){let r=e.pipe(W(([e,t])=>[el,[e,t]])),i=t.pipe(W(([e,t])=>[el,[e,t]]));return r.pipe(Xi(i,`inner`),Hi(([,[e,t]])=>e!=null&&t!=null),W(([,[e,t]])=>{let[r,i]=e,[a,o]=t;return n(r,i,a,o)}))}var nl=Symbol(`tanstack_db_routed_scalar_value`),rl=Symbol(`includesPublicKey`);function il(e,t,n,r){return t===void 0&&n===void 0&&r===void 0?e:typeof e==`object`&&e?{...e,__correlationKey:t,__parentContext:n,[rl]:r}:{[nl]:e,__correlationKey:t,__parentContext:n,[rl]:r}}function al(e){if(typeof e!=`object`||!e||!(nl in e))return;let t=e;return{value:t[nl],correlationKey:t.__correlationKey,parentContext:t.__parentContext,publicKey:t[rl]}}var ol=0;function sl(e,t){return tl(e,t,(e,t,n,r)=>[U([e,n,r]),{...t,__correlationKey:n,__parentContext:r}])}function cl(e,t){let n=al(t);if(n){let t={[e]:n.value,__correlationKey:n.correlationKey,__parentContext:n.parentContext,[rl]:n.publicKey};return n.parentContext!=null&&typeof n.parentContext==`object`&&Object.assign(t,n.parentContext),t}if(typeof t!=`object`||!t)return{[e]:t};let{__parentContext:r,...i}=t,a={[e]:i};return r!=null&&(Object.assign(a,r),a.__parentContext=r),a}function ll(e,t,n){return U([e[t]?.__correlationKey??e.__correlationKey,e.__parentContext??e[t]?.__parentContext??null,n])}function ul(e,t,n=new Set){let r={id:`lazy-demand-${++ol}`,path:t.path,collectionId:t.collection.id,initialKeys:new Set(n)},i=e[t.sourceId]??={};return(i.plans??=[]).push(r),r}function dl(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b){let x=e;for(let e of t)x=fl(x,e,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b);return x}function fl(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b){let x=t.from.type===`collectionRef`,S=t.from.alias,C=[...Object.keys(n),S],{mainExpr:w,joinedExpr:T}=pl(t.left,t.right,C,S,m.from.type===`unionAll`),E=[...ml(T)].some(e=>e!==S&&!n[e]),D=b!==void 0&&(t.from.type===`queryRef`||E),{alias:O,input:k,collectionId:A}=hl(t.from,a,c,l,u,d,f,p,o,s,h,g,_,v,D?b:void 0);if(O!==S)throw new qt;n[S]=k,x&&(g[S]=A);let j=c[r],M=c[A];if(!j)throw new Ut(r);if(!M)throw new Ut(A);let N=vl(t.type,j,M,y),P=D?void 0:N.activeSource,ee=N.lazySource,F=H(w),te=H(T),ne=e.pipe(W(([e,t])=>{let n=Cn(F(t));return[D?ll(t,i,n):n,[e,t]]})),re=k.pipe(W(([e,t])=>{let n=cl(S,t),r=Cn(te(n));return[D?ll(n,S,r):r,[e,n]]}));if(![`inner`,`left`,`right`,`full`].includes(t.type))throw new Gt(t.type);if(P){let e=P===`main`?t.from:m.from,n=e.type===`queryRef`&&(e.query.limit||e.query.offset),r=e.type===`unionAll`?[]:Wc(m,e,P===`main`?S:i,P===`main`?T:w,ee,_);if(!n&&r.length>0){for(let e of r)d.add(e.sourceId);let e=r.map(e=>ul(u,e)),t=new Map,n=P===`main`?ne:re;for(let e of r){let t=e.path[0];t&&ur(t,e.path,e.collection)}let i=n.pipe(Bi(n=>{for(let[[e],r]of n.getInner()){if(e==null)continue;let n=U(e),i=(t.get(n)?.weight??0)+r;i===0?t.delete(n):t.set(n,{key:e,weight:i})}let i=new Set([...t.values()].filter(({weight:e})=>e>0).map(({key:e})=>e));for(let t=0;t<r.length;t++)u[r[t].sourceId]?.setDemand?.(e[t],i)}));P===`main`?ne=i:re=i}}return ne.pipe(Xi(re,t.type),_l(t.type))}function pl(e,t,n,r,i=!1){let a=n.filter(e=>e!==r),o=ml(e),s=ml(t),c=o.has(r),l=s.has(r),u=[...o].filter(e=>a.includes(e)||i&&e!==r),d=[...s].filter(e=>a.includes(e)||i&&e!==r);if(u.length>0&&!c&&l&&d.length===0)return{mainExpr:e,joinedExpr:t};if(c&&u.length===0&&d.length>0&&!l)return{mainExpr:t,joinedExpr:e};throw o.size===0||s.size===0?new qt:o.size===1&&s.size===1&&[...o][0]===[...s][0]?new Kt([...o][0]):u.length===0?new Jt([...o][0]):l?new Xt:new Yt(r)}function ml(e){switch(e.type){case`ref`:return new Set(e.path[0]?[e.path[0]]:[]);case`func`:{let t=new Set;for(let n of e.args)for(let e of ml(n))t.add(e);return t}default:return new Set}}function hl(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m){switch(e.type){case`collectionRef`:{let n=t[e.sourceId]??t[e.alias];if(!n)throw new Lt(e.alias,e.collection.id,Object.keys(t));return d[e.alias]=e.collection.id,{alias:e.alias,input:m?sl(n,m):n,collectionId:e.collection.id}}case`queryRef`:{let h=u(l.get(e.query)||e.query,t,n,r,i,a,o,s,c,l,m);Object.assign(d,h.aliasToCollectionId),Object.assign(f,h.aliasRemapping);let g=l.has(e.query),_=gl(e.query);if(!(!g&&_!==void 0&&e.alias===_))for(let[e,t]of h.sourceWhereClauses)p.set(e,t);let v=Object.keys(h.aliasToCollectionId).find(e=>h.aliasToCollectionId[e]===h.collectionId);v&&v!==e.alias&&(f[e.alias]=v);let y=h.pipeline.pipe(W(e=>{let[t,[n,r,i,a,o]]=e;return m?[t,il(n,i,a,o)]:[t,n]}));return{alias:e.alias,input:y,collectionId:h.collectionId}}default:throw new Zt(e.type)}}function gl(e){if(e.from.type===`unionFrom`)return e.from.sources[0]?.alias;if(e.from.type!==`unionAll`)return e.from.alias}function _l(e){return function(t){return t.pipe(Hi(t=>{let[n,[r,i]]=t,a=r?.[1],o=i?.[1];return e===`inner`?!!(a&&o):e===`left`?!!a:e!==`right`||!!o}),W(e=>{let[t,[n,r]]=e,i=n?.[0],a=n?.[1],o=r?.[0],s=r?.[1],c={};return a&&Object.assign(c,a),s&&Object.assign(c,s),[`[${i},${o}]`,c]}))}}function vl(e,t,n,r){switch(e){case`left`:return{activeSource:`main`,lazySource:n};case`right`:return{activeSource:`joined`,lazySource:t};case`inner`:return r||t.size<n.size?{activeSource:`main`,lazySource:n}:{activeSource:`joined`,lazySource:t};default:return{activeSource:void 0,lazySource:void 0}}}function yl(e){return e instanceof we?e.value:e}var bl=new Set([`__proto__`,`prototype`,`constructor`]);function xl(e){for(let t of e)if(bl.has(t))throw new At(t)}function Sl(e,t,n){xl(e.targetPath);let r=e.source(t);if(r&&typeof r==`object`){let t=n,i=e.targetPath;if(i.length===0)for(let[e,t]of Object.entries(r))n[e]=yl(t);else for(let e=0;e<i.length;e++){let n=i[e];if(e===i.length-1){let e=t[n]??={};if(typeof e==`object`)for(let[t,n]of Object.entries(r))e[t]=yl(n)}else{let e=t[n];(typeof e!=`object`||!e)&&(t[n]={}),t=t[n]}}}}function Cl(e,t,n){let r=e.alias.split(`.`);if(xl(r),r.length===1)n[e.alias]=e.compiled(t);else{let i=n;for(let e=0;e<r.length-1;e++){let t=r[e],n=i[t];(typeof n!=`object`||!n)&&(i[t]={}),i=i[t]}i[r[r.length-1]]=yl(e.compiled(t))}}function wl([e,t],n){let r={};for(let e of n)e.kind===`merge`?Sl(e,t,r):Cl(e,t,r);return[e,{...t,$selected:r}]}function Tl(e,t,n){if(!Al(t)){let n=Dl(t);return e.pipe(W(([e,t])=>[e,{...t,$selected:n(t)}]))}let r=[];return jl([],t,r),e.pipe(W(e=>wl(e,r)))}function El(e){let t=[];return jl([],e,t),e=>{let n={};for(let r of t)r.kind===`merge`?Sl(r,e,n):Cl(r,e,n);return n}}function Dl(e){return e==null?()=>e:Ml(e)?Qa(e)?()=>null:Ol(e):e instanceof we?()=>e.value:e.type===`includesSubquery`?()=>null:Al(e)?El(e):kl(e)||Qa(e)?()=>null:ke(e)?H(e):()=>e}function Ol(e){let t=e.branches.map(e=>({condition:H(e.condition),value:Dl(e.value)})),n=e.defaultValue===void 0?void 0:Dl(e.defaultValue);return e=>{for(let n of t)if(Rn(n.condition(e)))return n.value(e);return n===void 0?null:n(e)}}function kl(e){return e.type===`agg`}function Al(e){return e&&typeof e==`object`&&!ke(e)}function jl(e,t,n){for(let[r,i]of Object.entries(t)){if(r.startsWith(`__SPREAD_SENTINEL__`)||xl(r.split(`.`)),r.startsWith(`__SPREAD_SENTINEL__`)){let t=r.slice(19),a=t.lastIndexOf(`__`),o=a>=0?t.slice(0,a):t,s=i&&typeof i==`object`&&`type`in i&&i.type===`ref`;if(o.includes(`.`)||s){let t=[...e],r=H(s?i:new z(o.split(`.`)));n.push({kind:`merge`,targetPath:t,source:r})}else{let t=o,r=[...e];n.push({kind:`merge`,targetPath:r,source:e=>e[t]})}continue}let t=i;if(Ml(t)){if(Qa(t)){n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});continue}n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:Ol(t)});continue}if(t&&t.type===`includesSubquery`){n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});continue}if(Al(t)){jl([...e,r],t,n);continue}if(kl(t)||Qa(t))n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});else{if(t===void 0||!ke(t)){n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>t});continue}if(t instanceof we){let i=t.value;n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>i})}else n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:H(t)})}}}function Ml(e){return e instanceof Oe||typeof e==`object`&&!!e&&e.type===`conditionalSelect`&&Array.isArray(e.branches)}var Nl=Symbol(`includesRouting`),Pl=Symbol(`fnSelectState`),Fl=Symbol(`skipInclude`);function Il(e,t=new Set){if(e instanceof Ec)return`a child query builder`;if(e instanceof Fo)return`toArray()`;if(e instanceof Io)return`concat(toArray())`;if(e instanceof Ro)return`materialize()`;if(e instanceof Lo)return`caseWhen()`;if(ke(e))return e&&typeof e==`object`&&`name`in e&&typeof e.name==`string`?`${e.name}()`:`a query expression`;if(typeof e!=`object`||!e||t.has(e))return;t.add(e);let n=[...Object.keys(e),...Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))];for(let r of n){let n=e[r],i=Il(n,t);if(i)return i}}function Ll(e){let t=Il(e);if(t)throw new Nt(t)}function Rl(e,t){let n=e.__parentContext,r=typeof n==`object`&&n?{...n}:{};for(let n of t){if(n.field.length===0){let t=n.compiled(e);r[n.alias]=typeof t==`object`&&t?{...t}:t;continue}let t=r[n.alias],i=typeof t==`object`&&t?{...t}:{};r[n.alias]=i;let a=i;for(let e=0;e<n.field.length-1;e++){let t=n.field[e],r=a[t],i=typeof r==`object`&&r?{...r}:{};a[t]=i,a=i}a[n.field[n.field.length-1]]=n.compiled(e)}return r}function zl(e,t,n){return tl(e,t,(e,t,r,i)=>{let a={...t};return a[n]={...a[n],__correlationKey:r,[rl]:a[n]?.[rl]??e},i!=null&&Object.assign(a,i),a.__correlationKey=r,a.__parentContext=i,[U([e,r,i]),a]})}function Bl(e,t){return e[t]?.__correlationKey??e.__correlationKey}function Vl(e,t){if(e==null||t==null)return!1;let n=Cn(e),r=Cn(t);return Object.is(n,r)||typeof n==`number`&&typeof r==`number`&&Number.isNaN(n)&&Number.isNaN(r)}function Hl(e,t,n,r,i,a,o,s,c=new WeakMap,l=new WeakMap,u,d){let f=u===void 0?c.get(e):void 0;if(f)return f;ql(e);let{optimizedQuery:p,sourceWhereClauses:m}=Gs(e),h=p;l.set(h,e),iu(h,e,l);let g={...t};Wl(e,g);let _={},v={},y={},{alias:b,collectionId:x,pipeline:S,sources:C,sourceIncludes:w,directIncludes:T,isUnionFrom:E,isParentRouted:D}=Jl(h.from,g,n,r,i,a,o,s,c,l,_,v,m,u);Object.assign(y,C);let O=S,k=d?.path[0],A=!E&&!D&&u!==void 0&&d!==void 0&&k===b;if(u&&d&&A){let e=y[b],t=e,n=d.path.slice(1);t=e.pipe(W(([e,t])=>[wu(t,n),[e,t]])).pipe(Xi(u,`inner`)).pipe(Hi(([e,[t]])=>t!=null),W(([e,[t,n]])=>{let[r,i]=t,a={...i,__correlationKey:e,[rl]:r};return n!=null&&(a.__parentContext=n),[n==null?r:U([r,n]),a]})),y[b]=t,O=Xl(t,b)}else u&&!D&&(O=zl(S,u,b));if(h.join&&h.join.length>0&&(O=dl(O,h.join,y,x,b,g,c,l,n,r,i,a,o,s,e,Hl,_,v,m,u!==void 0,u)),u&&d&&!A){let e=H(d);O=O.pipe(Hi(([,t])=>Vl(e(t),Bl(t,b))))}if(h.where&&h.where.length>0)for(let e of h.where){let t=H(je(e));O=O.pipe(Hi(([e,n])=>Mn(t(n))))}if(h.fnWhere&&h.fnWhere.length>0)for(let e of h.fnWhere)O=O.pipe(Hi(([t,n])=>Mn(e(n))));let j=h.select?[]:[...T],M=[];for(let{sourceAlias:e,include:t}of w){let n=h.select==null?h.fnSelect?[]:[{path:[e,...t.resultPath],guards:[]}]:cu(h.select,e,t.resultPath);if(n.length!==0)for(let{path:r,guards:i}of n){let n=_u(`${e}.${r.join(`.`)}`,M),a=i.map(e=>({condition:H(e.condition),expected:e.expected}));j.push({...t,fieldName:n,resultPath:r}),M.push({fieldName:n,getRouting:n=>Tu(a,n)?n[e]?.[Nl]?.[t.fieldName]??{active:!1,correlationKey:null,parentContext:null}:{active:!1,correlationKey:null,parentContext:null}})}}if(h.select&&T.length>0)for(let e of T){let t=lu(h.select,e.resultPath);for(let{path:n,guards:r}of t){let t=_u(n.join(`.`),M),i=r.map(e=>({condition:H(e.condition),expected:e.expected}));j.push({...e,fieldName:t,resultPath:n}),M.push({fieldName:t,getRouting:t=>Tu(i,t)?t[Nl]?.[e.fieldName]??{active:!1,correlationKey:null,parentContext:null}:{active:!1,correlationKey:null,parentContext:null}})}}if(h.select){let t=pu(h.select);t.length>0&&(h={...h,select:{...h.select}});for(let{key:u,path:d,subquery:f,guards:p}of t){let t=_u(u,M),y=H(f.correlationField),b=p.map(e=>({condition:H(e.condition),expected:e.expected})),x=f.parentProjection?.map(e=>({alias:e.path[0],field:e.path.slice(1),compiled:H(e)}))??[],S;S=x.length>0?O.pipe(W(([e,t])=>{if(!Tu(b,t))return[Fl,null];let n=Rl(t,x);return[y(t),n]})):O.pipe(W(([e,t])=>Tu(b,t)?[y(t),null]:[Fl,null])),S=S.pipe(Hi(([e])=>e!==Fl)),S=S.pipe(Oi(e=>e.map(([e,t])=>[e,+(t>0)])));let C=f.childCorrelationField.path[0],w=f.query.from.type===`collectionRef`?f.query.from.collection:void 0,T=Wc(f.query,f.query.from,C,f.childCorrelationField,w,v);if(T.length>0){for(let e of T)a.add(e.sourceId);for(let e of T){let t=e.path[0];t&&ur(t,e.path,e.collection)}let t=Eu(e,f.correlationField),n=T.map(e=>ul(i,e,t)),r=new Map;S=S.pipe(Bi(e=>{for(let[[t],n]of e.getInner()){if(t==null)continue;let e=U(t),i=(r.get(e)?.weight??0)+n;i===0?r.delete(e):r.set(e,{key:t,weight:i})}let t=new Set([...r.values()].filter(({weight:e})=>e>0).map(({key:e})=>e));for(let e=0;e<T.length;e++){let r=T[e],a=n[e];i[r.sourceId]?.setDemand?.(a,t)}}))}let E=Hl(f.parentFilters&&f.parentFilters.length>0?{...f.query,where:[...f.query.where||[],...f.parentFilters]}:f.query,g,n,r,i,a,o,s,c,l,S,f.childCorrelationField);Object.assign(_,E.aliasToCollectionId),Object.assign(v,E.aliasRemapping);for(let[e,t]of E.sourceWhereClauses)m.set(e,t);if(j.push({pipeline:E.pipeline,fieldName:t,resultPath:d,correlationField:f.correlationField,childCorrelationField:f.childCorrelationField,hasOrderBy:!!(f.query.orderBy&&f.query.orderBy.length>0),childCompilationResult:E,parentProjection:f.parentProjection,materialization:f.materialization,scalarField:f.scalarField}),x.length>0){let e=y,n=b;M.push({fieldName:t,getRouting:t=>{if(!Tu(n,t))return{active:!1,correlationKey:null,parentContext:null};let r=Rl(t,x);return{active:!0,correlationKey:e(t),parentContext:r}}})}else{let e=b;M.push({fieldName:t,getRouting:t=>Tu(e,t)?{active:!0,correlationKey:y(t),parentContext:null}:{active:!1,correlationKey:null,parentContext:null}})}h={...h,select:bu(h.select,d)}}}if(h.distinct&&!h.fnSelect&&!h.select&&h.from.type!==`unionAll`)throw new jt;if(h.fnSelect&&h.groupBy&&h.groupBy.length>0)throw new Mt;O=h.fnSelect?O.pipe(W(([e,t])=>{let n=h.fnSelect(t);Ll(n);let r=n;if(n&&typeof n==`object`){r=Array.isArray(n)?[...n]:{...n};let e=t[Nl];e&&(r[Nl]=e),T.length>0&&Object.defineProperty(r,Pl,{value:{sourceRow:t,fnSelect:h.fnSelect},enumerable:!0,configurable:!0})}return[e,{...t,$selected:r}]})):h.select?Tl(O,h.select):O.pipe(W(([e,t])=>{let n=al(t),r=E&&n?n.value:!E&&!h.join&&!h.groupBy?t[b]:t;return[e,{...t,$selected:r}]})),M.length>0&&(O=O.pipe(W(([e,t])=>{let n={};for(let{fieldName:e,getRouting:r}of M)n[e]=r(t);let r=Array.isArray(t.$selected)?[...t.$selected]:{...t.$selected};return r[Nl]=n,[e,{...t,$selected:r}]})));let N=u?b:void 0;if(h.groupBy&&h.groupBy.length>0?O=qa(O,h.groupBy,h.having,h.select,h.fnHaving,x,N):h.select&&Object.values(h.select).some(e=>e.type===`agg`||Qa(e))&&(O=qa(O,[],h.having,h.select,h.fnHaving,x,N)),h.having&&(!h.groupBy||h.groupBy.length===0)&&!(h.select&&Object.values(h.select).some(e=>e.type===`agg`)))throw new Ft;if(h.fnHaving&&h.fnHaving.length>0&&(!h.groupBy||h.groupBy.length===0))for(let e of h.fnHaving)O=O.pipe(Hi(([t,n])=>e(n)));(!h.select||!Qa(h.select))&&(O=Gl(O,h,b,u!==void 0));let P=Ul(e,m,v);if(h.distinct&&(O=O.pipe(Qi(([e,t])=>t.$selected))),h.orderBy&&h.orderBy.length>0){let t=u&&(h.limit!==void 0||h.offset!==void 0)?(e,t)=>{let n=t?.[b]?.__correlationKey??t?.__correlationKey,r=t?.__parentContext;return r==null?n:U([n,r])}:void 0,r={collectionId:x,pipeline:co(e,O,h.orderBy,h.select||{},n[x],o,s,h.limit,h.offset,t).pipe(W(([e,[t,n]])=>{let r=t.$selected,i=tu(eu(r),t);if(u){let r=t[b]?.__correlationKey??t.__correlationKey,a=t.__parentContext??null,o=ru(t,b,e);return[e,[nu(i),n,r,a,o]]}return[e,[i,n]]})),sourceWhereClauses:P,aliasToCollectionId:_,aliasRemapping:v,includes:j.length>0?j:void 0};return u===void 0&&c.set(e,r),r}if(h.limit!==void 0||h.offset!==void 0)throw new It;let ee={collectionId:x,pipeline:O.pipe(W(([e,t])=>{let n=t.$selected,r=tu(eu(n),t);if(u){let n=t[b]?.__correlationKey??t.__correlationKey,i=t.__parentContext??null,a=ru(t,b,e);return[e,[nu(r),void 0,n,i,a]]}return[e,[r,void 0]]})),sourceWhereClauses:P,aliasToCollectionId:_,aliasRemapping:v,includes:j.length>0?j:void 0};return u===void 0&&c.set(e,ee),ee}function Ul(e,t,n){let r=Ae(e),i=new Set(r.map(({sourceId:e})=>e)),a=new Map;for(let[e,o]of t){if(i.has(e)){a.set(e,o);continue}let t=n[e]??e;for(let e of r)e.alias===t&&a.set(e.sourceId,o)}return a}function Wl(e,t){for(let n of Ae(e)){let e=t[n.sourceId]??t[n.alias];e&&(t[n.sourceId]=e,t[n.alias]=e)}}function Gl(e,t,n,r){let i=(t.orderBy??[]).map(({expression:e})=>H(e)),a=e=>({value:e.$selected,routing:e.$selected?.[Nl],outerCorrelation:r?e[n]?.__correlationKey??e.__correlationKey:void 0,parentContext:r?e.__parentContext??e[n]?.__parentContext??null:void 0,order:i.map(t=>t(e))});return e.pipe(Oi(e=>{let t=e.reduce((e,[,t])=>e+t,0);if(t===0)return[];if(t<0)throw Error(`Query row has negative multiplicity`);let n=e.find(([,e])=>e>0)?.[0];if(!n)throw Error(`Query row has no positive contributor`);let r=a(n);for(let[t,n]of e)if(n>0&&!B(r,a(t)))throw Error(`Query contributors with the same row key are not congruent`);return[[n,1]]}))}function Kl(e){let t=new Set;for(let n of au(e.from))n.type===`collectionRef`&&t.add(n.alias);if(e.join)for(let n of e.join)n.from.type===`collectionRef`&&t.add(n.from.alias);return t}function ql(e,t=new Set){let n=Kl(e);for(let e of n)if(t.has(e))throw new Rt(e,Array.from(t));let r=new Set([...t,...n]);if(e.from.type===`unionAll`)for(let t of e.from.queries)ql(t,r);else for(let t of au(e.from))t.type===`queryRef`&&ql(t.query,r);if(e.join)for(let t of e.join)t.from.type===`queryRef`&&ql(t.from.query,r);if(e.select)for(let{subquery:t}of pu(e.select))ql(t.query,r)}function Jl(e,t,n,r,i,a,o,s,c,l,u,d,f,p){if(e.type===`unionAll`)return Yl(e,t,n,r,i,a,o,s,c,l,u,d,f,p);if(e.type!==`unionFrom`){let{alias:m,input:h,collectionId:g,sourceIncludes:_,isParentRouted:v}=Ql(e,t,n,r,i,a,o,s,c,l,u,d,f,p);return{alias:m,pipeline:Xl(h,m),collectionId:g,sources:{[m]:h},sourceIncludes:_,directIncludes:[],isUnionFrom:!1,isParentRouted:v}}if(e.sources.length===0)throw new zt(`empty unionFrom`);let m={},h=[],g,_=``,v=``;for(let y of e.sources){let{alias:e,input:b,collectionId:x,sourceIncludes:S,isParentRouted:C}=Ql(y,t,n,r,i,a,o,s,c,l,u,d,f,p);_||(_=e,v=x),m[e]=b,h.push(...S);let w=(p&&!C?zl(Xl(b,e),p,e):Xl(b,e)).pipe(W(([t,n])=>{let r=`${e}:${Zl(t)}`,i=n[e]?.[rl]??t,a=`${e}:${Zl(i)}`;return[r,p?{...n,[rl]:a,[e]:{...n[e],[rl]:a}}:n]}));g=g?g.pipe(Wi(w)):w}return{alias:_,pipeline:g,collectionId:v,sources:m,sourceIncludes:h,directIncludes:[],isUnionFrom:!0,isParentRouted:p!==void 0}}function Yl(e,t,n,r,i,a,o,s,c,l,u,d,f,p){if(e.queries.length===0)throw new zt(`empty unionAll`);let m={},h=[],g=[],_,v=``,y=new Set;for(let h=0;h<e.queries.length;h++){let b=e.queries[h];for(let e of ou(b)){if(y.has(e.alias))throw Error(`Duplicate source alias "${e.alias}" in unionAll query branches. Use distinct aliases in each branch before passing them to unionAll().`);y.add(e.alias)}let x=Hl(b,t,n,r,i,a,o,s,c,l,p);v||=x.collectionId,Object.assign(u,x.aliasToCollectionId),Object.assign(d,x.aliasRemapping),g.push(...x.includes??[]),Object.assign(m,t);for(let[e,t]of x.sourceWhereClauses)f.set(e,t);let S=x.pipeline.pipe(W(e=>{let[t,[n,r,i,a,o]]=e,s=`${h}:${Zl(t)}`,c=`${h}:${Zl(o??t)}`;return[s,p?il(n,i,a,c):n]}));_=_?_.pipe(Wi(S)):S}return{alias:``,pipeline:_,collectionId:v,sources:m,sourceIncludes:h,directIncludes:g,isUnionFrom:!0,isParentRouted:p!==void 0}}function Xl(e,t){return e.pipe(W(([e,n])=>{let r=n,i=al(r);if(i){let n={[t]:i.value,__correlationKey:i.correlationKey,__parentContext:i.parentContext,[rl]:i.publicKey};return i.parentContext!=null&&typeof i.parentContext==`object`&&Object.assign(n,i.parentContext),[e,n]}if(typeof r!=`object`||!r)return[e,{[t]:r}];let{__parentContext:a,...o}=n,s={[t]:o};return a&&(Object.assign(s,a),s.__parentContext=a),[e,s]}))}function Zl(e){return typeof e==`string`?`string:${e}`:typeof e==`number`?`number:${String(e)}`:typeof e==`bigint`?`bigint:${String(e)}`:`${typeof e}:${JSON.stringify(e)}`}function Ql(e,t,n,r,i,a,o,s,c,l,u,d,f,p){switch(e.type){case`collectionRef`:{let n=t[e.sourceId]??t[e.alias];if(!n)throw new Lt(e.alias,e.collection.id,Object.keys(t));return u[e.alias]=e.collection.id,{alias:e.alias,input:n,collectionId:e.collection.id,sourceIncludes:[],isParentRouted:!1}}case`queryRef`:{let m=Hl(l.get(e.query)||e.query,t,n,r,i,a,o,s,c,l,p);Object.assign(u,m.aliasToCollectionId),Object.assign(d,m.aliasRemapping);let h=l.has(e.query),g=su(e.query.from);if(!(!h&&e.alias===g))for(let[e,t]of m.sourceWhereClauses)f.set(e,t);let _=Object.keys(m.aliasToCollectionId).find(e=>m.aliasToCollectionId[e]===m.collectionId);_&&_!==e.alias&&(d[e.alias]=_);let v=m.pipeline.pipe(W(e=>{let[t,[n,r,i,a,o]]=e;return[t,il(eu(n),i,a,o)]}));return{alias:e.alias,input:v,collectionId:m.collectionId,sourceIncludes:m.includes?.map(t=>({sourceAlias:e.alias,include:t}))??[],isParentRouted:p!==void 0}}default:throw new zt(e.type)}}function $l(e){return e instanceof we||e&&typeof e==`object`&&`type`in e&&e.type===`val`}function eu(e){return $l(e)?e.value:e}function tu(e,t){if(!e||typeof e!=`object`)return e;let n=!1;for(let r of Hn)if(e[r]==null&&r in t){n=!0;break}if(!n)return e;let r=Array.isArray(e)?[...e]:{...e};for(let n of Hn)e[n]==null&&n in t&&(r[n]=t[n]);return r}function nu(e){if(!e||typeof e!=`object`||!(`__correlationKey`in e)&&!(`__parentContext`in e)&&!(rl in e))return e;let t=Array.isArray(e)?[...e]:{...e};return delete t.__correlationKey,delete t.__parentContext,delete t[rl],t}function ru(e,t,n){return e[t]?.[rl]??e[rl]??n}function iu(e,t,n){if(fu(e.from,t.from,n),e.join&&t.join)for(let r=0;r<e.join.length&&r<t.join.length;r++){let i=e.join[r],a=t.join[r];i.from.type===`queryRef`&&a.from.type===`queryRef`&&(n.set(i.from.query,a.from.query),iu(i.from.query,a.from.query,n))}}function au(e){return e.type===`unionFrom`?e.sources:e.type===`unionAll`?[]:[e]}function ou(e){return[...au(e.from),...e.join?.map(e=>e.from)??[]]}function su(e){return au(e)[0]?.alias??``}function cu(e,t,n){return uu(e,[t,...n])}function lu(e,t){return uu(e,t)}function uu(e,t){let n=[],r=(e,t,n)=>{for(let[r,o]of Object.entries(e)){if(r.startsWith(`__SPREAD_SENTINEL__`)){i(r,o,t,n);continue}a(o,[...t,r],n)}},i=(e,r,i,a)=>{let o=e.slice(19),s=o.lastIndexOf(`__`),c=s>=0?o.slice(0,s):o,l=r&&typeof r==`object`&&`type`in r&&r.type===`ref`?r.path:c.split(`.`).filter(Boolean);du(t,l)&&n.push({path:[...i,...t.slice(l.length)],guards:a})},a=(e,i,o)=>{if(e instanceof z&&du(t,e.path)){n.push({path:[...i,...t.slice(e.path.length)],guards:o});return}if(e instanceof Oe){let t=[];for(let n of e.branches)a(n.value,i,[...o,...t,{condition:n.condition,expected:!0}]),t.push({condition:n.condition,expected:!1});e.defaultValue!==void 0&&a(e.defaultValue,i,[...o,...t]);return}vu(e)&&r(e,i,o)};return r(e,[],[]),n}function du(e,t){return t.length<=e.length&&t.every((t,n)=>e[n]===t)}function fu(e,t,n){if(e.type===`unionAll`&&t.type===`unionAll`){for(let r=0;r<e.queries.length&&r<t.queries.length;r++){let i=e.queries[r],a=t.queries[r];n.set(i,a),iu(i,a,n)}return}let r=au(e),i=au(t);for(let e=0;e<r.length&&e<i.length;e++){let t=r[e],a=i[e];t.type===`queryRef`&&a.type===`queryRef`&&(n.set(t.query,a.query),iu(t.query,a.query,n))}}function pu(e){let t=[];for(let[n,r]of Object.entries(e))n.startsWith(`__SPREAD_SENTINEL__`)||(r instanceof De?t.push({key:gu([n],t),path:[n],subquery:r,guards:[]}):r instanceof Oe?mu(r,[n],[],t):vu(r)&&yu(r,n));return t}function mu(e,t,n,r){let i=[];for(let a of e.branches)hu(a.value,t,[...n,...i,{condition:a.condition,expected:!0}],r),i.push({condition:a.condition,expected:!1});e.defaultValue!==void 0&&hu(e.defaultValue,t,[...n,...i],r)}function hu(e,t,n,r){if(e instanceof De){let i=gu(t,r);r.push({key:i,path:t,subquery:e,guards:n});return}if(e instanceof Oe){mu(e,t,n,r);return}if(vu(e))for(let[i,a]of Object.entries(e))i.startsWith(`__SPREAD_SENTINEL__`)||hu(a,[...t,i],n,r)}function gu(e,t){return _u(e.join(`.`),t)}function _u(e,t){let n=e=>t.some(t=>(t.key??t.fieldName)===e);if(!n(e))return e;let r=t.length,i=`${e}#${r}`;for(;n(i);)r++,i=`${e}#${r}`;return i}function vu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!ke(e)&&e.__refProxy!==!0}function yu(e,t){for(let[n,r]of Object.entries(e))if(!n.startsWith(`__SPREAD_SENTINEL__`)){if(r instanceof De)throw Error(`Includes subqueries must be at the top level of select(). Found nested includes at "${t}.${n}".`);vu(r)&&yu(r,`${t}.${n}`)}}function bu(e,t){return xu(e,t,new we(null)).value}function xu(e,t,n){if(t.length===0)return Su(e,n);if(e instanceof Oe)return Cu(e,t,n);if(!vu(e))return{value:e,replaced:!1};if(t.length===1){let r=t[0],i=Su(e[r],n);return i.replaced?{value:{...e,[r]:i.value},replaced:!0}:{value:e,replaced:!1}}let[r,...i]=t,a=xu(e[r],i,n);return a.replaced?{value:{...e,[r]:a.value},replaced:!0}:{value:e,replaced:!1}}function Su(e,t){return e instanceof De?{value:t,replaced:!0}:e instanceof Oe?Cu(e,[],t):{value:e,replaced:!1}}function Cu(e,t,n){let r=!1,i=e.branches.map(e=>{let i=t.length===0?Su(e.value,n):xu(e.value,t,n);return i.replaced?(r=!0,{...e,value:i.value}):e}),a=e.defaultValue;if(e.defaultValue!==void 0){let i=t.length===0?Su(e.defaultValue,n):xu(e.defaultValue,t,n);i.replaced&&(r=!0,a=i.value)}return r?{value:new Oe(i,a),replaced:!0}:{value:e,replaced:!1}}function wu(e,t){let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}function Tu(e,t){return e.every(e=>Rn(e.condition(t))===e.expected)}function Eu(e,t){let n=[],r=e=>{if(e.type!==`func`)return;if(e.name===`and`){e.args.forEach(r);return}if(e.name!==`eq`&&e.name!==`in`)return;let[i,a]=e.args,o=i?.type===`ref`&&Du(i.path,t.path)&&a instanceof we?a.value:a?.type===`ref`&&Du(a.path,t.path)&&i instanceof we?i.value:void 0;o!==void 0&&n.push(new Set(Array.isArray(o)?o:[o]))};return e.where?.forEach(e=>r(je(e))),n.length===0?new Set:new Set([...n[0]].filter(e=>n.slice(1).every(t=>t.has(e))))}function Du(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Ou(e,t){let n=e.type;if(n===`val`)return new we(e.value);if(n===`ref`){let n=e.path;if(Array.isArray(n)){if(n[0]===t&&n.length>1)return new z(n.slice(1));if(n.length===1&&n[0]!==void 0)return new z([n[0]])}return new z(Array.isArray(n)?n:[String(n)])}{let n=[];for(let r of e.args){let e=Ou(r,t);n.push(e)}return new Te(e.name,n)}}function ku(e,t){return e.map(e=>{let n=Ou(e.expression,t);return{...e,expression:n}})}function Au(e){let t={};for(let n of Ae(e))t[n.collection.id]=n.collection;return t}function ju(e){let t=e.from;if(t.type===`collectionRef`)return t.collection;if(t.type===`queryRef`)return ju(t.query);if(t.type===`unionFrom`)return ju({from:t.sources[0]});if(t.type===`unionAll`)return ju(t.queries[0]);throw Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(e)}`)}function Mu(e){return!(typeof e!=`object`||!e||ke(e)||e.__refProxy)}function Nu(e){let t=typeof e.query==`function`?Hc(e.query):Uc(e.query);if(e.requireObjectResult&&t.select&&!Mu(t.select))throw new Pt;return t}function Pu(e,t){let n=[];for(let e of t){let t=e.key;e.type===`insert`?n.push([[t,e.value],1]):e.type===`update`?(n.push([[t,e.previousValue],-1]),n.push([[t,e.value],1])):n.push([[t,e.value],-1])}return n.length!==0&&e.sendData(new ui(n)),n.length}function*Fu(e){for(let t of e)t.type===`update`?(yield{type:`delete`,key:t.key,value:t.previousValue},yield{type:`insert`,key:t.key,value:t.value}):yield t}function Iu(e,t){let n=[];for(let r of e){if(r.type===`insert`){if(t.has(r.key))continue;t.add(r.key)}else r.type===`delete`&&t.delete(r.key);n.push(r)}return n}function Lu(e,t,n,r){let i=t,a=!1;for(let t of e){if(t.type===`delete`)continue;let e=!n.has(t.key);i===void 0||r(i,t.value)<0?(i=t.value,a=!0):e&&(a=!0)}return{biggest:i,shouldResetLoadKey:a}}function Ru(e,t){let{orderBy:n,limit:r,offset:i}=e,a=r!==void 0&&i!==void 0?r+i:r,o=n?ku(n,t):void 0,s=o?.every(e=>{let t=e.expression;if(t.type!==`ref`)return!1;let n=t.path;return Array.isArray(n)&&n.length===1})??!1;return{orderBy:s?o:void 0,limit:s?a:void 0}}function zu(e,t,n,r,i){let{orderBy:a,valueExtractorForRawRow:o,offset:s}=e,c=t?o(t):void 0,l;c!==void 0&&(l=Array.isArray(c)?c:[c]);let u=U({minValues:l??null,offset:s,limit:i});if(n===u)return;let d=ku(a,r);return{minValues:l,normalizedOrderBy:d,loadRequestKey:u}}var Bu=class{constructor(){this.states=new Map,this.warnedPlans=new Set}setDemand(e,t,n){let r=Vu(n),i=this.states.get(t.id),a=i?.segments.some(e=>e.state===`failed`&&Uu(e.keys,r));if(i&&Hu(i.keys,r)&&!a)return{changed:!1,empty:r.size===0,ready:!0};let o=[];for(let t of i?.segments??[]){if(t.state!==`failed`&&Uu(t.keys,r)){o.push(t);continue}t.abortController.abort(),e.releaseSnapshot(t.where)}let s=new Set(o.flatMap(e=>[...e.keys.keys()])),c=new Map([...r].filter(([e])=>!s.has(e)));c.size>0&&o.push(Wu(e,t,c,()=>this.warnUnoptimized(t))),r.size===0?this.states.delete(t.id):this.states.set(t.id,{keys:r,segments:o});let l=o.filter(e=>Uu(e.keys,r)).map(e=>e.ready).filter(e=>e instanceof Promise);return{changed:!0,empty:r.size===0,ready:l.length>0?Promise.all(l).then(()=>void 0):!0}}clear(){for(let e of this.states.values())for(let t of e.segments)t.abortController.abort();this.states.clear(),this.warnedPlans.clear()}warnUnoptimized(e){if(this.warnedPlans.has(e.id))return;this.warnedPlans.add(e.id);let t=e.path.join(`.`);console.warn(`[TanStack DB]${e.collectionId?` [${e.collectionId}]`:``} Join requires an index on "${t}" for efficient loading. Falling back to scanning local data. Consider creating an index on the collection with collection.createIndex((row) => row.${t}) or enable auto-indexing with autoIndex: 'eager' and a defaultIndexType.`)}};function Vu(e){return new Map([...e].map(e=>[U(e),e]))}function Hu(e,t){return e.size===t.size&&[...e.keys()].every(e=>t.has(e))}function Uu(e,t){return[...e.keys()].some(e=>t.has(e))}function Wu(e,t,n,r){let i=Po(new z(t.path),[...n.values()]),a=new AbortController,o={ready:!0};e.requestSnapshot({where:i,signal:a.signal,trackLoadSubsetPromise:!1,onUnoptimized:r,onLoadSubsetResult:e=>{o.ready=e}});let s=o.ready,c={keys:n,where:i,abortController:a,ready:s,state:s instanceof Promise?`pending`:`settled`};return s instanceof Promise&&s.then(()=>{c.state=`settled`},()=>{c.state=`failed`}),c}var Gu=Symbol.for(`@tanstack/db.collection-config-builder`),Ku=class{constructor(e,t,n,r){this.sourceId=e,this.alias=t,this.collection=n,this.collectionConfigBuilder=r,this.biggest=void 0,this.subscriptionLoadingPromises=new Map,this.sentToD2Keys=new Set,this.demand=new Bu}subscribe(){let e=this.getWhereClause();if(e){let t=Ou(e,this.alias);return this.subscribeToChanges(t)}return this.subscribeToChanges()}subscribeToChanges(e){let t=this.getOrderByInfo(),n=!this.collectionConfigBuilder.isLazySource(this.sourceId),r=e=>{if(e instanceof Promise){let t=e.catch(async e=>{throw await Promise.resolve(),e});this.collectionConfigBuilder.trackSubsetLoadPromise(t),n&&e.then(()=>{n=!1},()=>{})}else n=!1},i=e=>{if(this.collectionConfigBuilder.isLazySource(this.sourceId))return;let t=e.subscription;if(e.status===`loadingSubset`)this.ensureLoadingPromise(t);else{let e=this.subscriptionLoadingPromises.get(t);e&&(this.subscriptionLoadingPromises.delete(t),e.resolve())}},a=e=>{this.collectionConfigBuilder.recordSubsetError(e.error,n)},o;if(t)o=this.subscribeToOrderedChanges(e,t,i,r,a);else{let t=!this.collectionConfigBuilder.isLazySource(this.sourceId);o=this.subscribeToMatchingChanges(e,t,i,r,a),this.registerSubscriptionCleanup(o)}return!this.collectionConfigBuilder.isLazySource(this.sourceId)&&o.status===`loadingSubset`&&this.ensureLoadingPromise(o),o}registerSubscriptionCleanup(e){this.collectionConfigBuilder.currentSyncState.unsubscribeCallbacks.add(()=>{let t=this.subscriptionLoadingPromises.get(e);t&&(this.subscriptionLoadingPromises.delete(e),t.resolve()),this.demand.clear(),e.unsubscribe()})}setDemand(e,t,n){let r;try{r=this.demand.setDemand(e,t,n)}catch(n){if(e.lastError!==n)throw n;let r=this.collectionConfigBuilder.liveQueryCollection?.status===`loading`,i=this.collectionConfigBuilder.beginDemand(t.id);if(this.collectionConfigBuilder.failDemand(t.id,i,n),r)throw n;return}if(!r.changed)return;if(r.empty){this.collectionConfigBuilder.retireDemand(t.id);return}let i=this.collectionConfigBuilder.beginDemand(t.id);r.ready instanceof Promise?(this.collectionConfigBuilder.trackSubsetLoadOperationPromise(r.ready),r.ready.then(()=>this.collectionConfigBuilder.settleDemand(t.id,i),e=>this.collectionConfigBuilder.failDemand(t.id,i,e))):this.collectionConfigBuilder.settleDemand(t.id,i)}sendChangesToPipeline(e,t){let n=Iu(Array.isArray(e)?e:[...e],this.sentToD2Keys),r=this.collectionConfigBuilder.currentSyncState.inputs[this.sourceId],i=Pu(r,n)>0?t:void 0;this.collectionConfigBuilder.scheduleGraphRun(i,{sourceId:this.sourceId})}subscribeToMatchingChanges(e,t,n,r,i){let a=e=>{this.sendChangesToPipeline(e)},o=Ru(this.collectionConfigBuilder.query,this.alias);return this.collection.subscribeChanges(a,{...t&&{includeInitialState:t},whereExpression:e,onStatusChange:n,onLoadSubsetError:i,orderBy:o.orderBy,limit:o.limit,onLoadSubsetResult:t?r:void 0})}subscribeToOrderedChanges(e,t,n,r,i){let{orderBy:a,offset:o,limit:s,index:c}=t,l=e=>{if(e instanceof Promise){this.pendingOrderedLoadPromise=e;let t=()=>{this.pendingOrderedLoadPromise===e&&(this.pendingOrderedLoadPromise=void 0)};e.then(t,t)}r(e)};this.orderedLoadSubsetResult=l;let u={},d=this.collection.subscribeChanges(e=>{let n=Array.isArray(e)?e:[...e];this.trackSentValues(n,t.comparator);let r=Fu(n);this.sendChangesToPipelineWithTracking(r,u.current)},{whereExpression:e,onStatusChange:n,onLoadSubsetError:i});u.current=d,this.registerSubscriptionCleanup(d);let f=this.collection.on(`truncate`,()=>{this.biggest=void 0,this.lastLoadRequestKey=void 0,this.pendingOrderedLoadPromise=void 0,this.sentToD2Keys.clear()});d.on(`unsubscribed`,()=>{f()});let p=ku(a,this.alias);return c?(d.setOrderByIndex(c),d.requestLimitedSnapshot({limit:o+s,orderBy:p,trackLoadSubsetPromise:!1,onLoadSubsetResult:l})):d.requestSnapshot({orderBy:p,limit:o+s,trackLoadSubsetPromise:!1,onLoadSubsetResult:l}),d}loadMoreIfNeeded(e){let t=this.getOrderByInfo();if(!t)return!0;let{dataNeeded:n,index:r}=t;if(!n||!r)return!0;let i=n();if(i>0){if(this.pendingOrderedLoadPromise)return this.collectionConfigBuilder.trackSubsetLoadOperationPromise(this.pendingOrderedLoadPromise),!0;try{this.loadNextItems(i,e)}catch(t){if(e.lastError!==t)throw t}}return!0}sendChangesToPipelineWithTracking(e,t){if(!this.getOrderByInfo()){this.sendChangesToPipeline(e);return}let n=t;n[Gu]??=this.loadMoreIfNeeded.bind(this,t),this.sendChangesToPipeline(e,n[Gu])}loadNextItems(e,t){let n=this.getOrderByInfo();if(!n)return;let r=zu(n,this.biggest,this.lastLoadRequestKey,this.alias,e);if(!r)return;let i=r.loadRequestKey;this.lastLoadRequestKey=i;try{t.requestLimitedSnapshot({orderBy:r.normalizedOrderBy,limit:e,minValues:r.minValues,trackLoadSubsetPromise:!1,onLoadSubsetResult:e=>{e instanceof Promise&&e.then(void 0,()=>{this.lastLoadRequestKey===i&&(this.lastLoadRequestKey=void 0)}),this.orderedLoadSubsetResult?.(e)}})}catch(e){throw this.lastLoadRequestKey===i&&(this.lastLoadRequestKey=void 0),e}}getWhereClause(){let e=this.collectionConfigBuilder.sourceWhereClausesCache;if(e)return e.get(this.sourceId)}getOrderByInfo(){let e=this.collectionConfigBuilder.optimizableOrderByCollections[this.sourceId];if(e?.sourceId===this.sourceId)return e}trackSentValues(e,t){let n=Lu(e,this.biggest,this.sentToD2Keys,t);this.biggest=n.biggest,n.shouldResetLoadKey&&(this.lastLoadRequestKey=void 0)}ensureLoadingPromise(e){if(this.subscriptionLoadingPromises.has(e))return;let t,n=new Promise(e=>{t=e});this.subscriptionLoadingPromises.set(e,{resolve:t}),this.collectionConfigBuilder.trackSubsetLoadPromise(n)}},qu=Symbol(`bucketFacadeRef`),Ju=0;function Yu(e,t,n=!1){if(!e.includes?.length&&!(t&&n))return{pipeline:e.pipeline,facades:[]};let r=Xu(e,t,new WeakMap,`root`);return{...r,facades:Zu(r.facades)}}function Xu(e,t,n,r){let i=n.get(e)?.[r];if(i)return i;let a=$u(Qu(e.pipeline),t,r),o=[];for(let t of e.includes??[]){let e=Xu(t.childCompilationResult,void 0,n,`child`);o.push(...e.facades);let i=nd(e.pipeline);if(t.materialization===`collection`){let e=`bucket-facade-${++Ju}`,n=id(a,t),s=n.pipe(Xi(i),W(([e,[,t]])=>[e,t]));o.push({edgeId:e,rows:s,activeBuckets:n,hasOrderBy:t.hasOrderBy}),a=rd(a,t,e,r)}else a=td(a,i,t,r)}let s={pipeline:a,facades:o};return n.set(e,{...n.get(e),[r]:s}),s}function Zu(e){return[...new Map(e.map(e=>[e.edgeId,e])).values()]}function Qu(e){return e.pipe(W(([e,t])=>{let n=t;return[e,[n[0],n[1],n[2],n[3],n[0][Nl],n[4]]]}))}function $u(e,t,n){return e.pipe(W(([e,r])=>{let i=r,a=t?t(i[0]):i[5]??e;return[U(n===`root`?[`root`,a]:[sd(i[2],i[3]),a]),{publicKey:a,tuple:i}]}),Oi(e=>{let t=e.reduce((e,[,t])=>e+t,0);if(t===0)return[];if(t<0)throw Error(`Canonical query row has negative multiplicity`);let n=e.find(([,e])=>e>0)?.[0];if(!n)throw Error(`Canonical query row has no positive contributor`);for(let[t,r]of e)r<=0||ed(n,t);return[[n,1]]}),W(([e,{publicKey:t,tuple:r}])=>[n===`root`?t:e,r]))}function ed(e,t){let[n,r,i,a,o]=e.tuple,[s,c,l,u,d]=t.tuple;if(r!==c||!B(n,s)||!B(i,l)||!B(a,u)||!B(o,d))throw Error(`Query contributors for public key ${U(e.publicKey)} are not congruent`)}function td(e,t,n,r){let i=t.pipe(Oi(e=>{let t=[];for(let[n,r]of e){if(r<0)throw Error(`Materialization bucket row has negative multiplicity`);for(let e=0;e<r;e++)t.push(n)}return t.length===0?[]:(t.sort(cd),[[{value:ld(t,n)},1]])}));return $u(e.pipe(W(([e,t])=>{let r=t,i=od(r,n.fieldName);return[i?.active===!0?sd(i.correlationKey,i.parentContext):`inactive:${U(e)}`,{parentKey:e,tuple:r}]}),Xi(i,`left`),W(([e,[t,r]])=>{let[i,a,o,s,c,l]=t.tuple;if(c?.[n.fieldName]?.active!==!0)return[t.parentKey,[i,a,o,s,c,l]];let u=r===null?ud(n.materialization):r.value;return[t.parentKey,[fd(i,n.resultPath,u),a,o,s,c,l]]})),void 0,r)}function nd(e){return e.pipe(W(([e,t])=>{let[n,r,i,a,,o]=t;return[sd(i,a),{publicKey:o??e,value:n,order:r}]}))}function rd(e,t,n,r){return $u(e.pipe(W(([e,r])=>{let i=r,a=od(i,t.fieldName);if(a?.active!==!0)return[e,i];let o=ad(n,sd(a.correlationKey,a.parentContext));return[e,[fd(i[0],t.resultPath,o),i[1],i[2],i[3],i[4],i[5]]]})),void 0,r)}function id(e,t){return e.pipe(W(([e,n])=>{let r=od(n,t.fieldName);return[e,r?.active===!0?sd(r.correlationKey,r.parentContext):void 0]}),Hi(([,e])=>e!==void 0),Qi(([,e])=>e),W(([,e])=>[e,!0]))}function ad(e,t){return{[qu]:{edgeId:e,bucketKey:t}}}function od(e,t){return e[4]?.[t]}function sd(e,t){return U([e??null,t??null])}function cd(e,t){if(e.order!==t.order)return e.order===void 0?1:t.order===void 0||e.order<t.order?-1:1;if((typeof e.publicKey==`string`||typeof e.publicKey==`number`)&&(typeof t.publicKey==`string`||typeof t.publicKey==`number`))return br(e.publicKey,t.publicKey);let n=U(e.publicKey),r=U(t.publicKey);return n<r?-1:+(n>r)}function ld(e,t){let n=t.scalarField,r=n?e.map(({value:e})=>e[n]):e.map(({value:e})=>e);return t.materialization===`array`?r:t.materialization===`singleton`?r[0]:r.map(e=>String(e??``)).join(``)}function ud(e){if(e===`array`)return[];if(e===`concat`)return``;if(e!==`singleton`)throw Error(`Collection includes require a bucket facade`)}function dd(e,t,n){let r={...e},i=r,a=e;for(let e=0;e<t.length-1;e++){let n=t[e],r=a?.[n],o=Array.isArray(r)?[...r]:{...r??{}};i[n]=o,i=o,a=r}return i[t[t.length-1]]=n,r}function fd(e,t,n){let r=e[Pl];if(!r)return dd(e,t,n);let i=dd(r.sourceRow,t,n),a=r.fnSelect(i);if(Ll(a),!a||typeof a!=`object`)throw Error(`fn.select must return an object when it projects includes`);let o=Array.isArray(a)?[...a]:{...a};for(let t of Hn)t in e&&!(t in o)&&(o[t]=e[t]);return o[Nl]=e[Nl],Object.defineProperty(o,Pl,{value:{sourceRow:i,fnSelect:r.fnSelect},enumerable:!0,configurable:!0}),o}var pd=class{constructor(e,t,n){this.parentId=e,this.compilations=t,this.pending=new Map,this.pendingActivity=new Map,this.activeBuckets=new Map,this.entries=new Map,this.retiredEntries=new Map,this.resolvedValues=new WeakMap;for(let e of t)e.rows.pipe(Ki(t=>{let r=t.getInner();n(r.length);for(let[[t,n],i]of r)this.accumulate(e.edgeId,t,n,i)})),e.activeBuckets.pipe(Ki(t=>{let r=t.getInner();n(r.length);for(let[[t],n]of r)this.accumulateActivity(e.edgeId,t,n)}))}hasPendingChanges(){return this.pending.size>0||this.pendingActivity.size>0}flush(){let e=this.snapshot(),t=new Set,n=[],r=e=>{t.has(e)||(t.add(e),n.push(e.collection._deferPublication()))};try{for(let e of this.compilations){let t=this.pendingActivity.get(e.edgeId),n=this.getActiveBuckets(e.edgeId),i=[];for(let[r,a]of t??[])a>0&&!n.has(r)&&(n.add(r),i.push(this.getEntry(e.edgeId,r)));let a=this.pending.get(e.edgeId);for(let[t,i]of a??[]){let a=this.entries.get(e.edgeId)?.get(t);if(!n.has(t)&&!a)continue;let o=this.getEntry(e.edgeId,t),s=o.sync;if(!(!s||i.size===0)){for(let e of i.values())this.prepareChange(o,e);r(o),s.begin();for(let t of i.values())this.applyChange(o,s,t,e.hasOrderBy);s.commit()}}for(let e of i)e.sync?.markReady();for(let[i,a]of t??[])a>=0||(n.delete(i),this.retireEntry(e.edgeId,i,r))}}catch(r){this.restore(e,t),this.retiredEntries.clear();for(let e of n)e.discard();throw r}this.pending.clear(),this.pendingActivity.clear();let i=!1;return{publish:()=>{if(!i){i=!0;for(let e of n)e.publish();this.retiredEntries.clear()}},rollback:()=>{if(!i){i=!0,this.restore(e,t),this.retiredEntries.clear();for(let e of n)e.discard()}}}}resolve(e){return this.resolveValue(e)}cleanup(){for(let e of this.entries.values())for(let t of e.values())t.collection.cleanup();this.entries.clear(),this.cleanupRetiredEntries(),this.pending.clear(),this.pendingActivity.clear(),this.activeBuckets.clear()}accumulate(e,t,n,r){let i=this.pending.get(e);i||(i=new Map,this.pending.set(e,i));let a=i.get(t);a||(a=new Map,i.set(t,a));let o=U(n.publicKey),s=a.get(o)??{deletes:0,inserts:0,value:n};r<0?s.deletes+=-r:r>0&&(s.inserts+=r,s.value=n),a.set(o,s)}snapshot(){let e=new Map;for(let t of this.entries.values())for(let n of t.values())e.set(n,[...n.collection._state.syncedData].map(([e,t])=>({key:e,value:t,order:n.currentOrder.get(e)})));return{activeBuckets:new Map([...this.activeBuckets].map(([e,t])=>[e,new Set(t)])),entries:new Map([...this.entries].map(([e,t])=>[e,new Map(t)])),rows:e}}restore(e,t){let n=new Set([...e.entries.values()].flatMap(e=>[...e.values()])),r=new Set([...this.entries.values()].flatMap(e=>[...e.values()]));for(let r of t){if(!n.has(r))continue;let t=r.sync;if(t){t.begin(),t.truncate(),r.currentOrder.clear();for(let n of e.rows.get(r)??[])r.keys.set(n.value,n.key),n.order!==void 0&&r.order.set(n.value,n.order),r.currentOrder.set(n.key,n.order),t.write({type:`insert`,value:n.value});t.commit()}}this.entries.clear();for(let[t,n]of e.entries)this.entries.set(t,new Map(n));this.activeBuckets.clear();for(let[t,n]of e.activeBuckets)this.activeBuckets.set(t,new Set(n));this.resolvedValues=new WeakMap;for(let e of r)n.has(e)||e.collection.cleanup()}accumulateActivity(e,t,n){let r=this.pendingActivity.get(e);r||(r=new Map,this.pendingActivity.set(e,r)),r.set(t,(r.get(t)??0)+n)}getActiveBuckets(e){let t=this.activeBuckets.get(e);return t||(t=new Set,this.activeBuckets.set(e,t)),t}retireEntry(e,t,n){let r=this.entries.get(e),i=r?.get(t);if(!i)return;let a=i.sync,o=[...i.collection.keys()];if(a&&o.length>0){n(i),a.begin();for(let e of o)a.write({type:`delete`,key:e});a.commit()}r.delete(t),r.size===0&&this.entries.delete(e);let s=this.retiredEntries.get(e);s||(s=new Map,this.retiredEntries.set(e,s)),s.set(t,i)}getEntry(e,t){let n=this.entries.get(e);n||(n=new Map,this.entries.set(e,n));let r=n.get(t);if(r)return r;let i=new WeakMap,a=new WeakMap,o,s={collection:Is({id:`__bucket-facade:${this.parentId}:${e}:${t}`,getKey:e=>{let t=i.get(e)??e?.$key;if(typeof t!=`string`&&typeof t!=`number`)throw Error(`Bucket facade row has no public key`);return t},compare:(e,t)=>{let n=a.get(e),r=a.get(t);return n===r?0:n===void 0?1:r===void 0||n<r?-1:1},sync:{rowUpdateMode:`full`,sync:e=>(o=e,()=>{o=void 0})},startSync:!0,gcTime:0}),get sync(){return o},keys:i,order:a,currentOrder:new Map};return n.set(t,s),s}applyChange(e,t,n,r){let i=n.value.publicKey,a=e.currentOrder.get(i),o=n.value.order,s=t.collection.has(i)&&a!==o,c=this.resolve(n.value.value),l=s&&t.collection.get(i)===c?{...c}:c;if(e.keys.set(l,i),o!==void 0&&e.order.set(l,o),n.inserts>n.deletes)t.write({type:t.collection.has(i)?`update`:`insert`,value:l});else if(n.inserts===n.deletes&&t.collection.has(i))t.write({type:`update`,value:l});else if(n.deletes>0){t.write({type:`delete`,key:i}),e.currentOrder.delete(i);return}e.currentOrder.set(i,o),r&&s&&t.collection._markLayoutChange()}prepareChange(e,t){let n=t.value.publicKey,r=this.resolve(t.value.value);e.keys.set(r,n),e.collection.getKeyFromItem(r)}resolveValue(e){if(typeof e==`object`&&e){let t=this.resolvedValues.get(e);if(t!==void 0)return t}if(md(e)){let{edgeId:t,bucketKey:n}=e[qu],r=this.entries.get(t)?.get(n)?.collection??this.retiredEntries.get(t)?.get(n)?.collection??this.getEntry(t,n).collection;return this.resolvedValues.set(e,r),r}if(Array.isArray(e)){let t=[];return this.resolvedValues.set(e,t),t.push(...e.map(e=>this.resolveValue(e))),t}if(!hd(e))return e;let t={};this.resolvedValues.set(e,t);for(let n of Reflect.ownKeys(e))n!==Nl&&n!==Pl&&(t[n]=this.resolveValue(e[n]));return t}cleanupRetiredEntries(){for(let e of this.retiredEntries.values())for(let t of e.values())t.collection.cleanup();this.retiredEntries.clear()}};function md(e){return typeof e==`object`&&!!e&&qu in e}function hd(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var gd=0,_d=class{constructor(e){this.config=e,this.compiledAliasToCollectionId={},this.resultKeys=new WeakMap,this.orderByIndices=new WeakMap,this.isGraphRunning=!1,this.runCount=0,this.isInErrorState=!1,this.fatalQueryError=!1,this.erroredSourceIds=new Set,this.sourceDependencies={},this.builderDependencies=new Set,this.pendingGraphRuns=new Map,this.subscriptions={},this.lazySourcesCallbacks={},this.lazySources=new Set,this.activeDemands=new Map,this.demandGenerations=new Map,this.optimizableOrderByCollections={},this.id=e.id||`live-query-${++gd}`,this.query=Nu({query:e.query,requireObjectResult:!0}),this.initialWindow=this.query.orderBy?.length?{offset:this.query.offset??0,limit:this.query.limit??1/0}:void 0,this.collections=Au(this.query),this.collectionSources=Ae(this.query),this.collectionByAlias=Object.fromEntries(this.collectionSources.map(({alias:e,collection:t})=>[e,t])),this.query.orderBy&&this.query.orderBy.length>0&&(this.compare=vd(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??ju(this.query).compareOptions,this.compileBasePipeline()}hasJoins(e){if(e.join&&e.join.length>0)return!0;if(e.from.type===`queryRef`){if(this.hasJoins(e.from.query))return!0}else if(e.from.type===`unionFrom`){for(let t of e.from.sources)if(t.type===`queryRef`&&this.hasJoins(t.query))return!0}else if(e.from.type===`unionAll`){for(let t of e.from.queries)if(this.hasJoins(t))return!0}return!1}getConfig(){let e=this;return{id:this.id,getKey:this.config.getKey||(e=>this.resultKeys.get(e)??e.$key),sync:this.getSyncConfig(),compare:this.compare,defaultStringCollation:this.compareOptions,gcTime:this.config.gcTime??5e3,schema:this.config.schema,onInsert:this.config.onInsert,onUpdate:this.config.onUpdate,onDelete:this.config.onDelete,startSync:this.config.startSync,singleResult:this.query.singleResult,utils:{getRunCount:this.getRunCount.bind(this),get lastSubsetError(){return e.lastSubsetError},setWindow:this.setWindow.bind(this),getWindow:this.getWindow.bind(this),[Zo]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(e){if(!this.windowFn)throw new ln;let t=this.liveQueryCollection?._sync.beginLoadSubsetOperation(),n=this.currentWindow??this.initialWindow,r=this.activeWindowOperation,i={failed:!1};this.activeWindowOperation=i;try{if(this.windowFn(e),this.maybeRunGraphFn?.(),i.failed)throw i.error;this.currentWindow=e}catch(e){if(n)try{this.windowFn(n),this.maybeRunGraphFn?.()}catch{}throw t?.cancel(),e}finally{this.activeWindowOperation=r}return t?.wait()??!0}getWindow(){let e=this.currentWindow??this.initialWindow;if(!(!this.windowFn||!e))return{offset:e.offset??0,limit:e.limit??0}}getCollectionIdForAlias(e){let t=this.compiledAliasToCollectionId[e];if(t)return t;let n=this.collectionByAlias[e];if(n)return n.id;throw Error(`Unknown source alias "${e}"`)}isLazySource(e){return this.lazySources.has(e)}beginDemand(e){let t=(this.demandGenerations.get(e)??0)+1;return this.demandGenerations.set(e,t),this.activeDemands.set(e,{generation:t,settled:!1}),t}settleDemand(e,t){let n=this.activeDemands.get(e);!n||n.generation!==t||n.settled||(n.settled=!0,this.maybeRunGraphFn?.())}failDemand(e,t,n){let r=this.activeDemands.get(e);if(!r||r.generation!==t)return;this.recordSubsetError(n),this.activeWindowOperation&&(this.activeWindowOperation.failed=!0,this.activeWindowOperation.error=n);let i=n instanceof Error?n.message:String(n);this.transitionToError(`Subset demand '${e}' failed: ${i}`,n)}recordSubsetError(e,t=!1){if(this.lastSubsetError=e,this.activeWindowOperation&&(this.activeWindowOperation.failed=!0,this.activeWindowOperation.error=e),t){let t=e instanceof Error?e.message:String(e);this.transitionToError(`Initial subset load failed: ${t}`,e)}}trackSubsetLoadPromise(e){this.liveQueryCollection._sync.trackLoadPromise(e)}trackSubsetLoadOperationPromise(e){this.liveQueryCollection._sync.trackLoadSubsetOperationPromise(e)}retireDemand(e){this.activeDemands.delete(e)}maybeRunGraph(e){if(!this.isGraphRunning){if(!this.currentSyncConfig||!this.currentSyncState)throw Error(`maybeRunGraph called without active sync session. This should not happen.`);this.isGraphRunning=!0;try{let{begin:t,commit:n}=this.currentSyncConfig,r=this.currentSyncState;if(this.isInErrorState)return;if(r.subscribedToAllCollections){let i=!1;for(;r.graph.pendingWork();)r.graph.run(),e?.(),i=!0;r.flushPendingChanges?.(),i||e?.(),r.messagesCount===0&&(t(),n()),this.updateLiveQueryStatus(this.currentSyncConfig)}}finally{this.isGraphRunning=!1}}}scheduleGraphRun(e,t){let n=t?.contextId??Ms()?.id??So(),r=t?.jobId??this,i=(()=>{if(t?.dependencies)return t.dependencies;let e=new Set(this.builderDependencies);if(t?.sourceId){let n=this.sourceDependencies[t.sourceId];if(n)for(let t of n)e.add(t)}return e.delete(this),Array.from(e)})();if(n)for(let e of i)typeof e.scheduleGraphRun==`function`&&e.scheduleGraphRun(void 0,{contextId:n});if(!this.currentSyncConfig||!this.currentSyncState)throw Error(`scheduleGraphRun called without active sync session. This should not happen.`);let a=n?this.pendingGraphRuns.get(n):void 0;a||(a={loadCallbacks:new Set},n&&this.pendingGraphRuns.set(n,a)),e&&a.loadCallbacks.add(e);let o=n?void 0:a;bo.schedule({contextId:n,jobId:r,dependencies:i,run:()=>this.executeGraphRun(n,o)})}clearPendingGraphRun(e){this.pendingGraphRuns.delete(e)}hasPendingGraphRun(e){return this.pendingGraphRuns.has(e)}executeGraphRun(e,t){let n=t??(e?this.pendingGraphRuns.get(e):void 0);e&&this.pendingGraphRuns.delete(e),!(!n||!this.currentSyncConfig||!this.currentSyncState)&&(this.incrementRunCount(),this.maybeRunGraph(()=>{let e=!0,t;if(n.loadCallbacks.forEach(n=>{try{e=n()&&e}catch(n){e=!1,t??=n}}),t)throw t;return e}))}getSyncConfig(){return{rowUpdateMode:`full`,sync:this.syncFn.bind(this)}}incrementRunCount(){this.runCount++}getRunCount(){return this.runCount}syncFn(e){this.liveQueryCollection=e.collection,this.isInErrorState=!1,this.fatalQueryError=!1,this.erroredSourceIds.clear(),this.lastSubsetError=void 0,this.currentSyncConfig=e;let t={messagesCount:0,subscribedToAllCollections:!1,unsubscribeCallbacks:new Set},n=!1,r=()=>{if(n)return;n=!0;let e;for(let n of t.unsubscribeCallbacks)try{n()}catch(t){e??=t}if(t.unsubscribeCallbacks.clear(),this.currentSyncConfig=void 0,this.currentSyncState=void 0,this.maybeRunGraphFn=void 0,this.currentWindow=void 0,this.isInErrorState=!1,this.fatalQueryError=!1,this.erroredSourceIds.clear(),this.pendingGraphRuns.clear(),this.graphCache=void 0,this.inputsCache=void 0,this.pipelineCache=void 0,this.sourceWhereClausesCache=void 0,this.bucketFacadesCache=void 0,this.lazySources.clear(),this.demandGenerations.clear(),this.activeDemands.clear(),this.optimizableOrderByCollections={},this.lazySourcesCallbacks={},Object.keys(this.subscriptions).forEach(e=>delete this.subscriptions[e]),this.compiledAliasToCollectionId={},this.unsubscribeFromSchedulerClears?.(),this.unsubscribeFromSchedulerClears=void 0,e!==void 0)throw e};try{let n=this.extendPipelineWithChangeProcessing(e,t);this.currentSyncState=n,this.unsubscribeFromSchedulerClears=bo.onClear(e=>{this.clearPendingGraphRun(e)});let r=e.collection.on(`loadingSubset:change`,t=>{t.isLoadingSubset||this.updateLiveQueryStatus(e)});t.unsubscribeCallbacks.add(r);let i=this.subscribeToAllCollections(e,n);this.maybeRunGraphFn=()=>this.scheduleGraphRun(i),this.scheduleGraphRun(i)}catch(e){try{r()}catch{}throw e}return r}compileBasePipeline(){this.graphCache=new _i,this.inputsCache=Object.fromEntries(this.collectionSources.map(e=>[e.sourceId,this.graphCache.newInput()]));let e=Hl(this.query,this.inputsCache,this.collections,this.subscriptions,this.lazySourcesCallbacks,this.lazySources,this.optimizableOrderByCollections,e=>{this.windowFn=e,this.currentWindow&&e(this.currentWindow)}),t=Yu(e,this.config.getKey,this.hasJoins(this.query));this.pipelineCache=t.pipeline,this.sourceWhereClausesCache=e.sourceWhereClauses,this.compiledAliasToCollectionId=e.aliasToCollectionId,this.bucketFacadesCache=t.facades;let n=this.collectionSources.map(e=>e.sourceId).filter(e=>!Object.hasOwn(this.inputsCache,e));if(n.length>0)throw new cn(n)}maybeCompileBasePipeline(){return(!this.graphCache||!this.inputsCache||!this.pipelineCache)&&this.compileBasePipeline(),{graph:this.graphCache,inputs:this.inputsCache,pipeline:this.pipelineCache}}extendPipelineWithChangeProcessing(e,t){let{begin:n,commit:r}=e,{graph:i,inputs:a,pipeline:o}=this.maybeCompileBasePipeline(),s=new Map;o.pipe(Ki(e=>{let n=e.getInner();t.messagesCount+=n.length,n.reduce(yd,s)}));let c=new pd(this.id,this.bucketFacadesCache??[],e=>{t.messagesCount+=e});return t.unsubscribeCallbacks.add(()=>c.cleanup()),t.flushPendingChanges=()=>{let t=s.size>0,i=c.hasPendingChanges();if(!t&&!i)return;let a,o;try{a=c.flush(),o=t?e.collection._deferPublication():void 0;let i=new Map([...s].map(([e,t])=>{let n={...t,value:c.resolve(t.value)};return t.previousValue!==void 0&&(n.previousValue=c.resolve(t.previousValue)),[e,n]}));t&&(n(),i.forEach(this.applyChanges.bind(this,e)),bd(i)&&xd(e.collection),r())}catch(e){throw s=new Map,o?.discard(),a?.rollback(),e}s=new Map;let l;for(let e of[o?.publish,a.publish])if(e)try{e()}catch(e){l??=e}if(l!==void 0)throw l},i.finalize(),t.graph=i,t.inputs=a,t.pipeline=o,t}applyChanges(e,t,n){let{write:r,collection:i}=e,{deletes:a,inserts:o,value:s,orderByIndex:c}=t;if(this.resultKeys.set(s,n),c!==void 0&&this.orderByIndices.set(s,c),o&&a===0)r({value:s,type:`insert`});else if(o>a||o===a&&i.has(i.getKeyFromItem(s)))r({value:s,type:`update`});else if(a>0)r({value:s,type:`delete`});else throw Error(`Could not apply changes: ${JSON.stringify(t)}. This should never happen.`)}handleSourceStatusChange(e,t,n,r){let{status:i}=r;if(i===`error`){this.erroredSourceIds.add(t),this.setErrorState(`Source collection '${n}' entered error state`);return}if(i===`cleaned-up`){this.transitionToError(`Source collection '${n}' was manually cleaned up while live query '${this.id}' depends on it. Live queries prevent automatic GC, so this was likely a manual cleanup() call.`);return}i===`ready`&&this.erroredSourceIds.delete(t)&&!this.fatalQueryError&&this.erroredSourceIds.size===0&&(this.isInErrorState=!1,this.maybeRunGraphFn?.()),this.updateLiveQueryStatus(e)}updateLiveQueryStatus(e){let{markReady:t}=e;if(this.isInErrorState)return;let n=this.currentSyncState?.subscribedToAllCollections,r=this.allRequiredSourcesReady(),i=[...this.activeDemands.values()].every(e=>e.settled),a=this.liveQueryCollection?.isLoadingSubset;n&&r&&i&&!a&&t()}transitionToError(e,t){this.fatalQueryError=!0,this.setErrorState(e,t)}setErrorState(e,t){this.isInErrorState=!0,console.error(`[Live Query Error] ${e}`),this.liveQueryCollection?._lifecycle.markError(t??Error(e))}allRequiredSourcesReady(){return this.collectionSources.every(e=>this.lazySources.has(e.sourceId)&&e.collection.config.syncMode===`on-demand`||e.collection.isReady())}subscribeToAllCollections(e,t){if(this.collectionSources.length===0)throw Error(`Query '${this.id}' has no collection sources. This should not happen; please report.`);let n=this.collectionSources.map(n=>{let{sourceId:r,alias:i,collection:a}=n,o=a.id,s=Ws(a);s&&s!==this?(this.sourceDependencies[r]=[s],this.builderDependencies.add(s)):this.sourceDependencies[r]=[];let c=new Ku(r,i,a,this),l=a.on(`status:change`,t=>{this.handleSourceStatusChange(e,r,o,t)});t.unsubscribeCallbacks.add(l),a.status===`error`&&this.handleSourceStatusChange(e,r,o,{type:`status:change`,collection:a,status:`error`,previousStatus:`error`});let u=c.subscribe();this.subscriptions[r]=u;let d=this.lazySourcesCallbacks[r];if(d){d.setDemand=(e,t)=>c.setDemand(u,e,t);for(let e of d.plans??[])e.initialKeys.size>0&&d.setDemand(e,e.initialKeys)}return c.loadMoreIfNeeded.bind(c,u)});return t.subscribedToAllCollections=!0,()=>(n.map(e=>e()),!0)}};function vd(e){return(t,n)=>{let r=e.get(t),i=e.get(n);return r&&i?r<i?-1:+(r>i):0}}function yd(e,[[t,n],r]){let[i,a]=n,o=e.get(t)||{deletes:0,inserts:0,value:i,orderByIndex:a};return r<0?(o.deletes+=Math.abs(r),o.previousValue=i,o.previousOrderByIndex=a):r>0&&(o.inserts+=r,o.value=i,a!==void 0&&(o.orderByIndex=a)),e.set(t,o),e}function bd(e){for(let t of e.values())if(t.inserts>0&&t.deletes>0&&t.previousValue!==void 0&&B(t.previousValue,t.value)&&t.orderByIndex!==t.previousOrderByIndex)return!0;return!1}function xd(e){e._markLayoutChange()}function Sd(e){return new _d(e).getConfig()}function Cd(e){if(typeof e==`function`)return wd(Sd({query:e}));{let t=e,n=Sd(t);return t.utils&&Object.defineProperties(n.utils,Object.getOwnPropertyDescriptors(t.utils)),wd(n)}}function wd(e){let t=Is(e),n=Hs(e);return n&&Us(t,n),t}function Td(e){return typeof e==`object`&&!!e&&typeof e.subscribeChanges==`function`&&typeof e.startSyncImmediate==`function`&&typeof e.id==`string`}function Ed(e){return e.config?.singleResult===!0}function Dd(e){return{isLoading:e===`loading`,isReady:e===`ready`,isIdle:e===`idle`,isError:e===`error`,isCleanedUp:e===`cleaned-up`}}var Od={state:void 0,data:void 0,collection:void 0,layoutRevision:0,status:`disabled`,isLoading:!1,isReady:!0,isIdle:!1,isError:!1,isCleanedUp:!1,isEnabled:!1},kd=class{constructor(e,t,n,r,i){this.snapshotDirty=!0,this.cachedSnapshot=Od,this.layoutRevision=0,this.subscriptions=new Set,this.publicationQueue=[],this.dispatching=!1,this.blockDelivery=!1,this.attached=!1,this.collectionUnsub=null,this.hasHydrationError=!1,this.liveResultIsAuthoritative=!1,this.handoffScheduled=!1,this.disposed=!1,this.collection=e,this.wholesale=t,this.client=n,this.queryHash=r,this.onPreload=i,this.registerClientResource()}getSnapshot(){let e=this.collection;if(!e)return Od;if(this.syncHydrationState(),this.attached||this.refreshDetachedState(e),this.snapshotDirty){let t=this.getVisibleEntries(e),n=new Map(t),r=t.map(([,e])=>e),i=Ed(e),a=this.visibleStatus??e.status,o=this.hasHydrationError||a===`error`?`error`:this.hasHydrationSeed()?`ready`:a,s=this.lastLayoutKeys,c=s===void 0||s.length!==t.length;if(!c){for(let e=0;e<t.length;e++)if(s[e]!==t[e][0]){c=!0;break}}c&&(this.lastLayoutKeys=t.map(([e])=>e),this.layoutRevision++),this.cachedSnapshot={state:n,data:i?r[0]:r,collection:e,layoutRevision:this.layoutRevision,status:o,...Dd(o),isEnabled:!0},this.snapshotDirty=!1}return this.cachedSnapshot}getServerSnapshot(){return this.getSnapshot()}getError(){return this.syncHydrationState(),this.hasHydrationError?this.hydrationError:void 0}dehydrate(){let e=this.collection;return e?{rows:(this.hasHydrationSeed()?this.hydrationSeed.entries:this.readEntries(e).entries).map(([e,t])=>({key:e,value:t}))}:{rows:[]}}hasHydrationSeed(){return this.hydrationSeed!==void 0&&!this.liveResultIsAuthoritative}getVisibleEntries(e){return this.hasHydrationSeed()?this.hydrationSeed.entries:this.cachedEntries??this.captureEntries(e).entries}syncHydrationState(){if(!this.client||!this.queryHash||this.liveResultIsAuthoritative)return!1;let e=this.client._getLiveQuery(this.queryHash);if(!e)return!1;if(this.attached&&!this.hydrationSeed&&this.collection?.status===`ready`&&!this.collection.isLoadingSubset)return this.markLiveResultAuthoritative(e.dehydratedAt);if(e.status===`error`){let t=!this.hasHydrationError||this.hydrationError!==e.error;return this.hydrationError=e.error,this.hasHydrationError=!0,t&&(this.snapshotDirty=!0),t}return e.status!==`success`||!e.snapshot||this.hydrationSeed&&this.hydrationSeed.dehydratedAt>=e.dehydratedAt?!1:(this.hydrationSeed={dehydratedAt:e.dehydratedAt,entries:e.snapshot.rows.map(e=>[e.key,e.value])},this.hydrationError=void 0,this.hasHydrationError=!1,this.snapshotDirty=!0,!0)}diffEntries(e,t){let n=new Map(e),r=new Map(t),i=[];for(let[t,n]of e)r.has(t)||i.push({type:`delete`,key:t,value:n});for(let[e,r]of t){let t=n.get(e);t===void 0?i.push({type:`insert`,key:e,value:r}):t!==r&&i.push({type:`update`,key:e,value:r,previousValue:t})}return i}handoffHydrationSeed(e){let t=this.hydrationSeed?.entries??[],n=this.hydrationSeed?.dehydratedAt,{entries:r,revision:i}=this.readEntries(e);return this.hydrationSeed=void 0,this.markLiveResultAuthoritative(n),this.updateCachedEntries(r,i),this.snapshotDirty=!0,{changes:this.diffEntries(t,r),entries:r,revision:i}}markLiveResultAuthoritative(e){let t=this.hasHydrationError;return this.hydrationError=void 0,this.hasHydrationError=!1,this.liveResultIsAuthoritative=!0,e!==void 0&&this.queryHash&&this.client?._consumeLiveQueryResult(this.queryHash,e),t&&(this.snapshotDirty=!0),t}scheduleHydrationHandoff(){this.handoffScheduled||(this.handoffScheduled=!0,queueMicrotask(()=>{this.handoffScheduled=!1;let e=this.collection;if(this.disposed||!this.attached||!e||!this.hasHydrationSeed()||e.status!==`ready`||e.isLoadingSubset)return;let t=this.handoffHydrationSeed(e);this.emit(this.wholesale?void 0:t.changes,void 0,t.entries,e.status,t.revision,this.getCollectionLayoutRevision(e),!0)}))}getCollectionRevision(e){let t=e._stateRevision;return typeof t==`number`?t:void 0}getCollectionLayoutRevision(e){let t=e._layoutRevision;return typeof t==`number`?t:void 0}readEntries(e){return{entries:Array.from(e.entries()),revision:this.getCollectionRevision(e)}}captureEntries(e){let{entries:t,revision:n}=this.readEntries(e);return this.updateCachedEntries(t,n),{entries:t,revision:n}}updateCachedEntries(e,t){let n=t===void 0?!this.entriesEqual(this.cachedEntries,e):this.cachedEntries===void 0||t!==this.cachedCollectionRevision;this.cachedEntries=e,this.cachedCollectionRevision=t,n&&(this.snapshotDirty=!0)}entriesEqual(e,t){return!e||e.length!==t.length?!1:e.every(([e,n],r)=>t[r][0]===e&&t[r][1]===n)}refreshDetachedState(e){let t=e.status,n=this.getCollectionRevision(e),r=this.getCollectionLayoutRevision(e);if(n!==void 0)(this.cachedEntries===void 0||n!==this.cachedCollectionRevision||r!==this.cachedCollectionLayoutRevision)&&(this.captureEntries(e),this.cachedCollectionLayoutRevision=r,this.snapshotDirty=!0);else{let t=Array.from(e.entries());this.updateCachedEntries(t,void 0)}this.visibleStatus!==t&&(this.visibleStatus=t,this.snapshotDirty=!0)}subscribe(e){if(this.disposed)throw new Xe;let t={listener:e,active:!0};return this.subscriptions.add(t),this.subscriptions.size===1?this.attach():this.wholesale||this.seed(t),()=>{t.active&&(t.active=!1,this.subscriptions.delete(t),this.subscriptions.size===0&&this.detach())}}seed(e){let t=this.collection;if(!t)return;let n=[];for(let[e,r]of this.getVisibleEntries(t))n.push({type:`insert`,key:e,value:r});n.length!==0&&this.emit(n,[e])}attach(){let e=this.collection;if(!e||this.disposed)return;this.registerClientResource(),this.syncHydrationState(),this.refreshDetachedState(e),this.attached=!0,this.visibleStatus??=e.status,this.deliveredLayoutRevision=this.getCollectionLayoutRevision(e);let t=this.hasHydrationSeed();this.blockDelivery=this.wholesale||t;let n=(t,n=e.status,r=!1)=>{if(this.disposed||this.subscriptions.size===0||this.hasHydrationSeed()&&(n===`ready`&&this.scheduleHydrationHandoff(),n!==`error`))return;if(n===`ready`&&!e.isLoadingSubset&&!this.liveResultIsAuthoritative&&this.client&&this.queryHash){let e=this.client._getLiveQuery(this.queryHash);this.markLiveResultAuthoritative(e?.dehydratedAt)}let i=this.getCollectionLayoutRevision(e),a=r;if(!r&&t!==void 0&&t.length===0){if(i===void 0||i===this.deliveredLayoutRevision)return;a=!0}t!==void 0&&i!==void 0&&(this.deliveredLayoutRevision=i);let o=t===void 0?n===`cleaned-up`?this.readEntries(e):void 0:this.readEntries(e);this.emit(t,void 0,o?.entries,n,o?.revision,i,a)},r=e.on(`status:change`,({status:e})=>n(void 0,e)),i=e._subscribeLayoutChanges,a=typeof i==`function`?i.call(e,()=>n([],e.status,!0)):()=>{},o=null,s=this.client&&this.queryHash?this.client.subscribe(t=>{if(t.type===`liveQueryStreamError`||t.query.queryHash!==this.queryHash)return;let n=this.getVisibleEntries(e);if(!this.syncHydrationState())return;let r=this.getVisibleEntries(e);this.emit(this.wholesale?void 0:this.diffEntries(n,r))}):()=>{},c=()=>{s(),r(),a(),o?.unsubscribe()};if(this.collectionUnsub=c,o=e.subscribeChanges(e=>n(e),{includeInitialState:!this.wholesale&&!t}),this.blockDelivery=!1,this.collectionUnsub!==c){o.unsubscribe();return}if(this.wholesale||t){this.flushPublications(!this.wholesale);let{entries:t,revision:n}=this.readEntries(e);this.updateCachedEntries(t,n)}this.hasHydrationSeed()&&(this.wholesale||this.seed(Array.from(this.subscriptions)[0]),e.status===`ready`&&this.scheduleHydrationHandoff())}detach(){this.collectionUnsub?.(),this.collectionUnsub=null,this.attached=!1,this.blockDelivery=!1,this.publicationQueue.length=0,this.unregisterClientResource?.(),this.unregisterClientResource=void 0}registerClientResource(){this.unregisterClientResource||!this.client?._isSsrServerCleanupEnabled()||!this.collection||!Hs(this.collection.config)||(this.unregisterClientResource=this.client._registerLiveQueryResource(this,async()=>{let e=this.collection;this.dispose(),await e?.cleanup()}))}emit(e,t=Array.from(this.subscriptions),n,r=this.collection?.status??`cleaned-up`,i,a,o=!1){this.publicationQueue.push({changes:e,targets:t,entries:n,status:r,collectionRevision:i,collectionLayoutRevision:a,layoutChanged:o}),!(this.dispatching||this.blockDelivery)&&this.flushPublications()}flushPublications(e=!0){if(!this.dispatching){this.dispatching=!0;try{for(;this.publicationQueue.length>0;){let t=this.publicationQueue.shift();if(t.entries&&this.updateCachedEntries(t.entries,t.collectionRevision),t.collectionLayoutRevision!==void 0&&(this.cachedCollectionLayoutRevision=t.collectionLayoutRevision),t.layoutChanged&&(this.snapshotDirty=!0),this.visibleStatus!==t.status&&(this.visibleStatus=t.status,this.snapshotDirty=!0),e)for(let e of t.targets){if(this.disposed)return;e.listener(t.changes)}}}finally{this.dispatching=!1}}}preload(){if(this.preloadPromise)return this.preloadPromise;if(this.client&&this.queryHash){let e=this.client._getLiveQuery(this.queryHash);if(e?.status===`pending`)return e.promise;if(e?.status===`success`)return Promise.resolve()}this.registerClientResource(),this.onPreload?.();let e=this.collection?.preload()??Promise.resolve(),t=this.client?._isSsrStreamingEnabled()&&this.queryHash?this.client._registerLiveQuery(this.queryHash,e.then(()=>this.dehydrate())):e;this.preloadPromise=t;let n=()=>{this.preloadPromise===t&&(this.preloadPromise=void 0)};return t.then(n,n),t}dispose(){if(!this.disposed){this.disposed=!0,this.detach();for(let e of this.subscriptions)e.active=!1;this.subscriptions.clear(),this.publicationQueue.length=0}}};function Ad(e,t={}){return new kd(e??null,t.mode===`wholesale`,t.client,t.queryHash,t.onPreload)}function jd(){let e=Pd(),t=new WeakMap,n=0;return r=>{let i=t.get(r);return i===void 0&&(i=++n,t.set(r,i)),[`runtimeReference`,e,i]}}var Md;function Nd(e){return Md??=jd(),Md(e)}function Pd(){let e=new Uint32Array(4),t=Reflect.get(globalThis,`crypto`);return typeof t?.getRandomValues==`function`?(t.getRandomValues(e),Array.from(e,e=>e.toString(36)).join(`-`)):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}var Fd=class extends Error{constructor(e,t){super(`Query IR is not stably hashable at ${e}: ${t}`),this.path=e,this.reason=t,this.name=`UnhashableQueryIRError`}};function Id(e){return zd(e)}function Ld(e){return Id(Uc(e))}function Rd(e,t=`value`){return JSON.stringify(q(e,t,new WeakSet))}function zd(e){return JSON.stringify(Bd(e))}function Bd(e){return Ud(e,`query`,new WeakSet)}function Vd(e,t){let n=new Map,r=e=>{if(e.type===`unionFrom`){e.sources.forEach(r);return}e.type!==`unionAll`&&(n.has(e.alias)||n.set(e.alias,n.size))};return r(e.from),e.join?.forEach(({from:e})=>r(e)),{bindings:n,hasUnqualifiedOutput:e.from.type===`unionAll`,parent:t}}function Hd(e,t){let n=e,r=0;for(;n;){let e=n.bindings.get(t);if(e!==void 0)return[r,e];if(n.hasUnqualifiedOutput)return;n=n.parent,r++}}function Ud(e,t,n,r){return Wd(e,t,n,Vd(e,r))}function Wd(e,t,n,r){if(e.fnSelect)throw new Fd(`${t}.fnSelect`,`function select`);if(e.fnWhere?.length)throw new Fd(`${t}.fnWhere`,`function where`);if(e.fnHaving?.length)throw new Fd(`${t}.fnHaving`,`function having`);let i={type:`query`,from:qd(e.from,`${t}.from`,n,r)};return e.select&&(i.select=Jd(e.select,`${t}.select`,n,r)),!e.select&&(e.from.type===`unionFrom`||e.join!==void 0||e.groupBy!==void 0)&&(i.implicitOutput={type:`namespaced`,aliases:Array.from(r.bindings.keys())}),e.join&&(i.join=e.join.map((e,i)=>Kd(e,`${t}.join[${i}]`,n,r))),e.where&&(i.where=Gd(e.where,`${t}.where`,n,r)),e.groupBy&&(i.groupBy=e.groupBy.map((e,i)=>Qd(e,`${t}.groupBy[${i}]`,n,`exact-output`,r))),e.having&&(i.having=Gd(e.having,`${t}.having`,n,r)),e.orderBy&&(i.orderBy=e.orderBy.map((e,i)=>Zd(e,`${t}.orderBy[${i}]`,n,`ordering-operand`,r))),e.limit!==void 0&&(i.limit=q(e.limit,`${t}.limit`,n)),e.offset!==void 0&&e.offset!==0&&(i.offset=q(e.offset,`${t}.offset`,n)),e.distinct&&(i.distinct=!0),e.singleResult&&(i.singleResult=!0),i}function Gd(e,t,n,r){let i=e.map((e,i)=>Xd(e,`${t}[${i}]`,n,r));return i.sort(sf),i.filter((e,t)=>t===0||sf(e,i[t-1])!==0)}function Kd(e,t,n,r){return{type:e.type,from:qd(e.from,`${t}.from`,n,r),left:Qd(e.left,`${t}.left`,n,`equality-operand`,r),right:Qd(e.right,`${t}.right`,n,`equality-operand`,r)}}function qd(e,t,n,r){return e.type===`collectionRef`?{type:`collectionRef`,collectionId:q(e.collection.id,`${t}.collection.id`,n)}:e.type===`unionFrom`?{type:`unionFrom`,sources:e.sources.map((e,i)=>qd(e,`${t}.sources[${i}]`,n,r))}:e.type===`unionAll`?{type:`unionAll`,queries:e.queries.map((e,i)=>Ud(e,`${t}.queries[${i}]`,n,r.parent))}:{type:`queryRef`,query:Ud(e.query,`${t}.query`,n,r)}}function Jd(e,t,n,r){return{type:`select`,fields:Object.keys(e).sort().map(i=>[i,Yd(e[i],`${t}.${i}`,n,r)])}}function Yd(e,t,n,r){return Do(e)?Qd(G(e),t,n,`exact-output`,r):df(e)?Qd(e,t,n,`exact-output`,r):ff(e)?Jd(e,t,n,r):rf(e,t,n)}function Xd(e,t,n,r){if(uf(e)){let i={type:`where`,expression:Qd(e.expression,`${t}.expression`,n,`exact-output`,r)};return e.residual===!0&&(i.residual=!0),i}return Qd(e,t,n,`exact-output`,r)}function Zd(e,t,n,r=`exact-output`,i){return{expression:Qd(e.expression,`${t}.expression`,n,r,i),compareOptions:q(e.compareOptions,`${t}.compareOptions`,n)}}function Qd(e,t,n,r=`exact-output`,i){if(e.type===`ref`){let r=Hd(i,e.path[0]??``);return{type:`ref`,path:r===void 0?e.path.map((e,r)=>q(e,`${t}.path[${r}]`,n)):[[`binding`,...r],...e.path.slice(1).map((e,r)=>q(e,`${t}.path[${r+1}]`,n))]}}if(e.type===`val`)return{type:`val`,value:r===`equality-operand`?af(e.value,`${t}.value`,n,i):r===`ordering-operand`?of(e.value,`${t}.value`,n):rf(e.value,`${t}.value`,n)};if(e.type===`func`){if(e.name===`in`&&e.args.length===2&&e.args[1]?.type===`val`&&Array.isArray(e.args[1].value)){let r=e.args[1].value.map((e,r)=>af(e,`${t}.args[1].value[${r}]`,n,i));return $d(e.name,[Qd(e.args[0],`${t}.args[0]`,n,`equality-operand`,i),{type:`val`,value:[`set`,ef(r)]}])}let r=e.name===`eq`?`equality-operand`:e.name===`gt`||e.name===`gte`||e.name===`lt`||e.name===`lte`?`ordering-operand`:`exact-output`,a=e.args.map((e,a)=>Qd(e,`${t}.args[${a}]`,n,r,i));return $d(e.name,a)}if(e.type===`agg`)return{type:`agg`,name:e.name,args:e.args.map((e,r)=>Qd(e,`${t}.args[${r}]`,n,`exact-output`,i))};if(e.type===`conditionalSelect`){let r={type:`conditionalSelect`,branches:e.branches.map((e,r)=>({condition:Qd(e.condition,`${t}.branches[${r}].condition`,n,`exact-output`,i),value:Yd(e.value,`${t}.branches[${r}].value`,n,i)}))};return e.defaultValue!==void 0&&(r.defaultValue=Yd(e.defaultValue,`${t}.defaultValue`,n,i)),r}let a=Vd(e.query,i),o={type:`includesSubquery`,query:Wd(e.query,`${t}.query`,n,a),correlationField:Qd(e.correlationField,`${t}.correlationField`,n,`equality-operand`,i),childCorrelationField:Qd(e.childCorrelationField,`${t}.childCorrelationField`,n,`equality-operand`,a),fieldName:e.fieldName,materialization:e.materialization};return e.parentFilters&&(o.parentFilters=e.parentFilters.map((e,r)=>Xd(e,`${t}.parentFilters[${r}]`,n,i))),e.parentProjection&&(o.parentProjection=e.parentProjection.map((e,r)=>Qd(e,`${t}.parentProjection[${r}]`,n,`exact-output`,i))),e.scalarField!==void 0&&(o.scalarField=e.scalarField),o}function $d(e,t){return(e===`and`||e===`or`)&&t.length>0?{type:`func`,name:e,args:ef(t.flatMap(t=>tf(t,e)?t.args:[t]))}:e===`eq`&&t.length===2?(t.sort(sf),{type:`func`,name:e,args:t}):(e===`gt`||e===`gte`||e===`lt`||e===`lte`)&&t.length===2&&sf(t[0],t[1])>0?{type:`func`,name:nf(e),args:[t[1],t[0]]}:{type:`func`,name:e,args:t}}function ef(e){let t=e.map(e=>({key:JSON.stringify(e),value:e}));return t.sort((e,t)=>e.key<t.key?-1:+(e.key>t.key)),t.filter((e,n)=>n===0||e.key!==t[n-1].key).map(e=>e.value)}function tf(e,t){return typeof e==`object`&&!!e&&!Array.isArray(e)&&e.type===`func`&&e.name===t&&Array.isArray(e.args)}function nf(e){switch(e){case`gt`:return`lt`;case`gte`:return`lte`;case`lt`:return`gt`;case`lte`:return`gte`}}function q(e,t,n){if(e===null)return[`null`];if(typeof e==`string`)return[`string`,e];if(typeof e==`boolean`)return[`boolean`,e];if(typeof e==`number`)return Number.isNaN(e)?[`number`,`NaN`]:e===1/0?[`number`,`Infinity`]:e===-1/0?[`number`,`-Infinity`]:Object.is(e,-0)?[`number`,`-0`]:[`number`,e];if(e===void 0)return[`undefined`];if(typeof e==`bigint`)return[`bigint`,e.toString()];if(typeof e==`function`)throw new Fd(t,`function value`);if(typeof e==`symbol`)throw new Fd(t,`symbol value`);if(Do(e))return Qd(G(e),t,n);if(Array.isArray(e))return lf(e,t,n,()=>[`array`,e.map((e,r)=>q(e,`${t}[${r}]`,n))]);if(e instanceof Date){let n=e.getTime();if(Number.isNaN(n))throw new Fd(t,`invalid Date`);return[`Date`,e.toISOString()]}if(e instanceof ArrayBuffer)return[`binary`,`ArrayBuffer`,Array.from(new Uint8Array(e))];if(ArrayBuffer.isView(e))return[`binary`,e.constructor.name,Array.from(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))];if(e instanceof Map)return lf(e,t,n,()=>{let r=Array.from(e.entries(),([e,r],i)=>[q(e,`${t}.key[${i}]`,n),q(r,`${t}.value[${i}]`,n)]);return r.sort(sf),[`Map`,r]});if(e instanceof Set)return lf(e,t,n,()=>{let r=Array.from(e,(e,r)=>q(e,`${t}[${r}]`,n));return r.sort(sf),[`Set`,r]});if(ff(e))return cf(e,t,n);throw new Fd(t,`non-plain object value`)}function rf(e,t,n){return typeof e==`object`&&e?Nd(e):q(e,t,n)}function af(e,t,n,r){if(Do(e))return Qd(G(e),t,n,`equality-operand`,r);if(typeof e==`number`&&Object.is(e,-0))return q(0,t,n);if(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)return[`binary`,`Uint8Array`,Array.from(e)];let i=Cn(e);return i===e?typeof e==`object`&&e?Nd(e):q(e,t,n):q(i,t,n)}function of(e,t,n){if(typeof e==`number`&&Object.is(e,-0))return q(0,t,n);if(e instanceof Date&&Number.isNaN(e.getTime()))return q(NaN,t,n);let r=Cn(e);if(r!==e&&!(e instanceof Uint8Array))return q(r,t,n);try{return q(e,t,n)}catch(t){if(t instanceof Fd&&typeof e==`object`&&e)return Nd(e);throw t}}function sf(e,t){let n=JSON.stringify(e),r=JSON.stringify(t);return n<r?-1:+(n>r)}function cf(e,t,n){return lf(e,t,n,()=>[`object`,Object.keys(e).sort().map(r=>[r,q(e[r],`${t}.${r}`,n)])])}function lf(e,t,n,r){if(n.has(e))throw new Fd(t,`circular value`);n.add(e);try{return r()}finally{n.delete(e)}}function uf(e){return`expression`in e}function df(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`agg`||t===`conditionalSelect`||t===`func`||t===`ref`||t===`val`||t===`includesSubquery`}function ff(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pf(e,t){return new Ec({},e?n=>{let r=e._materializeCollectionForRender(n);return r._deferSyncStart()&&t.add(r),r}:void 0)}function mf(e,t,n){if(typeof e==`function`)return mf(e(pf(t,n)),t,n);if(e&&typeof e==`object`&&!Td(e)&&!(e instanceof Ec)&&`query`in e){let{query:r,queryKey:i,client:a,...o}=e,s=typeof r==`function`?r(pf(t,n)):r;return s==null?s:{...o,query:s}}return e}function hf(e){if(Td(e))return[`collection`,e.id];if(e instanceof Ec)return[`query`,Ld(e)];if(e&&typeof e==`object`&&`query`in e){let t=e;return[`config`,hf(t.query),[`getKey`,t.getKey],[`schema`,t.schema],[`singleResult`,t.singleResult===!0],[`defaultStringCollation`,t.defaultStringCollation]]}return e==null?[`disabled`]:[`value`,e]}var gf=(0,I.createContext)(void 0);function _f(){return(0,I.useContext)(gf)}var vf=Symbol(`liveQueryResultInfo`);function yf(e,t){Object.defineProperty(e,vf,{configurable:!0,value:t})}var bf=1,xf=16,Sf=10,Cf=50,wf=new Set,Tf=new Set,Ef=new Set,Df=Symbol(`unpreparedQueryValue`);function Of(e=`useLiveQuery`){if(!kf(`TANSTACK_DB_DISABLE_DEPRECATION_WARNINGS`))return;let t=jf(4);wf.has(t)||(wf.add(t),console.warn(`[${e}] The dependency-array form is deprecated and will be removed in 1.0. Use ${e===`useLiveQuery`?`useLiveQuery({ query })`:`useLiveInfiniteQuery(query, { queryKey })`} instead. Provide queryKey only for functional/opaque queries or to avoid deriving identity from structured query IR on render.`))}function kf(e){return!1}function Af(){return typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}function jf(e){let t=Error().stack??`unknown`;return t.split(`
15
+ `)[e]?.trim()??t}function Mf(e,t){if(e.warned||!kf(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`))return;let n=t>=xf,r=e.renderCount>=Sf&&e.totalMs>=Cf;if(!n&&!r)return;let i=jf(5);if(Tf.has(i)){e.warned=!0;return}Tf.add(i),e.warned=!0;let a=n?`one render took ${t.toFixed(1)}ms`:`${e.renderCount} renders took ${e.totalMs.toFixed(1)}ms`;console.warn(`[useLiveQuery] Deriving live query identity from structured query IR is running on a hot render path (${a}, max ${e.maxMs.toFixed(1)}ms). Provide an explicit queryKey to skip rebuilding and hashing the IR on every render: useLiveQuery({ queryKey: [...], query }).`)}function Nf(e){return e&&typeof e==`object`&&Array.isArray(e.queryKey)?e.queryKey:void 0}function Pf(e){return e&&typeof e==`object`&&`client`in e&&e.client!==void 0?e.client:void 0}function Ff(e,t,n){return mf(e,t,n)}function If(e,t,n,r){let i=kf(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`),a=i?Af():0,o=Ff(e,t,r);try{return{status:`hashable`,value:o,identityDeps:[`derived`,hf(o)]}}catch(e){if(e instanceof Fd)return{status:`unhashable`,value:o,error:e};throw e}finally{if(i){let e=Af()-a;n.renderCount+=1,n.totalMs+=e,n.maxMs=Math.max(n.maxMs,e),Mf(n,e)}}}function Lf(e){if(!kf(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`))return;let t=jf(4);Ef.has(t)||(Ef.add(t),console.warn(`[useLiveQuery] This query cannot derive a stable identity because ${e.reason} at ${e.path}. It will keep the legacy mount-stable behavior for now. Add queryKey: [...] to make captured values reactive. Unhashable queries without queryKey will throw in 1.0.`))}function Rf(e){if(e==null)return null;if(Td(e))return e.startSyncImmediate(),e;if(e instanceof Ec)return Cd({query:e,startSync:!0,gcTime:bf});if(typeof e==`object`)return Cd({startSync:!0,gcTime:bf,...e});throw Error(`useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof e}`)}function zf(e,t){let n=_f(),r=Td(e),i=r?n:Pf(e)??n,a=t??[],o=(0,I.useRef)(null),s=(0,I.useRef)(null),c=(0,I.useRef)(null),l=(0,I.useRef)(i),u=(0,I.useRef)([`legacy-unhashable`]),d=(0,I.useRef)({renderCount:0,totalMs:0,maxMs:0,warned:!1}),f=(0,I.useRef)(new Set),p=(0,I.useRef)(null),m=(0,I.useRef)(void 0),h=(0,I.useRef)(void 0),g=r?void 0:Nf(e),_=Df,v,y,b;if(g)v=g,y=[`queryKey`,g];else if(t!==void 0){v=a;try{_=Ff(e,i,f.current),y=[`deps`,a,hf(_)]}catch(e){if(!(e instanceof Fd))throw e;Lf(e),b=e}}else if(r)v=[],y=[`collection`,e.id];else{let t=If(e,i,d.current,f.current);_=t.value,t.status===`hashable`?(v=t.identityDeps,y=t.identityDeps):(Lf(t.error),v=u.current,b=t.error)}let x;if(y!==void 0)try{x=Rd(y,`queryKey`)}catch(e){if(e instanceof Fd){if(g!==void 0)throw e;b=e}else throw e}t!==void 0&&Of();let S=s.current===null||(t===void 0?!B(s.current,v):s.current.length!==v.length||s.current.some((e,t)=>e!==v[t])),C=!o.current||r&&c.current!==e||!r&&(l.current!==i||S),w=()=>{for(let e of f.current)e._resumeSyncStart();f.current.clear()};C&&(r?(e.config?.syncMode===`on-demand`&&kf(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`)&&console.warn(`[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.
16
+
17
+ Instead, use a query builder function:
18
+ const { data } = useLiveQuery({ query: (q) => q.from({ c: myCollection }).select(({ c }) => c) })
19
+
20
+ Or switch to syncMode "eager" if you want all data to sync automatically.`),e.startSyncImmediate(),o.current=e,c.current=e):(_===Df&&(_=Ff(e,i,f.current)),o.current=Rf(_),c.current=e,s.current=[...v]),l.current=i,m.current=x,h.current=b),C&&(p.current=Ad(o.current,{mode:`wholesale`,client:i,queryHash:m.current,onPreload:w}));let T=p.current,E=(0,I.useRef)(null);(!E.current||C)&&(E.current=e=>{let t=T.subscribe(()=>e());return w(),t});let D=(0,I.useSyncExternalStore)(E.current,()=>T.getSnapshot(),()=>T.getServerSnapshot());return yf(D,{client:i,queryHash:m.current,identityError:h.current,observer:T}),D}function Bf(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(n=Bf(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n)}return r}function Vf(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=Bf(e))&&(r&&(r+=` `),r+=t);return r}var Hf=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,Uf=Vf,Wf=(e,t)=>n=>{if(t?.variants==null)return Uf(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=Hf(t)||Hf(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return Uf(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},Gf=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),Kf=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),qf=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),Jf=e=>{let t=qf(e);return t.charAt(0).toUpperCase()+t.slice(1)},Yf={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},Xf=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Zf=(0,I.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,I.createElement)(`svg`,{ref:c,...Yf,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Gf(`lucide`,i),...!a&&!Xf(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,I.createElement)(e,t)),...Array.isArray(a)?a:[a]])),Qf=(e,t)=>{let n=(0,I.forwardRef)(({className:n,...r},i)=>(0,I.createElement)(Zf,{ref:i,iconNode:t,className:Gf(`lucide-${Kf(Jf(e))}`,`lucide-${e}`,n),...r}));return n.displayName=Jf(e),n},$f=Qf(`panel-left`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}]]),ep=Qf(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),tp=Qf(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),np=Object.defineProperty,rp=(e,t)=>np(e,`name`,{value:t,configurable:!0});function ip(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}rp(ip,`setRef`);function ap(...e){return t=>{let n=!1,r=e.map(e=>{let r=ip(e,t);return!n&&typeof r==`function`&&(n=!0),r});if(n)return()=>{for(let t=0;t<r.length;t++){let n=r[t];typeof n==`function`?n():ip(e[t],null)}}}}rp(ap,`composeRefs`);function op(...e){return I.useCallback(ap(...e),e)}rp(op,`useComposedRefs`);var sp=a(v(),1),cp=Object.defineProperty,lp=(e,t)=>cp(e,`name`,{value:t,configurable:!0});function up(e){let t=I.forwardRef((t,n)=>{let{children:r,...i}=t,a=null,o=!1,s=[];yp(r)&&typeof Cp==`function`&&(r=Cp(r._payload)),I.Children.forEach(r,e=>{if(_p(e)){o=!0;let t=e,n=`child`in t.props?t.props.child:t.props.children;yp(n)&&typeof Cp==`function`&&(n=Cp(n._payload)),a=mp(t,n),s.push(a?.props?.children)}else s.push(e)}),a?a=I.cloneElement(a,void 0,s):!o&&I.Children.count(r)===1&&I.isValidElement(r)&&(a=r);let c=a?gp(a):void 0,l=op(n,c);if(!a){if(r||r===0)throw Error(o?Sp(e):xp(e));return r}let u=hp(i,a.props??{});return a.type!==I.Fragment&&(u.ref=n?l:c),I.cloneElement(a,u)});return t.displayName=`${e}.Slot`,t}lp(up,`createSlot`);var dp=up(`Slot`),fp=Symbol.for(`radix.slottable`);function pp(e){let t=lp(e=>`child`in e?e.children(e.child):e.children,`Slottable`);return t.displayName=`${e}.Slottable`,t.__radixId=fp,t}lp(pp,`createSlottable`);var mp=lp((e,t)=>{if(`child`in e.props){let t=e.props.child;return I.isValidElement(t)?I.cloneElement(t,void 0,e.props.children(t.props.children)):null}return I.isValidElement(t)?t:null},`getSlottableElementFromSlottable`);function hp(e,t){let n={...t};for(let r in t){let i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...e)=>{let t=a(...e);return i(...e),t}:i&&(n[r]=i):r===`style`?n[r]={...i,...a}:r===`className`&&(n[r]=[i,a].filter(Boolean).join(` `))}return{...e,...n}}lp(hp,`mergeProps`);function gp(e){let t=Object.getOwnPropertyDescriptor(e.props,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}lp(gp,`getElementRef`);function _p(e){return I.isValidElement(e)&&typeof e.type==`function`&&`__radixId`in e.type&&e.type.__radixId===fp}lp(_p,`isSlottable`);var vp=Symbol.for(`react.lazy`);function yp(e){return typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===vp&&`_payload`in e&&bp(e._payload)}lp(yp,`isLazyComponent`);function bp(e){return typeof e==`object`&&!!e&&`then`in e}lp(bp,`isPromiseLike`);var xp=lp(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,`createSlotError`),Sp=lp(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,`createSlottableError`),Cp=I.use,wp=Object.defineProperty,Tp=(e,t)=>wp(e,`name`,{value:t,configurable:!0}),J=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`].reduce((e,t)=>{let n=up(`Primitive.${t}`),r=I.forwardRef((e,r)=>{let{asChild:i,...a}=e,o=i?n:t;return typeof window<`u`&&(window[Symbol.for(`radix-ui`)]=!0),(0,L.jsx)(o,{...a,ref:r})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Ep(e,t){e&&sp.flushSync(()=>e.dispatchEvent(t))}Tp(Ep,`dispatchDiscreteCustomEvent`);var Dp=Object.defineProperty,Op=(e,t)=>Dp(e,`name`,{value:t,configurable:!0}),kp=Object.freeze({position:`absolute`,border:0,width:1,height:1,padding:0,margin:-1,overflow:`hidden`,clip:`rect(0, 0, 0, 0)`,whiteSpace:`nowrap`,wordWrap:`normal`}),Ap=I.forwardRef(Op(function(e,t){return(0,L.jsx)(J.span,{...e,ref:t,style:{...kp,...e.style}})},`VisuallyHidden`)),jp=Object.defineProperty,Mp=(e,t)=>jp(e,`name`,{value:t,configurable:!0});function Np(e,t){let n=I.createContext(t);n.displayName=e+`Context`;let r=Mp(e=>{let{children:t,...r}=e,i=I.useMemo(()=>r,Object.values(r));return(0,L.jsx)(n.Provider,{value:i,children:t})},`Provider`);r.displayName=e+`Provider`;function i(r,i={}){let{optional:a=!1}=i,o=I.useContext(n);if(o)return o;if(t!==void 0)return t;if(!a)throw Error(`\`${r}\` must be used within \`${e}\``)}return Mp(i,`useContext`),[r,i]}Mp(Np,`createContext`);function Pp(e,t=[]){let n=[];function r(t,r){let i=I.createContext(r);i.displayName=t+`Context`;let a=n.length;n=[...n,r];let o=Mp(t=>{let{scope:n,children:r,...o}=t,s=n?.[e]?.[a]||i,c=I.useMemo(()=>o,Object.values(o));return(0,L.jsx)(s.Provider,{value:c,children:r})},`Provider`);o.displayName=t+`Provider`;function s(n,o,s={}){let{optional:c=!1}=s,l=o?.[e]?.[a]||i,u=I.useContext(l);if(u)return u;if(r!==void 0)return r;if(!c)throw Error(`\`${n}\` must be used within \`${t}\``)}return Mp(s,`useContext`),[o,s]}Mp(r,`createContext`);let i=Mp(()=>{let t=n.map(e=>I.createContext(e));return Mp(function(n){let r=n?.[e]||t;return I.useMemo(()=>({[`__scope${e}`]:{...n,[e]:r}}),[n,r])},`useScope`)},`createScope`);return i.scopeName=e,[r,Fp(i,...t)]}Mp(Pp,`createContextScope`);function Fp(...e){let t=e[0];if(e.length===1)return t;let n=Mp(()=>{let n=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return Mp(function(e){let r=n.reduce((t,{useScope:n,scopeName:r})=>{let i=n(e)[`__scope${r}`];return{...t,...i}},{});return I.useMemo(()=>({[`__scope${t.scopeName}`]:r}),[r])},`useComposedScopes`)},`createScope`);return n.scopeName=t.scopeName,n}Mp(Fp,`composeContextScopes`);var Ip=Object.defineProperty,Lp=(e,t)=>Ip(e,`name`,{value:t,configurable:!0}),Rp=!!(typeof window<`u`&&window.document&&window.document.createElement);function zp(e,t,{checkForDefaultPrevented:n=!0}={}){return Lp(function(r){if(e?.(r),n===!1||!r||!r.defaultPrevented)return t?.(r)},`handleEvent`)}Lp(zp,`composeEventHandlers`);function Bp(e){if(!Rp)throw Error(`Cannot access window outside of the DOM`);return e?.ownerDocument?.defaultView??window}Lp(Bp,`getOwnerWindow`);function Vp(e){if(!Rp)throw Error(`Cannot access document outside of the DOM`);return e?.ownerDocument??document}Lp(Vp,`getOwnerDocument`);function Hp(e,t=!1){let{activeElement:n}=Vp(e);if(!n?.nodeName)return null;if(Up(n)&&n.contentDocument)return Hp(n.contentDocument.body,t);if(t){let e=n.getAttribute(`aria-activedescendant`);if(e){let t=Vp(n).getElementById(e);if(t)return t}}return n}Lp(Hp,`getActiveElement`);function Up(e){return e.tagName===`IFRAME`}Lp(Up,`isFrame`);var Wp=globalThis?.document?I.useLayoutEffect:()=>{},Gp=Object.defineProperty,Kp=(e,t)=>Gp(e,`name`,{value:t,configurable:!0}),qp=I.useEffectEvent,Jp=I.useInsertionEffect;function Yp(e){if(typeof qp==`function`)return qp(e);let t=I.useRef(()=>{throw Error(`Cannot call an event handler while rendering.`)});return typeof Jp==`function`?Jp(()=>{t.current=e}):Wp(()=>{t.current=e}),I.useMemo(()=>((...e)=>t.current?.(...e)),[])}Kp(Yp,`useEffectEvent`);var Xp=Object.defineProperty,Zp=(e,t)=>Xp(e,`name`,{value:t,configurable:!0}),Qp=I.useInsertionEffect||Wp;function $p({prop:e,defaultProp:t,onChange:n=Zp(()=>{},`onChange`),caller:r}){let[i,a,o]=em({defaultProp:t,onChange:n}),s=e!==void 0;return[s?e:i,I.useCallback(t=>{if(s){let n=tm(t)?t(e):t;n!==e&&o.current?.(n)}else a(t)},[s,e,a,o])]}Zp($p,`useControllableState`);function em({defaultProp:e,onChange:t}){let[n,r]=I.useState(e),i=I.useRef(n),a=I.useRef(t);return Qp(()=>{a.current=t},[t]),I.useEffect(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}Zp(em,`useUncontrolledState`);function tm(e){return typeof e==`function`}Zp(tm,`isFunction`);var nm=Symbol(`RADIX:SYNC_STATE`);function rm(e,t,n,r){let{prop:i,defaultProp:a,onChange:o,caller:s}=t,c=i!==void 0,l=Yp(o),u=[{...n,state:a}];r&&u.push(r);let[d,f]=I.useReducer((t,n)=>{if(n.type===nm)return{...t,state:n.state};let r=e(t,n);return c&&!Object.is(r.state,t.state)&&l(r.state),r},...u),p=d.state,m=I.useRef(p);I.useEffect(()=>{m.current!==p&&(m.current=p,c||l(p))},[p,m,c]);let h=I.useMemo(()=>i===void 0?d:{...d,state:i},[d,i]);return I.useEffect(()=>{c&&!Object.is(i,d.state)&&f({type:nm,state:i})},[i,d.state,c]),[h,f]}Zp(rm,`useControllableStateReducer`);var im=Object.defineProperty,am=(e,t)=>im(e,`name`,{value:t,configurable:!0});function om(e,t){return I.useReducer((e,n)=>t[e][n]??e,e)}am(om,`useStateMachine`);var sm=am(e=>{let{present:t,children:n}=e,r=cm(t),i=typeof n==`function`?n({present:r.isPresent}):I.Children.only(n),a=um(r.ref,fm(i));return typeof n==`function`||r.isPresent?I.cloneElement(i,{ref:a}):null},`Presence`);function cm(e){let[t,n]=I.useState(),r=I.useRef(null),i=I.useRef(e),a=I.useRef(`none`),o=I.useRef(void 0),[s,c]=om(e?`mounted`:`unmounted`,{mounted:{UNMOUNT:`unmounted`,ANIMATION_OUT:`unmountSuspended`},unmountSuspended:{MOUNT:`mounted`,ANIMATION_END:`unmounted`},unmounted:{MOUNT:`mounted`}});return I.useEffect(()=>{s===`mounted`?(a.current=o.current??dm(r.current),o.current=void 0):a.current=`none`},[s]),Wp(()=>{let t=r.current,n=i.current;if(n!==e){let r=a.current,s=dm(t);e?(o.current=s,c(`MOUNT`)):s===`none`||t?.display===`none`?c(`UNMOUNT`):c(n&&r!==s?`ANIMATION_OUT`:`UNMOUNT`),i.current=e}},[e,c]),Wp(()=>{if(t){let e,n=t.ownerDocument.defaultView??window,o=am(a=>{let o=dm(r.current).includes(CSS.escape(a.animationName));if(a.target===t&&o&&(c(`ANIMATION_END`),!i.current)){let r=t.style.animationFillMode;t.style.animationFillMode=`forwards`,e=n.setTimeout(()=>{t.style.animationFillMode===`forwards`&&(t.style.animationFillMode=r)})}},`handleAnimationEnd`),s=am(e=>{e.target===t&&(a.current=dm(r.current))},`handleAnimationStart`);return t.addEventListener(`animationstart`,s),t.addEventListener(`animationcancel`,o),t.addEventListener(`animationend`,o),()=>{n.clearTimeout(e),t.removeEventListener(`animationstart`,s),t.removeEventListener(`animationcancel`,o),t.removeEventListener(`animationend`,o)}}c(`ANIMATION_END`)},[t,c]),{isPresent:[`mounted`,`unmountSuspended`].includes(s),ref:I.useCallback(e=>{if(e){let t=getComputedStyle(e);r.current=t,o.current=dm(t)}else r.current=null;n(e)},[])}}am(cm,`usePresence`);function lm(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}am(lm,`setRef`);function um(...e){let t=I.useRef(e);return t.current=e,I.useCallback(e=>{let n=t.current,r=!1,i=n.map(t=>{let n=lm(t,e);return!r&&typeof n==`function`&&(r=!0),n});if(r)return()=>{for(let e=0;e<i.length;e++){let t=i[e];typeof t==`function`?t():lm(n[e],null)}}},[])}am(um,`useStableComposedRefs`);function dm(e){return e?.animationName||`none`}am(dm,`getAnimationName`);function fm(e){let t=Object.getOwnPropertyDescriptor(e.props,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}am(fm,`getElementRef`);var pm=Object.defineProperty,mm=(e,t)=>pm(e,`name`,{value:t,configurable:!0}),hm=I.useId||(()=>void 0),gm=0;function _m(e){let[t,n]=I.useState(hm());return Wp(()=>{e||n(e=>e??String(gm++))},[e]),e||(t?`radix-${t}`:``)}mm(_m,`useId`);var vm=Object.defineProperty,ym=(e,t)=>vm(e,`name`,{value:t,configurable:!0});function bm(e){let t=I.useRef(e);return I.useEffect(()=>{t.current=e}),I.useMemo(()=>((...e)=>t.current?.(...e)),[])}ym(bm,`useCallbackRef`);var xm=Object.defineProperty,Sm=(e,t)=>xm(e,`name`,{value:t,configurable:!0}),Cm=`dismissableLayer.update`,wm=`dismissableLayer.pointerDownOutside`,Tm=`dismissableLayer.focusOutside`,Em,Dm=I.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Om=I.forwardRef(Sm(function(e,t){let{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,u=I.useContext(Dm),[d,f]=I.useState(null),p=d?.ownerDocument??globalThis?.document,[,m]=I.useState({}),h=op(t,f),g=Array.from(u.layers),[_]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),v=_?g.indexOf(_):-1,y=d?g.indexOf(d):-1,b=u.layersWithOutsidePointerEventsDisabled.size>0,x=y>=v,S=I.useRef(!1),C=jm(e=>{a?.(e),s?.(e),e.defaultPrevented||c?.()},{ownerDocument:p,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:S,dismissableSurfaces:u.dismissableSurfaces,shouldHandlePointerDownOutside:I.useCallback(e=>{if(!(e instanceof Node))return!1;let t=[...u.branches].some(t=>t.contains(e));return x&&!t},[u.branches,x])}),w=Mm(e=>{if(r&&S.current)return;let t=e.target;[...u.branches].some(e=>e.contains(t))||(o?.(e),s?.(e),e.defaultPrevented||c?.())},p),T=d?y===g.length-1:!1,E=bm(e=>{e.key===`Escape`&&(i?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))});return I.useEffect(()=>{if(T)return p.addEventListener(`keydown`,E,{capture:!0}),()=>p.removeEventListener(`keydown`,E,{capture:!0})},[p,T,E]),I.useEffect(()=>{if(d)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Em=p.body.style.pointerEvents,p.body.style.pointerEvents=`none`),u.layersWithOutsidePointerEventsDisabled.add(d)),u.layers.add(d),Nm(),()=>{n&&(u.layersWithOutsidePointerEventsDisabled.delete(d),u.layersWithOutsidePointerEventsDisabled.size===0&&(p.body.style.pointerEvents=Em))}},[d,p,n,u]),I.useEffect(()=>()=>{d&&(u.layers.delete(d),u.layersWithOutsidePointerEventsDisabled.delete(d),Nm())},[d,u]),I.useEffect(()=>{let e=Sm(()=>m({}),`handleUpdate`);return document.addEventListener(Cm,e),()=>document.removeEventListener(Cm,e)},[]),(0,L.jsx)(J.div,{...l,ref:h,style:{pointerEvents:b?x?`auto`:`none`:void 0,...e.style},onFocusCapture:zp(e.onFocusCapture,w.onFocusCapture),onBlurCapture:zp(e.onBlurCapture,w.onBlurCapture),onPointerDownCapture:zp(e.onPointerDownCapture,C.onPointerDownCapture)})},`DismissableLayer`));function km(){let e=I.useContext(Dm),[t,n]=I.useState(null);return I.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}Sm(km,`useDismissableLayerSurface`);var Am=Sm(()=>!0,`IS_TRUE`);function jm(e,t){let{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:o=Am}=t,s=bm(e),c=I.useRef(!1),l=I.useRef(!1),u=I.useRef(new Map),d=I.useRef(()=>{});return I.useEffect(()=>{function e(){l.current=!1,i.current=!1,u.current.clear()}Sm(e,`resetOutsideInteraction`);function t(){return Array.from(u.current.values()).some(Boolean)}Sm(t,`isOutsideInteractionIntercepted`);function f(e){if(!l.current)return;let t=e.target;t instanceof Node&&[...a].some(e=>e.contains(t))||u.current.set(e.type,!0),e.type===`click`&&window.setTimeout(()=>{l.current&&d.current()},0)}Sm(f,`handleInteractionCapture`);function p(e){l.current&&u.current.set(e.type,!1)}Sm(p,`handleInteractionBubble`);let m=Sm(a=>{if(a.target&&!c.current){let f=function(){n.removeEventListener(`click`,d.current);let r=t();e(),r||Pm(wm,s,p,{discrete:!0})};if(Sm(f,`handleAndDispatchPointerDownOutsideEvent`),!o(a.target)){n.removeEventListener(`click`,d.current),e(),c.current=!1;return}let p={originalEvent:a};l.current=!0,i.current=r&&a.button===0,u.current.clear(),!r||a.button!==0?f():(n.removeEventListener(`click`,d.current),d.current=f,n.addEventListener(`click`,d.current,{once:!0}))}else n.removeEventListener(`click`,d.current),e();c.current=!1},`handlePointerDown`),h=[`pointerup`,`mousedown`,`mouseup`,`touchstart`,`touchend`,`click`];for(let e of h)n.addEventListener(e,f,!0),n.addEventListener(e,p);let g=window.setTimeout(()=>{n.addEventListener(`pointerdown`,m)},0);return()=>{window.clearTimeout(g),n.removeEventListener(`pointerdown`,m),n.removeEventListener(`click`,d.current);for(let e of h)n.removeEventListener(e,f,!0),n.removeEventListener(e,p)}},[n,s,r,i,a,o]),{onPointerDownCapture:Sm(()=>c.current=!0,`onPointerDownCapture`)}}Sm(jm,`usePointerDownOutside`);function Mm(e,t=globalThis?.document){let n=bm(e),r=I.useRef(!1);return I.useEffect(()=>{let e=Sm(e=>{e.target&&!r.current&&Pm(Tm,n,{originalEvent:e},{discrete:!1})},`handleFocus`);return t.addEventListener(`focusin`,e),()=>t.removeEventListener(`focusin`,e)},[t,n]),{onFocusCapture:Sm(()=>r.current=!0,`onFocusCapture`),onBlurCapture:Sm(()=>r.current=!1,`onBlurCapture`)}}Sm(Mm,`useFocusOutside`);function Nm(){let e=new CustomEvent(Cm);document.dispatchEvent(e)}Sm(Nm,`dispatchUpdate`);function Pm(e,t,n,{discrete:r}){let i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Ep(i,a):i.dispatchEvent(a)}Sm(Pm,`handleAndDispatchCustomEvent`);var Fm=Object.defineProperty,Im=(e,t)=>Fm(e,`name`,{value:t,configurable:!0}),Lm=`focusScope.autoFocusOnMount`,Rm=`focusScope.autoFocusOnUnmount`,zm={bubbles:!1,cancelable:!0},Bm=I.forwardRef(Im(function(e,t){let{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...o}=e,[s,c]=I.useState(null),l=bm(i),u=bm(a),d=I.useRef(null),f=op(t,c),p=I.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;I.useEffect(()=>{if(r){let e=function(e){if(p.paused||!s)return;let t=e.target;s.contains(t)?d.current=t:qm(d.current,{select:!0})},t=function(e){if(p.paused||!s)return;let t=e.relatedTarget;t!==null&&(s.contains(t)||qm(d.current,{select:!0}))},n=function(e){if(document.activeElement===document.body)for(let t of e)t.removedNodes.length>0&&qm(s)};Im(e,`handleFocusIn`),Im(t,`handleFocusOut`),Im(n,`handleMutations`),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t);let r=new MutationObserver(n);return s&&r.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t),r.disconnect()}}},[r,s,p.paused]),I.useEffect(()=>{if(s){Jm.add(p);let e=document.activeElement;if(!s.contains(e)){let t=new CustomEvent(Lm,zm);s.addEventListener(Lm,l),s.dispatchEvent(t),t.defaultPrevented||(Vm(Zm(Um(s)),{select:!0}),document.activeElement===e&&qm(s))}return()=>{s.removeEventListener(Lm,l),setTimeout(()=>{let t=new CustomEvent(Rm,zm);s.addEventListener(Rm,u),s.dispatchEvent(t),t.defaultPrevented||qm(e??document.body,{select:!0}),s.removeEventListener(Rm,u),Jm.remove(p)},0)}}},[s,l,u,p]);let m=I.useCallback(e=>{if(!n&&!r||p.paused)return;let t=e.key===`Tab`&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){let t=e.currentTarget,[r,a]=Hm(t);r&&a?!e.shiftKey&&i===a?(e.preventDefault(),n&&qm(r,{select:!0})):e.shiftKey&&i===r&&(e.preventDefault(),n&&qm(a,{select:!0})):i===t&&e.preventDefault()}},[n,r,p.paused]);return(0,L.jsx)(J.div,{tabIndex:-1,...o,ref:f,onKeyDown:m})},`FocusScope`));function Vm(e,{select:t=!1}={}){let n=document.activeElement;for(let r of e)if(qm(r,{select:t}),document.activeElement!==n)return}Im(Vm,`focusFirst`);function Hm(e){let t=Um(e);return[Wm(t,e),Wm(t.reverse(),e)]}Im(Hm,`getTabbableEdges`);function Um(e){let t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:Im(e=>{let t=e.tagName===`INPUT`&&e.type===`hidden`;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},`acceptNode`)});for(;n.nextNode();)t.push(n.currentNode);return t}Im(Um,`getTabbableCandidates`);function Wm(e,t){let n=typeof t.checkVisibility==`function`&&t.checkVisibility({checkVisibilityCSS:!0});for(let r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):Gm(r,{upTo:t})))return r}Im(Wm,`findVisible`);function Gm(e,{upTo:t}){if(getComputedStyle(e).visibility===`hidden`)return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display===`none`)return!0;e=e.parentElement}return!1}Im(Gm,`isHidden`);function Km(e){return e instanceof HTMLInputElement&&`select`in e}Im(Km,`isSelectableInput`);function qm(e,{select:t=!1}={}){if(e&&e.focus){let n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Km(e)&&t&&e.select()}}Im(qm,`focus`);var Jm=Ym();function Ym(){let e=[];return{add(t){let n=e[0];t!==n&&n?.pause(),e=Xm(e,t),e.unshift(t)},remove(t){e=Xm(e,t),e[0]?.resume()}}}Im(Ym,`createFocusScopesStack`);function Xm(e,t){let n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}Im(Xm,`arrayRemove`);function Zm(e){return e.filter(e=>e.tagName!==`A`)}Im(Zm,`removeLinks`);var Qm=Object.defineProperty,$m=I.forwardRef(((e,t)=>Qm(e,`name`,{value:t,configurable:!0}))(function(e,t){let{container:n,...r}=e,[i,a]=I.useState(!1);Wp(()=>a(!0),[]);let o=n||i&&globalThis?.document?.body;return o?sp.createPortal((0,L.jsx)(J.div,{...r,ref:t}),o):null},`Portal`)),eh=Object.defineProperty,th=(e,t)=>eh(e,`name`,{value:t,configurable:!0}),nh=0,rh=null;function ih(e){return ah(),e.children}th(ih,`FocusGuards`);function ah(){I.useEffect(()=>{rh||={start:oh(),end:oh()};let{start:e,end:t}=rh;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement(`afterbegin`,e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement(`beforeend`,t),nh++,()=>{nh===1&&(rh?.start.remove(),rh?.end.remove(),rh=null),nh=Math.max(0,nh-1)}},[])}th(ah,`useFocusGuards`);function oh(){let e=document.createElement(`span`);return e.setAttribute(`data-radix-focus-guard`,``),e.tabIndex=0,e.style.outline=`none`,e.style.opacity=`0`,e.style.position=`fixed`,e.style.pointerEvents=`none`,e}th(oh,`createFocusGuard`);var sh=function(){return sh=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},sh.apply(this,arguments)};function ch(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function lh(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var uh=`right-scroll-bar-position`,dh=`width-before-scroll-bar`,fh=`with-scroll-bars-hidden`,ph=`--removed-body-scroll-bar-size`;function mh(e,t){return typeof e==`function`?e(t):e&&(e.current=t),e}function hh(e,t){var n=(0,I.useState)(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(e){var t=n.value;t!==e&&(n.value=e,n.callback(e,t))}}}})[0];return n.callback=t,n.facade}var gh=typeof window<`u`?I.useLayoutEffect:I.useEffect,_h=new WeakMap;function vh(e,t){var n=hh(t||null,function(t){return e.forEach(function(e){return mh(e,t)})});return gh(function(){var t=_h.get(n);if(t){var r=new Set(t),i=new Set(e),a=n.current;r.forEach(function(e){i.has(e)||mh(e,null)}),i.forEach(function(e){r.has(e)||mh(e,a)})}_h.set(n,e)},[e]),n}function yh(e){return e}function bh(e,t){t===void 0&&(t=yh);var n=[],r=!1;return{read:function(){if(r)throw Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(e){var i=t(e,r);return n.push(i),function(){n=n.filter(function(e){return e!==i})}},assignSyncMedium:function(e){for(r=!0;n.length;){var t=n;n=[],t.forEach(e)}n={push:function(t){return e(t)},filter:function(){return n}}},assignMedium:function(e){r=!0;var t=[];if(n.length){var i=n;n=[],i.forEach(e),t=n}var a=function(){var n=t;t=[],n.forEach(e)},o=function(){return Promise.resolve().then(a)};o(),n={push:function(e){t.push(e),o()},filter:function(e){return t=t.filter(e),n}}}}}function xh(e){e===void 0&&(e={});var t=bh(null);return t.options=sh({async:!0,ssr:!1},e),t}var Sh=function(e){var t=e.sideCar,n=ch(e,[`sideCar`]);if(!t)throw Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw Error(`Sidecar medium not found`);return I.createElement(r,sh({},n))};Sh.isSideCarExport=!0;function Ch(e,t){return e.useMedium(t),Sh}var wh=xh(),Th=function(){},Eh=I.forwardRef(function(e,t){var n=I.useRef(null),r=I.useState({onScrollCapture:Th,onWheelCapture:Th,onTouchMoveCapture:Th}),i=r[0],a=r[1],o=e.forwardProps,s=e.children,c=e.className,l=e.removeScrollBar,u=e.enabled,d=e.shards,f=e.sideCar,p=e.noRelative,m=e.noIsolation,h=e.inert,g=e.allowPinchZoom,_=e.as,v=_===void 0?`div`:_,y=e.gapMode,b=ch(e,[`forwardProps`,`children`,`className`,`removeScrollBar`,`enabled`,`shards`,`sideCar`,`noRelative`,`noIsolation`,`inert`,`allowPinchZoom`,`as`,`gapMode`]),x=f,S=vh([n,t]),C=sh(sh({},b),i);return I.createElement(I.Fragment,null,u&&I.createElement(x,{sideCar:wh,removeScrollBar:l,shards:d,noRelative:p,noIsolation:m,inert:h,setCallbacks:a,allowPinchZoom:!!g,lockRef:n,gapMode:y}),o?I.cloneElement(I.Children.only(s),sh(sh({},C),{ref:S})):I.createElement(v,sh({},C,{className:c,ref:S}),s))});Eh.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Eh.classNames={fullWidth:dh,zeroRight:uh};var Dh=function(){if(typeof __webpack_nonce__<`u`)return __webpack_nonce__};function Oh(){if(!document)return null;var e=document.createElement(`style`);e.type=`text/css`;var t=Dh();return t&&e.setAttribute(`nonce`,t),e}function kh(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Ah(e){(document.head||document.getElementsByTagName(`head`)[0]).appendChild(e)}var jh=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Oh())&&(kh(t,n),Ah(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Mh=function(){var e=jh();return function(t,n){I.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Nh=function(){var e=Mh();return function(t){var n=t.styles,r=t.dynamic;return e(n,r),null}},Ph={left:0,top:0,right:0,gap:0},Fh=function(e){return parseInt(e||``,10)||0},Ih=function(e){var t=window.getComputedStyle(document.body),n=t[e===`padding`?`paddingLeft`:`marginLeft`],r=t[e===`padding`?`paddingTop`:`marginTop`],i=t[e===`padding`?`paddingRight`:`marginRight`];return[Fh(n),Fh(r),Fh(i)]},Lh=function(e){if(e===void 0&&(e=`margin`),typeof window>`u`)return Ph;var t=Ih(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Rh=Nh(),zh=`data-scroll-locked`,Bh=function(e,t,n,r){var i=e.left,a=e.top,o=e.right,s=e.gap;return n===void 0&&(n=`margin`),`
21
+ .${fh} {
22
+ overflow: hidden ${r};
23
+ padding-right: ${s}px ${r};
24
+ }
25
+ body[${zh}] {
26
+ overflow: hidden ${r};
27
+ overscroll-behavior: contain;
28
+ ${[t&&`position: relative ${r};`,n===`margin`&&`
29
+ padding-left: ${i}px;
30
+ padding-top: ${a}px;
31
+ padding-right: ${o}px;
32
+ margin-left:0;
33
+ margin-top:0;
34
+ margin-right: ${s}px ${r};
35
+ `,n===`padding`&&`padding-right: ${s}px ${r};`].filter(Boolean).join(``)}
36
+ }
37
+
38
+ .${uh} {
39
+ right: ${s}px ${r};
40
+ }
41
+
42
+ .${dh} {
43
+ margin-right: ${s}px ${r};
44
+ }
45
+
46
+ .${uh} .${uh} {
47
+ right: 0 ${r};
48
+ }
49
+
50
+ .${dh} .${dh} {
51
+ margin-right: 0 ${r};
52
+ }
53
+
54
+ body[${zh}] {
55
+ ${ph}: ${s}px;
56
+ }
57
+ `},Vh=function(){var e=parseInt(document.body.getAttribute(`data-scroll-locked`)||`0`,10);return isFinite(e)?e:0},Hh=function(){I.useEffect(function(){return document.body.setAttribute(zh,(Vh()+1).toString()),function(){var e=Vh()-1;e<=0?document.body.removeAttribute(zh):document.body.setAttribute(zh,e.toString())}},[])},Uh=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?`margin`:r;Hh();var a=I.useMemo(function(){return Lh(i)},[i]);return I.createElement(Rh,{styles:Bh(a,!t,i,n?``:`!important`)})},Wh=!1;if(typeof window<`u`)try{var Gh=Object.defineProperty({},"passive",{get:function(){return Wh=!0,!0}});window.addEventListener(`test`,Gh,Gh),window.removeEventListener(`test`,Gh,Gh)}catch{Wh=!1}var Kh=Wh?{passive:!1}:!1,qh=function(e){return e.tagName===`TEXTAREA`},Jh=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!==`hidden`&&!(n.overflowY===n.overflowX&&!qh(e)&&n[t]===`visible`)},Yh=function(e){return Jh(e,`overflowY`)},Xh=function(e){return Jh(e,`overflowX`)},Zh=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<`u`&&r instanceof ShadowRoot&&(r=r.host),eg(e,r)){var i=tg(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Qh=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},$h=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},eg=function(e,t){return e===`v`?Yh(t):Xh(t)},tg=function(e,t){return e===`v`?Qh(t):$h(t)},ng=function(e,t){return e===`h`&&t===`rtl`?-1:1},rg=function(e,t,n,r,i){var a=ng(e,window.getComputedStyle(t).direction),o=a*r,s=n.target,c=t.contains(s),l=!1,u=o>0,d=0,f=0;do{if(!s)break;var p=tg(e,s),m=p[0],h=p[1]-p[2]-a*m;(m||h)&&eg(e,s)&&(d+=h,f+=m);var g=s.parentNode;s=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}while(!c&&s!==document.body||c&&(t.contains(s)||t===s));return(u&&(i&&Math.abs(d)<1||!i&&o>d)||!u&&(i&&Math.abs(f)<1||!i&&-o>f))&&(l=!0),l},ig=function(e){return`changedTouches`in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},ag=function(e){return[e.deltaX,e.deltaY]},og=function(e){return e&&`current`in e?e.current:e},sg=function(e,t){return e[0]===t[0]&&e[1]===t[1]},cg=function(e){return`
58
+ .block-interactivity-${e} {pointer-events: none;}
59
+ .allow-interactivity-${e} {pointer-events: all;}
60
+ `},lg=0,ug=[];function dg(e){var t=I.useRef([]),n=I.useRef([0,0]),r=I.useRef(),i=I.useState(lg++)[0],a=I.useState(Nh)[0],o=I.useRef(e);I.useEffect(function(){o.current=e},[e]),I.useEffect(function(){if(e.inert){document.body.classList.add(`block-interactivity-${i}`);var t=lh([e.lockRef.current],(e.shards||[]).map(og),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add(`allow-interactivity-${i}`)}),function(){document.body.classList.remove(`block-interactivity-${i}`),t.forEach(function(e){return e.classList.remove(`allow-interactivity-${i}`)})}}},[e.inert,e.lockRef.current,e.shards]);var s=I.useCallback(function(e,t){if(`touches`in e&&e.touches.length===2||e.type===`wheel`&&e.ctrlKey)return!o.current.allowPinchZoom;var i=ig(e),a=n.current,s=`deltaX`in e?e.deltaX:a[0]-i[0],c=`deltaY`in e?e.deltaY:a[1]-i[1],l,u=e.target,d=Math.abs(s)>Math.abs(c)?`h`:`v`;if(`touches`in e&&d===`h`&&u.type===`range`)return!1;var f=window.getSelection(),p=f&&f.anchorNode;if(p&&(p===u||p.contains(u)))return!1;var m=Zh(d,u);if(!m)return!0;if(m?l=d:(l=d===`v`?`h`:`v`,m=Zh(d,u)),!m)return!1;if(!r.current&&`changedTouches`in e&&(s||c)&&(r.current=l),!l)return!0;var h=r.current||l;return rg(h,t,e,h===`h`?s:c,!0)},[]),c=I.useCallback(function(e){var n=e;if(!(!ug.length||ug[ug.length-1]!==a)){var r=`deltaY`in n?ag(n):ig(n),i=t.current.filter(function(e){return e.name===n.type&&(e.target===n.target||n.target===e.shadowParent)&&sg(e.delta,r)})[0];if(i&&i.should){n.cancelable&&n.preventDefault();return}if(!i){var c=(o.current.shards||[]).map(og).filter(Boolean).filter(function(e){return e.contains(n.target)});(c.length>0?s(n,c[0]):!o.current.noIsolation)&&n.cancelable&&n.preventDefault()}}},[]),l=I.useCallback(function(e,n,r,i){var a={name:e,delta:n,target:r,should:i,shadowParent:fg(r)};t.current.push(a),setTimeout(function(){t.current=t.current.filter(function(e){return e!==a})},1)},[]),u=I.useCallback(function(e){n.current=ig(e),r.current=void 0},[]),d=I.useCallback(function(t){l(t.type,ag(t),t.target,s(t,e.lockRef.current))},[]),f=I.useCallback(function(t){l(t.type,ig(t),t.target,s(t,e.lockRef.current))},[]);I.useEffect(function(){return ug.push(a),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener(`wheel`,c,Kh),document.addEventListener(`touchmove`,c,Kh),document.addEventListener(`touchstart`,u,Kh),function(){ug=ug.filter(function(e){return e!==a}),document.removeEventListener(`wheel`,c,Kh),document.removeEventListener(`touchmove`,c,Kh),document.removeEventListener(`touchstart`,u,Kh)}},[]);var p=e.removeScrollBar,m=e.inert;return I.createElement(I.Fragment,null,m?I.createElement(a,{styles:cg(i)}):null,p?I.createElement(Uh,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function fg(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var pg=Ch(wh,dg),mg=I.forwardRef(function(e,t){return I.createElement(Eh,sh({},e,{ref:t,sideCar:pg}))});mg.classNames=Eh.classNames;var hg=function(e){return typeof document>`u`?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},gg=new WeakMap,_g=new WeakMap,vg={},yg=0,bg=function(e){return e&&(e.host||bg(e.parentNode))},xg=function(e,t){return t.map(function(t){if(e.contains(t))return t;var n=bg(t);return n&&e.contains(n)?n:(console.error(`aria-hidden`,t,`in not contained inside`,e,`. Doing nothing`),null)}).filter(function(e){return!!e})},Sg=function(e,t,n,r){var i=xg(t,Array.isArray(e)?e:[e]);vg[n]||(vg[n]=new WeakMap);var a=vg[n],o=[],s=new Set,c=new Set(i),l=function(e){!e||s.has(e)||(s.add(e),l(e.parentNode))};i.forEach(l);var u=function(e){!e||c.has(e)||Array.prototype.forEach.call(e.children,function(e){if(s.has(e))u(e);else try{var t=e.getAttribute(r),i=t!==null&&t!==`false`,c=(gg.get(e)||0)+1,l=(a.get(e)||0)+1;gg.set(e,c),a.set(e,l),o.push(e),c===1&&i&&_g.set(e,!0),l===1&&e.setAttribute(n,`true`),i||e.setAttribute(r,`true`)}catch(t){console.error(`aria-hidden: cannot operate on `,e,t)}})};return u(t),s.clear(),yg++,function(){o.forEach(function(e){var t=gg.get(e)-1,i=a.get(e)-1;gg.set(e,t),a.set(e,i),t||(_g.has(e)||e.removeAttribute(r),_g.delete(e)),i||e.removeAttribute(n)}),yg--,yg||(gg=new WeakMap,gg=new WeakMap,_g=new WeakMap,vg={})}},Cg=function(e,t,n){n===void 0&&(n=`data-aria-hidden`);var r=Array.from(Array.isArray(e)?e:[e]),i=t||hg(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll(`[aria-live], script`))),Sg(r,i,n,`aria-hidden`)):function(){return null}},wg=Object.defineProperty,Tg=(e,t)=>wg(e,`name`,{value:t,configurable:!0}),Eg=`Dialog`,[Dg,Og]=Pp(Eg),[kg,Ag]=Dg(Eg),jg=Tg(e=>{let{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!0}=e,s=I.useRef(null),c=I.useRef(null),[l,u]=$p({prop:r,defaultProp:i??!1,onChange:a,caller:Eg}),[d,f]=I.useState(0),[p,m]=I.useState(0);return(0,L.jsx)(kg,{scope:t,triggerRef:s,contentRef:c,contentId:_m(),titleId:_m(),descriptionId:_m(),titlePresent:d>0,descriptionPresent:p>0,setTitleCount:f,setDescriptionCount:m,open:l,onOpenChange:u,onOpenToggle:I.useCallback(()=>u(e=>!e),[u]),modal:o,children:n})},`Dialog`),Mg=`DialogPortal`,[Ng,Pg]=Dg(Mg,{forceMount:void 0}),Fg=Tg(e=>{let{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=Ag(Mg,t);return(0,L.jsx)(Ng,{scope:t,forceMount:n,children:I.Children.map(r,e=>(0,L.jsx)(sm,{present:n||a.open,children:(0,L.jsx)($m,{asChild:!0,container:i,children:e})}))})},`DialogPortal`),Ig=`DialogOverlay`,Lg=I.forwardRef(Tg(function(e,t){let n=Pg(Ig,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Ag(Ig,e.__scopeDialog);return a.modal?(0,L.jsx)(sm,{present:r||a.open,children:(0,L.jsx)(zg,{...i,ref:t})}):null},`DialogOverlay`)),Rg=up(`DialogOverlay.RemoveScroll`),zg=I.forwardRef(Tg(function(e,t){let{__scopeDialog:n,...r}=e,i=Ag(Ig,n),a=op(t,km());return(0,L.jsx)(mg,{as:Rg,allowPinchZoom:!0,shards:[i.contentRef],children:(0,L.jsx)(J.div,{"data-state":Zg(i.open),...r,ref:a,style:{pointerEvents:`auto`,...r.style}})})},`DialogOverlayImpl`)),Bg=`DialogContent`,Vg=I.forwardRef(Tg(function(e,t){let n=Pg(Bg,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Ag(Bg,e.__scopeDialog);return(0,L.jsx)(sm,{present:r||a.open,children:a.modal?(0,L.jsx)(Hg,{...i,ref:t}):(0,L.jsx)(Ug,{...i,ref:t})})},`DialogContent`)),Hg=I.forwardRef(Tg(function(e,t){let n=Ag(Bg,e.__scopeDialog),r=I.useRef(null),i=op(t,n.contentRef,r);return I.useEffect(()=>{let e=r.current;if(e)return Cg(e)},[]),(0,L.jsx)(Wg,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:zp(e.onCloseAutoFocus,e=>{e.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:zp(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0;(t.button===2||n)&&e.preventDefault()}),onFocusOutside:zp(e.onFocusOutside,e=>e.preventDefault())})},`DialogContentModal`)),Ug=I.forwardRef(Tg(function(e,t){let n=Ag(Bg,e.__scopeDialog),r=I.useRef(!1),i=I.useRef(!1);return(0,L.jsx)(Wg,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})},`DialogContentNonModal`)),Wg=I.forwardRef(Tg(function(e,t){let{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...o}=e,s=Ag(Bg,n);return ah(),(0,L.jsx)(L.Fragment,{children:(0,L.jsx)(Bm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,L.jsx)(Om,{role:`dialog`,id:s.contentId,"aria-describedby":s.descriptionPresent?s.descriptionId:void 0,"aria-labelledby":s.titlePresent?s.titleId:void 0,"data-state":Zg(s.open),...o,ref:t,deferPointerDownOutside:!0,onDismiss:()=>s.onOpenChange(!1)})})})},`DialogContentImpl`)),Gg=`DialogTitle`,Kg=I.forwardRef(Tg(function(e,t){let{__scopeDialog:n,...r}=e,i=Ag(Gg,n),{setTitleCount:a}=i;return Wp(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,L.jsx)(J.h2,{id:i.titleId,...r,ref:t})},`DialogTitle`)),qg=`DialogDescription`,Jg=I.forwardRef(Tg(function(e,t){let{__scopeDialog:n,...r}=e,i=Ag(qg,n),{setDescriptionCount:a}=i;return Wp(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,L.jsx)(J.p,{id:i.descriptionId,...r,ref:t})},`DialogDescription`)),Yg=`DialogClose`,Xg=I.forwardRef(Tg(function(e,t){let{__scopeDialog:n,...r}=e,i=Ag(Yg,n);return(0,L.jsx)(J.button,{type:`button`,...r,ref:t,onClick:zp(e.onClick,()=>i.onOpenChange(!1))})},`DialogClose`));function Zg(e){return e?`open`:`closed`}Tg(Zg,`getState`);var Qg=Object.defineProperty,$g=(e,t)=>Qg(e,`name`,{value:t,configurable:!0});function e_(e){let[t,n]=I.useState(void 0);return Wp(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});let t=new ResizeObserver(t=>{if(!Array.isArray(t)||!t.length)return;let r=t[0],i,a;if(`borderBoxSize`in r){let e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;i=t.inlineSize,a=t.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return t.observe(e,{box:`border-box`}),()=>t.unobserve(e)}n(void 0)},[e]),t}$g(e_,`useSize`);var t_=[`top`,`right`,`bottom`,`left`],n_=Math.min,r_=Math.max,i_=Math.round,a_=Math.floor,o_=e=>({x:e,y:e}),s_={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function c_(e,t,n){return r_(e,n_(t,n))}function l_(e,t){return typeof e==`function`?e(t):e}function u_(e){return e.split(`-`)[0]}function d_(e){return e.split(`-`)[1]}function f_(e){return e===`x`?`y`:`x`}function p_(e){return e===`y`?`height`:`width`}function m_(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function h_(e){return f_(m_(e))}function g_(e,t,n){n===void 0&&(n=!1);let r=d_(e),i=h_(e),a=p_(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=T_(o)),[o,T_(o)]}function __(e){let t=T_(e);return[v_(e),t,v_(t)]}function v_(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var y_=[`left`,`right`],b_=[`right`,`left`],x_=[`top`,`bottom`],S_=[`bottom`,`top`];function C_(e,t,n){switch(e){case`top`:case`bottom`:return n?t?b_:y_:t?y_:b_;case`left`:case`right`:return t?x_:S_;default:return[]}}function w_(e,t,n,r){let i=d_(e),a=C_(u_(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(v_)))),a}function T_(e){let t=u_(e);return s_[t]+e.slice(t.length)}function E_(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function D_(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:E_(e)}function O_(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function k_(e,t,n){let{reference:r,floating:i}=e,a=m_(t),o=h_(t),s=p_(o),c=u_(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=d_(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function A_(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=l_(t,e),p=D_(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=O_(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=O_(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var j_=50,M_=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:A_},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=k_(l,r,c),f=r,p=0,m={};for(let n=0;n<a.length;n++){let h=a[n];if(!h)continue;let{name:g,fn:_}=h,{x:v,y,data:b,reset:x}=await _({x:u,y:d,initialPlacement:r,placement:f,strategy:i,middlewareData:m,rects:l,platform:s,elements:{reference:e,floating:t}});u=v??u,d=y??d,m[g]={...m[g],...b},x&&p<j_&&(p++,typeof x==`object`&&(x.placement&&(f=x.placement),x.rects&&(l=x.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):x.rects),{x:u,y:d}=k_(l,f,c)),n=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:m}},N_=e=>({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=l_(e,t)||{};if(l==null)return{};let d=D_(u),f={x:n,y:r},p=h_(i),m=p_(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l)),C=S?S[y]:0;(!C||!await(o.isElement==null?void 0:o.isElement(S)))&&(C=s.floating[y]||a.floating[m]);let w=b/2-x/2,T=C/2-h[m]/2-1,E=n_(d[_],T),D=n_(d[v],T),O=C-h[m]-D,k=C/2-h[m]/2+w,A=c_(E,k,O),j=!c.arrow&&d_(i)!=null&&k!==A&&a.reference[m]/2-(k<E?E:D)-h[m]/2<0,M=j?k<E?k-E:k-O:0;return{[p]:f[p]+M,data:{[p]:A,centerOffset:k-A-M,...j&&{alignmentOffset:M}},reset:j}}}),P_=function(e){return e===void 0&&(e={}),{name:`flip`,options:e,async fn(t){var n;let{placement:r,middlewareData:i,rects:a,initialPlacement:o,platform:s,elements:c}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:f=`bestFit`,fallbackAxisSideDirection:p=`none`,flipAlignment:m=!0,...h}=l_(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let g=u_(r),_=m_(o),v=u_(o)===o,y=await(s.isRTL==null?void 0:s.isRTL(c.floating)),b=d||(v||!m?[T_(o)]:__(o)),x=p!==`none`;!d&&x&&b.push(...w_(o,m,p,y));let S=[o,...b],C=await s.detectOverflow(t,h),w=[],T=i.flip?.overflows||[];if(l&&w.push(C[g]),u){let e=g_(r,a,y);w.push(C[e[0]],C[e[1]])}if(T=[...T,{placement:r,overflows:w}],!w.every(e=>e<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(u!==`alignment`||_===m_(t)||T.every(e=>m_(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=m_(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o}if(r!==n)return{reset:{placement:n}}}return{}}}};function F_(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function I_(e){return t_.some(t=>e[t]>=0)}var L_=function(e){return e===void 0&&(e={}),{name:`hide`,options:e,async fn(t){let{rects:n,platform:r}=t,{strategy:i=`referenceHidden`,...a}=l_(e,t);switch(i){case`referenceHidden`:{let e=F_(await r.detectOverflow(t,{...a,elementContext:`reference`}),n.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:I_(e)}}}case`escaped`:{let e=F_(await r.detectOverflow(t,{...a,altBoundary:!0}),n.floating);return{data:{escapedOffsets:e,escaped:I_(e)}}}default:return{}}}}},R_=new Set([`left`,`top`]);async function z_(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=u_(n),s=d_(n),c=m_(n)===`y`,l=R_.has(o)?-1:1,u=a&&c?-1:1,d=l_(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var B_=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await z_(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},V_=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=l_(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=m_(i),p=f_(f),m=u[p],h=u[f],g=(e,t)=>c_(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},H_=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=l_(e,t),u={x:n,y:r},d=m_(i),f=f_(d),p=u[f],m=u[d],h=l_(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;p<t?p=t:p>n&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=R_.has(u_(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);m<n?m=n:m>r&&(m=r)}return{[f]:p,[d]:m}}}},U_=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=l_(e,t),c=await i.detectOverflow(t,s),l=u_(n),u=d_(n),d=m_(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=n_(p-c[m],g),y=n_(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*r_(c.left,c.right):S=p-2*r_(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function W_(){return typeof window<`u`}function G_(e){return J_(e)?(e.nodeName||``).toLowerCase():`#document`}function K_(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function q_(e){return((J_(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function J_(e){return W_()?e instanceof Node||e instanceof K_(e).Node:!1}function Y_(e){return W_()?e instanceof Element||e instanceof K_(e).Element:!1}function X_(e){return W_()?e instanceof HTMLElement||e instanceof K_(e).HTMLElement:!1}function Z_(e){return!W_()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof K_(e).ShadowRoot}function Q_(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=lv(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function $_(e){return/^(table|td|th)$/.test(G_(e))}function ev(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var tv=/transform|translate|scale|rotate|perspective|filter/,nv=/paint|layout|strict|content/,rv=e=>!!e&&e!==`none`,iv;function av(e){let t=Y_(e)?lv(e):e;return rv(t.transform)||rv(t.translate)||rv(t.scale)||rv(t.rotate)||rv(t.perspective)||!sv()&&(rv(t.backdropFilter)||rv(t.filter))||tv.test(t.willChange||``)||nv.test(t.contain||``)}function ov(e){let t=dv(e);for(;X_(t)&&!cv(t);){if(av(t))return t;if(ev(t))return null;t=dv(t)}return null}function sv(){return iv??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),iv}function cv(e){return/^(html|body|#document)$/.test(G_(e))}function lv(e){return K_(e).getComputedStyle(e)}function uv(e){return Y_(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function dv(e){if(G_(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||Z_(e)&&e.host||q_(e);return Z_(t)?t.host:t}function fv(e){let t=dv(e);return cv(t)?(e.ownerDocument||e).body:X_(t)&&Q_(t)?t:fv(t)}function pv(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=fv(e),i=r===e.ownerDocument?.body,a=K_(r);if(i){let e=mv(a);return t.concat(a,a.visualViewport||[],Q_(r)?r:[],e&&n?pv(e):[])}return t.concat(r,pv(r,[],n))}function mv(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function hv(e){let t=lv(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=X_(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=i_(n)!==a||i_(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function gv(e){return Y_(e)?e:e.contextElement}function _v(e){let t=gv(e);if(!X_(t))return o_(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=hv(t),o=(a?i_(n.width):n.width)/r,s=(a?i_(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var vv=o_(0);function yv(e){let t=K_(e);return!sv()||!t.visualViewport?vv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function bv(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===K_(e)}function xv(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=gv(e),o=o_(1);t&&(r?Y_(r)&&(o=_v(r)):o=_v(e));let s=bv(a,n,r)?yv(a):o_(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=K_(a),t=Y_(r)?K_(r):r,n=e,i=mv(n);for(;i&&t!==n;){let e=_v(i),t=i.getBoundingClientRect(),r=lv(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=K_(i),i=mv(n)}}return O_({width:u,height:d,x:c,y:l})}function Sv(e,t){let n=uv(e).scrollLeft;return t?t.left+n:xv(q_(e)).left+n}function Cv(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Sv(e,n),y:n.top+t.scrollTop}}function wv(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=q_(r),s=t?ev(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=o_(1),u=o_(0),d=X_(r);if((d||!a)&&((G_(r)!==`body`||Q_(o))&&(c=uv(r)),d)){let e=xv(r);l=_v(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?Cv(o,c):o_(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function Tv(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function Ev(e){let t=uv(e),n=e.ownerDocument.body,r=r_(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=r_(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+Sv(e),o=-t.scrollTop;return lv(n).direction===`rtl`&&(a+=r_(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var Dv=25;function Ov(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=K_(e),a=q_(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!sv()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(Sv(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=Dv&&(s-=o)}return{width:s,height:c,x:l,y:u}}function kv(e,t){let n=xv(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=_v(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function Av(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=Ov(e,n,t);else if(t===`document`)r=Ev(q_(e));else if(Y_(t))r=kv(t,n);else{let n=yv(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return O_(r)}function jv(e,t){let n=t.get(e);if(n)return n;let r=pv(e,[],!1).filter(e=>Y_(e)&&G_(e)!==`body`),i=null,a=lv(e).position===`fixed`,o=a?dv(e):e;for(;Y_(o)&&!cv(o);){let e=lv(o),t=av(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=dv(o)}return t.set(e,r),r}function Mv(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?ev(t)?[]:jv(t,this._c):[].concat(n),r],o=Av(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e<a.length;e++){let n=Av(t,a[e],i);s=r_(n.top,s),c=n_(n.right,c),l=n_(n.bottom,l),u=r_(n.left,u)}return{width:c-u,height:l-s,x:u,y:s}}function Nv(e){let{width:t,height:n}=hv(e);return{width:t,height:n}}function Pv(e,t,n){let r=X_(t),i=q_(t),a=n===`fixed`,o=xv(e,!0,a,t),s={scrollLeft:0,scrollTop:0},c=o_(0);if((r||!a)&&((G_(t)!==`body`||Q_(i))&&(s=uv(t)),r)){let e=xv(t,!0,a,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}!r&&i&&(c.x=Sv(i));let l=i&&!r&&!a?Cv(i,s):o_(0);return{x:o.left+s.scrollLeft-c.x-l.x,y:o.top+s.scrollTop-c.y-l.y,width:o.width,height:o.height}}function Fv(e){return lv(e).position===`static`}function Iv(e,t){if(!X_(e)||lv(e).position===`fixed`)return null;if(t)return t(e);let n=e.offsetParent;return q_(e)===n&&(n=n.ownerDocument.body),n}function Lv(e,t){let n=K_(e);if(ev(e))return n;if(!X_(e)){let t=dv(e);for(;t&&!cv(t);){if(Y_(t)&&!Fv(t))return t;t=dv(t)}return n}let r=Iv(e,t);for(;r&&$_(r)&&Fv(r);)r=Iv(r,t);return r&&cv(r)&&Fv(r)&&!av(r)?n:r||ov(e)||n}var Rv=async function(e){let t=this.getOffsetParent||Lv,n=this.getDimensions,r=await n(e.floating);return{reference:Pv(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function zv(e){return lv(e).direction===`rtl`}var Bv={convertOffsetParentRelativeRectToViewportRelativeRect:wv,getDocumentElement:q_,getClippingRect:Mv,getOffsetParent:Lv,getElementRects:Rv,getClientRects:Tv,getDimensions:Nv,getScale:_v,isElement:Y_,isRTL:zv};function Vv(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Hv(e,t,n){let r=null,i,a=q_(e);function o(){var e;clearTimeout(i),(e=r)==null||e.disconnect(),r=null}function s(n,c){n===void 0&&(n=!1),c===void 0&&(c=1),o();let l=e.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=l;if(n||t(),!f||!p)return;let m=a_(d),h=a_(a.clientWidth-(u+f)),g=a_(a.clientHeight-(d+p)),_=a_(u),v={rootMargin:-m+`px `+-h+`px `+-g+`px `+-_+`px`,threshold:r_(0,n_(1,c))||1},y=!0;function b(t){let n=t[0].intersectionRatio;if(!Vv(l,e.getBoundingClientRect()))return s();if(n!==c){if(!y)return s();n?s(!1,n):i=setTimeout(()=>{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=K_(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function Uv(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=gv(e),u=i||a?[...l?pv(l):[],...t?pv(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?Hv(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?xv(e):null;c&&g();function g(){let t=xv(e);h&&!Vv(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var Wv=B_,Gv=V_,Kv=P_,qv=U_,Jv=L_,Yv=N_,Xv=H_,Zv=(e,t,n)=>{let r=new Map,i=n??{},a={...Bv,...i.platform,_c:r};return M_(e,t,{...i,platform:a})},Qv=typeof document<`u`?I.useLayoutEffect:function(){};function $v(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e==`function`&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!$v(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!$v(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function ey(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function ty(e,t){let n=ey(e);return Math.round(t*n)/n}function ny(e){let t=I.useRef(e);return Qv(()=>{t.current=e}),t}function ry(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=I.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=I.useState(r);$v(f,r)||p(r);let[m,h]=I.useState(null),[g,_]=I.useState(null),v=I.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=I.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=I.useRef(null),C=I.useRef(null),w=I.useRef(u),T=c!=null,E=ny(c),D=ny(i),O=ny(l),k=I.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),Zv(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};A.current&&!$v(w.current,t)&&(w.current=t,sp.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);Qv(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let A=I.useRef(!1);Qv(()=>(A.current=!0,()=>{A.current=!1}),[]),Qv(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,k);k()}},[b,x,k,E,T]);let j=I.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),M=I.useMemo(()=>({reference:b,floating:x}),[b,x]),N=I.useMemo(()=>{let e={position:n,left:0,top:0};if(!M.floating)return e;let t=ty(M.floating,u.x),r=ty(M.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...ey(M.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,M.floating,u.x,u.y]);return I.useMemo(()=>({...u,update:k,refs:j,elements:M,floatingStyles:N}),[u,k,j,M,N])}var iy=e=>{function t(e){return{}.hasOwnProperty.call(e,`current`)}return{name:`arrow`,options:e,fn(n){let{element:r,padding:i}=typeof e==`function`?e(n):e;return r&&t(r)?r.current==null?{}:Yv({element:r.current,padding:i}).fn(n):r?Yv({element:r,padding:i}).fn(n):{}}}},ay=(e,t)=>{let n=Wv(e);return{name:n.name,fn:n.fn,options:[e,t]}},oy=(e,t)=>{let n=Gv(e);return{name:n.name,fn:n.fn,options:[e,t]}},sy=(e,t)=>({fn:Xv(e).fn,options:[e,t]}),cy=(e,t)=>{let n=Kv(e);return{name:n.name,fn:n.fn,options:[e,t]}},ly=(e,t)=>{let n=qv(e);return{name:n.name,fn:n.fn,options:[e,t]}},uy=(e,t)=>{let n=Jv(e);return{name:n.name,fn:n.fn,options:[e,t]}},dy=(e,t)=>{let n=iy(e);return{name:n.name,fn:n.fn,options:[e,t]}},fy=Object.defineProperty,py=I.forwardRef(((e,t)=>fy(e,`name`,{value:t,configurable:!0}))(function(e,t){let{children:n,width:r=10,height:i=5,...a}=e;return(0,L.jsx)(J.svg,{...a,ref:t,width:r,height:i,viewBox:`0 0 30 10`,preserveAspectRatio:`none`,children:e.asChild?n:(0,L.jsx)(`polygon`,{points:`0,0 30,0 15,10`})})},`Arrow`)),my=Object.defineProperty,hy=(e,t)=>my(e,`name`,{value:t,configurable:!0}),gy=`Popper`,[_y,vy]=Pp(gy),[yy,by]=_y(gy),xy=hy(e=>{let{__scopePopper:t,children:n}=e,[r,i]=I.useState(null),[a,o]=I.useState(void 0);return(0,L.jsx)(yy,{scope:t,anchor:r,onAnchorChange:i,placementState:a,setPlacementState:o,children:n})},`Popper`),Sy=`PopperAnchor`,Cy=I.forwardRef(hy(function(e,t){let{__scopePopper:n,virtualRef:r,...i}=e,a=by(Sy,n),o=I.useRef(null),s=a.onAnchorChange,c=op(t,I.useCallback(e=>{o.current=e,e&&s(e)},[s])),l=I.useRef(null);I.useEffect(()=>{if(!r)return;let e=l.current;l.current=r.current,e!==l.current&&s(l.current)});let u=a.placementState&&Ny(a.placementState),d=u?.[0],f=u?.[1];return r?null:(0,L.jsx)(J.div,{"data-radix-popper-side":d,"data-radix-popper-align":f,...i,ref:c})},`PopperAnchor`)),wy=`PopperContent`,[Ty,Ey]=_y(wy),Dy=I.forwardRef(hy(function(e,t){let{__scopePopper:n,side:r=`bottom`,sideOffset:i=0,align:a=`center`,alignOffset:o=0,arrowPadding:s=0,avoidCollisions:c=!0,collisionBoundary:l=[],collisionPadding:u=0,sticky:d=`partial`,hideWhenDetached:f=!1,updatePositionStrategy:p=`optimized`,onPlaced:m,...h}=e,g=by(wy,n),[_,v]=I.useState(null),y=op(t,v),[b,x]=I.useState(null),S=e_(b),C=S?.width??0,w=S?.height??0,T=r+(a===`center`?``:`-`+a),E=typeof u==`number`?u:{top:0,right:0,bottom:0,left:0,...u},D=Array.isArray(l)?l:[l],O=D.length>0,k={padding:E,boundary:D.filter(jy),altBoundary:O},{refs:A,floatingStyles:j,placement:M,isPositioned:N,middlewareData:P}=ry({strategy:`fixed`,placement:T,whileElementsMounted:hy((...e)=>Uv(...e,{animationFrame:p===`always`}),`whileElementsMounted`),elements:{reference:g.anchor},middleware:[ay({mainAxis:i+w,alignmentAxis:o}),c&&oy({mainAxis:!0,crossAxis:!1,limiter:d===`partial`?sy():void 0,...k}),c&&cy({...k}),ly({...k,apply:hy(({elements:e,rects:t,availableWidth:n,availableHeight:r})=>{let{width:i,height:a}=t.reference,o=e.floating.style;o.setProperty(`--radix-popper-available-width`,`${n}px`),o.setProperty(`--radix-popper-available-height`,`${r}px`),o.setProperty(`--radix-popper-anchor-width`,`${i}px`),o.setProperty(`--radix-popper-anchor-height`,`${a}px`)},`apply`)}),b&&dy({element:b,padding:s}),My({arrowWidth:C,arrowHeight:w}),f&&uy({strategy:`referenceHidden`,...k,boundary:O?k.boundary:void 0})]}),ee=g.setPlacementState;Wp(()=>(ee(M),()=>{ee(void 0)}),[M,ee]);let[F,te]=Ny(M),ne=bm(m);Wp(()=>{N&&ne?.()},[N,ne]);let re=P.arrow?.x,ie=P.arrow?.y,ae=P.arrow?.centerOffset!==0,[oe,R]=I.useState();return Wp(()=>{_&&R(window.getComputedStyle(_).zIndex)},[_]),(0,L.jsx)(`div`,{ref:A.setFloating,"data-radix-popper-content-wrapper":``,style:{...j,transform:N?j.transform:`translate(0, -200%)`,minWidth:`max-content`,zIndex:oe,"--radix-popper-transform-origin":[P.transformOrigin?.x,P.transformOrigin?.y].join(` `),...P.hide?.referenceHidden&&{visibility:`hidden`,pointerEvents:`none`}},dir:e.dir,children:(0,L.jsx)(Ty,{scope:n,placedSide:F,placedAlign:te,onArrowChange:x,arrowX:re,arrowY:ie,shouldHideArrow:ae,children:(0,L.jsx)(J.div,{"data-side":F,"data-align":te,...h,ref:y,style:{...h.style,animation:N?h.style?.animation:`none`}})})})},`PopperContent`)),Oy=`PopperArrow`,ky={top:`bottom`,right:`left`,bottom:`top`,left:`right`},Ay=I.forwardRef(hy(function(e,t){let{__scopePopper:n,...r}=e,i=Ey(Oy,n),a=ky[i.placedSide];return(0,L.jsx)(`span`,{ref:i.onArrowChange,style:{position:`absolute`,left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:``,right:`0 0`,bottom:`center 0`,left:`100% 0`}[i.placedSide],transform:{top:`translateY(100%)`,right:`translateY(50%) rotate(90deg) translateX(-50%)`,bottom:`rotate(180deg)`,left:`translateY(50%) rotate(-90deg) translateX(50%)`}[i.placedSide],visibility:i.shouldHideArrow?`hidden`:void 0},children:(0,L.jsx)(py,{...r,ref:t,style:{...r.style,display:`block`}})})},`PopperArrow`));function jy(e){return e!==null}hy(jy,`isNotNull`);var My=hy(e=>({name:`transformOrigin`,options:e,fn(t){let{placement:n,rects:r,middlewareData:i}=t,a=i.arrow?.centerOffset!==0,o=a?0:e.arrowWidth,s=a?0:e.arrowHeight,[c,l]=Ny(n),u={start:`0%`,center:`50%`,end:`100%`}[l],d=(i.arrow?.x??0)+o/2,f=(i.arrow?.y??0)+s/2,p=``,m=``;return c===`bottom`?(p=a?u:`${d}px`,m=`${-s}px`):c===`top`?(p=a?u:`${d}px`,m=`${r.floating.height+s}px`):c===`right`?(p=`${-s}px`,m=a?u:`${f}px`):c===`left`&&(p=`${r.floating.width+s}px`,m=a?u:`${f}px`),{data:{x:p,y:m}}}}),`transformOrigin`);function Ny(e){let[t,n=`center`]=e.split(`-`);return[t,n]}hy(Ny,`getSideAndAlignFromPlacement`);var Py=xy,Fy=Cy,Iy=Dy,Ly=Ay,Ry=Object.defineProperty,Y=(e,t)=>Ry(e,`name`,{value:t,configurable:!0}),[zy,By]=Pp(`Tooltip`,[vy]),Vy=vy(),Hy=`TooltipProvider`,Uy=700,Wy=`tooltip.open`,[Gy,Ky]=zy(Hy),qy=Y(e=>{let{__scopeTooltip:t,delayDuration:n=Uy,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,o=I.useRef(!0),s=I.useRef(!1),c=I.useRef(0);return I.useEffect(()=>{let e=c.current;return()=>window.clearTimeout(e)},[]),(0,L.jsx)(Gy,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:I.useCallback(()=>{r<=0||(window.clearTimeout(c.current),o.current=!1)},[r]),onClose:I.useCallback(()=>{r<=0||(window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.current=!0,r))},[r]),isPointerInTransitRef:s,onPointerInTransitChange:I.useCallback(e=>{s.current=e},[]),disableHoverableContent:i,children:a})},`TooltipProvider`),Jy=`Tooltip`,[Yy,Xy]=zy(Jy),Zy=Y(e=>{let{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:a,disableHoverableContent:o,delayDuration:s}=e,c=Ky(Jy,e.__scopeTooltip),l=Vy(t),[u,d]=I.useState(null),[f,p]=I.useState(void 0),m=_m(),h=I.useRef(0),g=o??c.disableHoverableContent,_=s??c.delayDuration,v=I.useRef(!1),[y,b]=$p({prop:r,defaultProp:i??!1,onChange:Y(e=>{e?(c.onOpen(),document.dispatchEvent(new CustomEvent(Wy))):c.onClose(),a?.(e)},`onChange`),caller:Jy}),x=I.useMemo(()=>y?v.current?`delayed-open`:`instant-open`:`closed`,[y]),S=I.useCallback(()=>{window.clearTimeout(h.current),h.current=0,v.current=!1,b(!0)},[b]),C=I.useCallback(()=>{window.clearTimeout(h.current),h.current=0,b(!1)},[b]),w=I.useCallback(()=>{window.clearTimeout(h.current),h.current=window.setTimeout(()=>{v.current=!0,b(!0),h.current=0},_)},[_,b]);I.useEffect(()=>()=>{h.current&&=(window.clearTimeout(h.current),0)},[]);let T=f??m;return(0,L.jsx)(Py,{...l,children:(0,L.jsx)(Yy,{scope:t,contentId:T,setContentId:p,open:y,stateAttribute:x,trigger:u,onTriggerChange:d,onTriggerEnter:I.useCallback(()=>{c.isOpenDelayedRef.current?w():S()},[c.isOpenDelayedRef,w,S]),onTriggerLeave:I.useCallback(()=>{g?C():(window.clearTimeout(h.current),h.current=0)},[C,g]),onOpen:S,onClose:C,disableHoverableContent:g,children:n})})},`Tooltip`),Qy=`TooltipTrigger`,$y=I.forwardRef(Y(function(e,t){let{__scopeTooltip:n,...r}=e,i=Xy(Qy,n),a=Ky(Qy,n),o=Vy(n),s=op(t,I.useRef(null),i.onTriggerChange),c=I.useRef(!1),l=I.useRef(!1),u=I.useCallback(()=>c.current=!1,[]);return I.useEffect(()=>()=>document.removeEventListener(`pointerup`,u),[u]),(0,L.jsx)(Fy,{asChild:!0,...o,children:(0,L.jsx)(J.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:s,onPointerMove:zp(e.onPointerMove,e=>{e.pointerType!==`touch`&&!l.current&&!a.isPointerInTransitRef.current&&(i.onTriggerEnter(),l.current=!0)}),onPointerLeave:zp(e.onPointerLeave,()=>{i.onTriggerLeave(),l.current=!1}),onPointerDown:zp(e.onPointerDown,()=>{i.open&&i.onClose(),c.current=!0,document.addEventListener(`pointerup`,u,{once:!0})}),onFocus:zp(e.onFocus,()=>{c.current||i.onOpen()}),onBlur:zp(e.onBlur,i.onClose),onClick:zp(e.onClick,i.onClose)})})},`TooltipTrigger`)),eb=`TooltipPortal`,[tb,nb]=zy(eb,{forceMount:void 0}),rb=Y(e=>{let{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,a=Xy(eb,t);return(0,L.jsx)(tb,{scope:t,forceMount:n,children:(0,L.jsx)(sm,{present:n||a.open,children:(0,L.jsx)($m,{asChild:!0,container:i,children:r})})})},`TooltipPortal`),ib=`TooltipContent`,ab=I.forwardRef(Y(function(e,t){let n=nb(ib,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i=`top`,...a}=e,o=Xy(ib,e.__scopeTooltip);return(0,L.jsx)(sm,{present:r||o.open,children:o.disableHoverableContent?(0,L.jsx)(cb,{side:i,...a,ref:t}):(0,L.jsx)(ob,{side:i,...a,ref:t})})},`TooltipContent`)),ob=I.forwardRef(Y(function(e,t){let n=Xy(ib,e.__scopeTooltip),r=Ky(ib,e.__scopeTooltip),i=I.useRef(null),a=op(t,i),[o,s]=I.useState(null),{trigger:c,onClose:l}=n,u=i.current,{onPointerInTransitChange:d}=r,f=I.useCallback(()=>{s(null),d(!1)},[d]),p=I.useCallback((e,t)=>{let n=e.currentTarget,r={x:e.clientX,y:e.clientY},i=db(r,ub(r,n.getBoundingClientRect())),a=fb(t.getBoundingClientRect()),o=mb([...i,...a]);s(o),d(!0)},[d]);return I.useEffect(()=>()=>f(),[f]),I.useEffect(()=>{if(c&&u){let e=Y(e=>p(e,u),`handleTriggerLeave`),t=Y(e=>p(e,c),`handleContentLeave`);return c.addEventListener(`pointerleave`,e),u.addEventListener(`pointerleave`,t),()=>{c.removeEventListener(`pointerleave`,e),u.removeEventListener(`pointerleave`,t)}}},[c,u,p,f]),I.useEffect(()=>{if(o){let e=Y(e=>{let t=e.target,n={x:e.clientX,y:e.clientY},r=c?.contains(t)||u?.contains(t),i=!pb(n,o);r?f():i&&(f(),l())},`handleTrackPointerGrace`);return document.addEventListener(`pointermove`,e),()=>document.removeEventListener(`pointermove`,e)}},[c,u,o,l,f]),(0,L.jsx)(cb,{...e,ref:a})},`TooltipContentHoverable`)),sb=pp(`TooltipContent`),cb=I.forwardRef(Y(function(e,t){let{__scopeTooltip:n,children:r,"aria-label":i,id:a,onEscapeKeyDown:o,onPointerDownOutside:s,...c}=e,l=Xy(ib,n),u=Vy(n),{onClose:d}=l;I.useEffect(()=>(document.addEventListener(Wy,d),()=>document.removeEventListener(Wy,d)),[d]),I.useEffect(()=>{if(l.trigger){let e=Y(e=>{e.target instanceof Node&&e.target.contains(l.trigger)&&d()},`handleScroll`);return window.addEventListener(`scroll`,e,{capture:!0}),()=>window.removeEventListener(`scroll`,e,{capture:!0})}},[l.trigger,d]);let{setContentId:f}=l;return Wp(()=>(f(a),()=>{f(void 0)}),[a,f]),(0,L.jsx)(Om,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:e=>e.preventDefault(),onDismiss:d,children:(0,L.jsxs)(Iy,{"data-state":l.stateAttribute,role:i?void 0:`tooltip`,id:i?void 0:l.contentId,...u,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-tooltip-content-available-width":`var(--radix-popper-available-width)`,"--radix-tooltip-content-available-height":`var(--radix-popper-available-height)`,"--radix-tooltip-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-tooltip-trigger-height":`var(--radix-popper-anchor-height)`},children:[(0,L.jsx)(sb,{children:r}),i?(0,L.jsx)(Ap,{id:l.contentId,role:`tooltip`,children:i}):null]})})},`TooltipContentImpl`)),lb=I.forwardRef(Y(function(e,t){let{__scopeTooltip:n,...r}=e,i=Vy(n);return(0,L.jsx)(Ly,{...i,...r,ref:t})},`TooltipArrow`));function ub(e,t){let n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return`left`;case i:return`right`;case n:return`top`;case r:return`bottom`;default:throw Error(`unreachable`)}}Y(ub,`getExitSideFromRect`);function db(e,t,n=5){let r=[];switch(t){case`top`:r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case`bottom`:r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case`left`:r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case`right`:r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n})}return r}Y(db,`getPaddedExitPoints`);function fb(e){let{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}Y(fb,`getPointsFromRect`);function pb(e,t){let{x:n,y:r}=e,i=!1;for(let e=0,a=t.length-1;e<t.length;a=e++){let o=t[e],s=t[a],c=o.x,l=o.y,u=s.x,d=s.y;l>r!=d>r&&n<(u-c)*(r-l)/(d-l)+c&&(i=!i)}return i}Y(pb,`isPointInPolygon`);function mb(e){let t=e.slice();return t.sort((e,t)=>e.x<t.x?-1:e.x>t.x?1:e.y<t.y?-1:+(e.y>t.y)),hb(t)}Y(mb,`getHull`);function hb(e){if(e.length<=1)return e.slice();let t=[];for(let n=0;n<e.length;n++){let r=e[n];for(;t.length>=2;){let e=t[t.length-1],n=t[t.length-2];if((e.x-n.x)*(r.y-n.y)>=(e.y-n.y)*(r.x-n.x))t.pop();else break}t.push(r)}t.pop();let n=[];for(let t=e.length-1;t>=0;t--){let r=e[t];for(;n.length>=2;){let e=n[n.length-1],t=n[n.length-2];if((e.x-t.x)*(r.y-t.y)>=(e.y-t.y)*(r.x-t.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}Y(hb,`getHullPresorted`);var gb=qy,_b=Zy,vb=$y,yb=rb,bb=ab,xb=lb,Sb=768;function Cb(){let[e,t]=I.useState(void 0);return I.useEffect(()=>{let e=window.matchMedia(`(max-width: 767px)`),n=()=>{t(window.innerWidth<Sb)};return e.addEventListener(`change`,n),t(window.innerWidth<Sb),()=>e.removeEventListener(`change`,n)},[]),!!e}var wb=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t<e.length;t++)n[t]=e[t];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n},Tb=(e,t)=>({classGroupId:e,validator:t}),Eb=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Db=`-`,Ob=[],kb=`arbitrary..`,Ab=e=>{let t=Nb(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return Mb(e);let n=e.split(Db);return jb(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?wb(i,t):t:i||Ob}return n[e]||Ob}}},jb=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=jb(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(Db):e.slice(t).join(Db),s=a.length;for(let e=0;e<s;e++){let t=a[e];if(t.validator(o))return t.classGroupId}},Mb=e=>e.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?kb+r:void 0})(),Nb=e=>{let{theme:t,classGroups:n}=e;return Pb(n,t)},Pb=(e,t)=>{let n=Eb();for(let r in e){let i=e[r];Fb(i,n,r,t)}return n},Fb=(e,t,n,r)=>{let i=e.length;for(let a=0;a<i;a++){let i=e[a];Ib(i,t,n,r)}},Ib=(e,t,n,r)=>{if(typeof e==`string`){Lb(e,t,n);return}if(typeof e==`function`){Rb(e,t,n,r);return}zb(e,t,n,r)},Lb=(e,t,n)=>{let r=e===``?t:Bb(t,e);r.classGroupId=n},Rb=(e,t,n,r)=>{if(Vb(e)){Fb(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(Tb(n,e))},zb=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e<a;e++){let[a,o]=i[e];Fb(o,Bb(t,a),n,r)}},Bb=(e,t)=>{let n=e,r=t.split(Db),i=r.length;for(let e=0;e<i;e++){let t=r[e],i=n.nextPart.get(t);i||(i=Eb(),n.nextPart.set(t,i)),n=i}return n},Vb=e=>`isThemeGetter`in e&&e.isThemeGetter===!0,Hb=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},Ub=`!`,Wb=`:`,Gb=[],Kb=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),qb=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;s<o;s++){let o=e[s];if(n===0&&r===0){if(o===Wb){t.push(e.slice(i,s)),i=s+1;continue}if(o===`/`){a=s;continue}}o===`[`?n++:o===`]`?n--:o===`(`?r++:o===`)`&&r--}let s=t.length===0?e:e.slice(i),c=s,l=!1;s.endsWith(Ub)?(c=s.slice(0,-1),l=!0):s.startsWith(Ub)&&(c=s.slice(1),l=!0);let u=a&&a>i?a-i:void 0;return Kb(t,l,c,u)};if(t){let e=t+Wb,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):Kb(Gb,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},Jb=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=a[0]===`[`,s=t.has(a);o||s?(r.length>0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},Yb=e=>({cache:Hb(e.cacheSize),parseClassName:qb(e),sortModifiers:Jb(e),postfixLookupClassGroupIds:Xb(e),...Ab(e)}),Xb=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e<n.length;e++)t[n[e]]=!0;return t},Zb=/\s+/,Qb=(e,t)=>{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(Zb),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+Ub:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e<b.length;++e){let t=b[e];s.push(v+t)}l=t+(l.length>0?` `+l:l)}return l},$b=(...e)=>{let t=0,n,r,i=``;for(;t<e.length;)(n=e[t++])&&(r=ex(n))&&(i&&(i+=` `),i+=r);return i},ex=e=>{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r<e.length;r++)e[r]&&(t=ex(e[r]))&&(n&&(n+=` `),n+=t);return n},tx=(e,...t)=>{let n,r,i,a,o=o=>(n=Yb(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=Qb(e,n);return i(e,a),a};return a=o,(...e)=>a($b(...e))},nx=[],rx=e=>{let t=t=>t[e]||nx;return t.isThemeGetter=!0,t},ix=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,ax=/^\((?:(\w[\w-]*):)?(.+)\)$/i,ox=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,sx=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,cx=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,lx=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ux=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,dx=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,fx=e=>ox.test(e),X=e=>!!e&&!Number.isNaN(Number(e)),px=e=>!!e&&Number.isInteger(Number(e)),mx=e=>e.endsWith(`%`)&&X(e.slice(0,-1)),hx=e=>sx.test(e),gx=()=>!0,_x=e=>cx.test(e)&&!lx.test(e),vx=()=>!1,yx=e=>ux.test(e),bx=e=>dx.test(e),xx=e=>!Z(e)&&!Q(e),Sx=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),Cx=e=>Rx(e,Hx,vx),Z=e=>ix.test(e),wx=e=>Rx(e,Ux,_x),Tx=e=>Rx(e,Wx,X),Ex=e=>Rx(e,Kx,gx),Dx=e=>Rx(e,Gx,vx),Ox=e=>Rx(e,Bx,vx),kx=e=>Rx(e,Vx,bx),Ax=e=>Rx(e,qx,yx),Q=e=>ax.test(e),jx=e=>zx(e,Ux),Mx=e=>zx(e,Gx),Nx=e=>zx(e,Bx),Px=e=>zx(e,Hx),Fx=e=>zx(e,Vx),Ix=e=>zx(e,qx,!0),Lx=e=>zx(e,Kx,!0),Rx=(e,t,n)=>{let r=ix.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},zx=(e,t,n=!1)=>{let r=ax.exec(e);return r?r[1]?t(r[1]):n:!1},Bx=e=>e===`position`||e===`percentage`,Vx=e=>e===`image`||e===`url`,Hx=e=>e===`length`||e===`size`||e===`bg-size`,Ux=e=>e===`length`,Wx=e=>e===`number`,Gx=e=>e===`family-name`,Kx=e=>e===`number`||e===`weight`,qx=e=>e===`shadow`,Jx=tx(()=>{let e=rx(`color`),t=rx(`font`),n=rx(`text`),r=rx(`font-weight`),i=rx(`tracking`),a=rx(`leading`),o=rx(`breakpoint`),s=rx(`container`),c=rx(`spacing`),l=rx(`radius`),u=rx(`shadow`),d=rx(`inset-shadow`),f=rx(`text-shadow`),p=rx(`drop-shadow`),m=rx(`blur`),h=rx(`perspective`),g=rx(`aspect`),_=rx(`ease`),v=rx(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),Q,Z],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[Q,Z,c],T=()=>[fx,`full`,`auto`,...w()],E=()=>[px,`none`,`subgrid`,Q,Z],D=()=>[`auto`,{span:[`full`,px,Q,Z]},px,Q,Z],O=()=>[px,`auto`,Q,Z],k=()=>[`auto`,`min`,`max`,`fr`,Q,Z],A=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],j=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],M=()=>[`auto`,...w()],N=()=>[fx,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],P=()=>[fx,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],ee=()=>[fx,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],F=()=>[e,Q,Z],te=()=>[...b(),Nx,Ox,{position:[Q,Z]}],ne=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,Px,Cx,{size:[Q,Z]}],I=()=>[mx,jx,wx],ie=()=>[``,`none`,`full`,l,Q,Z],ae=()=>[``,X,jx,wx],L=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],R=()=>[X,mx,Nx,Ox],se=()=>[``,`none`,m,Q,Z],ce=()=>[`none`,X,Q,Z],le=()=>[`none`,X,Q,Z],ue=()=>[X,Q,Z],de=()=>[fx,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[hx],breakpoint:[hx],color:[gx],container:[hx],"drop-shadow":[hx],ease:[`in`,`out`,`in-out`],font:[xx],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[hx],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[hx],shadow:[hx],spacing:[`px`,X],text:[hx],"text-shadow":[hx],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,fx,Z,Q,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,Q,Z]}],"container-named":[Sx],columns:[{columns:[X,Z,Q,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[px,`auto`,Q,Z]}],basis:[{basis:[fx,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[X,fx,`auto`,`initial`,`none`,Z]}],grow:[{grow:[``,X,Q,Z]}],shrink:[{shrink:[``,X,Q,Z]}],order:[{order:[px,`first`,`last`,`none`,Q,Z]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":k()}],"auto-rows":[{"auto-rows":k()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...A(),`normal`]}],"justify-items":[{"justify-items":[...j(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...j()]}],"align-content":[{content:[`normal`,...A()]}],"align-items":[{items:[...j(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...j(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":A()}],"place-items":[{"place-items":[...j(),`baseline`]}],"place-self":[{"place-self":[`auto`,...j()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:M()}],mx:[{mx:M()}],my:[{my:M()}],ms:[{ms:M()}],me:[{me:M()}],mbs:[{mbs:M()}],mbe:[{mbe:M()}],mt:[{mt:M()}],mr:[{mr:M()}],mb:[{mb:M()}],ml:[{ml:M()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:N()}],"inline-size":[{inline:[`auto`,...P()]}],"min-inline-size":[{"min-inline":[`auto`,...P()]}],"max-inline-size":[{"max-inline":[`none`,...P()]}],"block-size":[{block:[`auto`,...ee()]}],"min-block-size":[{"min-block":[`auto`,...ee()]}],"max-block-size":[{"max-block":[`none`,...ee()]}],w:[{w:[s,`screen`,...N()]}],"min-w":[{"min-w":[s,`screen`,`none`,...N()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...N()]}],h:[{h:[`screen`,`lh`,...N()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...N()]}],"max-h":[{"max-h":[`screen`,`lh`,...N()]}],"font-size":[{text:[`base`,n,jx,wx]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Lx,Ex]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,mx,Z]}],"font-family":[{font:[Mx,Dx,t]}],"font-features":[{"font-features":[Z]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,Q,Z]}],"line-clamp":[{"line-clamp":[X,`none`,Q,Tx]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,Q,Z]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,Q,Z]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...L(),`wavy`]}],"text-decoration-thickness":[{decoration:[X,`from-font`,`auto`,Q,wx]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[X,`auto`,Q,Z]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[px,Q,Z]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,Q,Z]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,Q,Z]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:te()}],"bg-repeat":[{bg:ne()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},px,Q,Z],radial:[``,Q,Z],conic:[px,Q,Z]},Fx,kx]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:I()}],"gradient-via-pos":[{via:I()}],"gradient-to-pos":[{to:I()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:ie()}],"rounded-s":[{"rounded-s":ie()}],"rounded-e":[{"rounded-e":ie()}],"rounded-t":[{"rounded-t":ie()}],"rounded-r":[{"rounded-r":ie()}],"rounded-b":[{"rounded-b":ie()}],"rounded-l":[{"rounded-l":ie()}],"rounded-ss":[{"rounded-ss":ie()}],"rounded-se":[{"rounded-se":ie()}],"rounded-ee":[{"rounded-ee":ie()}],"rounded-es":[{"rounded-es":ie()}],"rounded-tl":[{"rounded-tl":ie()}],"rounded-tr":[{"rounded-tr":ie()}],"rounded-br":[{"rounded-br":ie()}],"rounded-bl":[{"rounded-bl":ie()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-bs":[{"border-bs":ae()}],"border-w-be":[{"border-be":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...L(),`hidden`,`none`]}],"divide-style":[{divide:[...L(),`hidden`,`none`]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-bs":[{"border-bs":F()}],"border-color-be":[{"border-be":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...L(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[X,Q,Z]}],"outline-w":[{outline:[``,X,jx,wx]}],"outline-color":[{outline:F()}],shadow:[{shadow:[``,`none`,u,Ix,Ax]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":[`none`,d,Ix,Ax]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:ae()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[X,wx]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":[`none`,f,Ix,Ax]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[X,Q,Z]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[X]}],"mask-image-linear-from-pos":[{"mask-linear-from":R()}],"mask-image-linear-to-pos":[{"mask-linear-to":R()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":R()}],"mask-image-t-to-pos":[{"mask-t-to":R()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":R()}],"mask-image-r-to-pos":[{"mask-r-to":R()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":R()}],"mask-image-b-to-pos":[{"mask-b-to":R()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":R()}],"mask-image-l-to-pos":[{"mask-l-to":R()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":R()}],"mask-image-x-to-pos":[{"mask-x-to":R()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":R()}],"mask-image-y-to-pos":[{"mask-y-to":R()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[Q,Z]}],"mask-image-radial-from-pos":[{"mask-radial-from":R()}],"mask-image-radial-to-pos":[{"mask-radial-to":R()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[X]}],"mask-image-conic-from-pos":[{"mask-conic-from":R()}],"mask-image-conic-to-pos":[{"mask-conic-to":R()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:te()}],"mask-repeat":[{mask:ne()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,Q,Z]}],filter:[{filter:[``,`none`,Q,Z]}],blur:[{blur:se()}],brightness:[{brightness:[X,Q,Z]}],contrast:[{contrast:[X,Q,Z]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Ix,Ax]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:[``,X,Q,Z]}],"hue-rotate":[{"hue-rotate":[X,Q,Z]}],invert:[{invert:[``,X,Q,Z]}],saturate:[{saturate:[X,Q,Z]}],sepia:[{sepia:[``,X,Q,Z]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,Q,Z]}],"backdrop-blur":[{"backdrop-blur":se()}],"backdrop-brightness":[{"backdrop-brightness":[X,Q,Z]}],"backdrop-contrast":[{"backdrop-contrast":[X,Q,Z]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,X,Q,Z]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[X,Q,Z]}],"backdrop-invert":[{"backdrop-invert":[``,X,Q,Z]}],"backdrop-opacity":[{"backdrop-opacity":[X,Q,Z]}],"backdrop-saturate":[{"backdrop-saturate":[X,Q,Z]}],"backdrop-sepia":[{"backdrop-sepia":[``,X,Q,Z]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,Q,Z]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[X,`initial`,Q,Z]}],ease:[{ease:[`linear`,`initial`,_,Q,Z]}],delay:[{delay:[X,Q,Z]}],animate:[{animate:[`none`,v,Q,Z]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,Q,Z]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:ce()}],"rotate-x":[{"rotate-x":ce()}],"rotate-y":[{"rotate-y":ce()}],"rotate-z":[{"rotate-z":ce()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":[`scale-3d`],skew:[{skew:ue()}],"skew-x":[{"skew-x":ue()}],"skew-y":[{"skew-y":ue()}],transform:[{transform:[Q,Z,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:de()}],"translate-x":[{"translate-x":de()}],"translate-y":[{"translate-y":de()}],"translate-z":[{"translate-z":de()}],"translate-none":[`translate-none`],zoom:[{zoom:[px,Q,Z]}],accent:[{accent:F()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,Q,Z]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":F()}],"scrollbar-track-color":[{"scrollbar-track":F()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,Q,Z]}],fill:[{fill:[`none`,...F()]}],"stroke-w":[{stroke:[X,jx,wx,Tx]}],stroke:[{stroke:[`none`,...F()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function $(...e){return Jx(Vf(e))}var Yx=Wf(`inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/90`,destructive:`bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40`,outline:`border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,ghost:`hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-9 px-4 py-2 has-[>svg]:px-3`,xs:`h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3`,sm:`h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5`,lg:`h-10 rounded-md px-6 has-[>svg]:px-4`,icon:`size-9`,"icon-xs":`size-6 rounded-md [&_svg:not([class*='size-'])]:size-3`,"icon-sm":`size-8`,"icon-lg":`size-10`}},defaultVariants:{variant:`default`,size:`default`}});function Xx({className:e,variant:t=`default`,size:n=`default`,asChild:r=!1,...i}){let a=r?dp:`button`;return(0,L.jsx)(a,{"data-slot":`button`,"data-variant":t,"data-size":n,className:$(Yx({variant:t,size:n,className:e})),...i})}function Zx({...e}){return(0,L.jsx)(jg,{"data-slot":`sheet`,...e})}function Qx({...e}){return(0,L.jsx)(Fg,{"data-slot":`sheet-portal`,...e})}function $x({className:e,...t}){return(0,L.jsx)(Lg,{"data-slot":`sheet-overlay`,className:$(`fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0`,e),...t})}function eS({className:e,children:t,side:n=`right`,showCloseButton:r=!0,...i}){return(0,L.jsxs)(Qx,{children:[(0,L.jsx)($x,{}),(0,L.jsxs)(Vg,{"data-slot":`sheet-content`,className:$(`fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500`,n===`right`&&`inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm`,n===`left`&&`inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm`,n===`top`&&`inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top`,n===`bottom`&&`inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom`,e),...i,children:[t,r&&(0,L.jsxs)(Xg,{className:`absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary`,children:[(0,L.jsx)(tp,{className:`size-4`}),(0,L.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function tS({className:e,...t}){return(0,L.jsx)(`div`,{"data-slot":`sheet-header`,className:$(`flex flex-col gap-1.5 p-4`,e),...t})}function nS({className:e,...t}){return(0,L.jsx)(Kg,{"data-slot":`sheet-title`,className:$(`font-semibold text-foreground`,e),...t})}function rS({className:e,...t}){return(0,L.jsx)(Jg,{"data-slot":`sheet-description`,className:$(`text-sm text-muted-foreground`,e),...t})}function iS({delayDuration:e=0,...t}){return(0,L.jsx)(gb,{"data-slot":`tooltip-provider`,delayDuration:e,...t})}function aS({...e}){return(0,L.jsx)(_b,{"data-slot":`tooltip`,...e})}function oS({...e}){return(0,L.jsx)(vb,{"data-slot":`tooltip-trigger`,...e})}function sS({className:e,sideOffset:t=0,children:n,...r}){return(0,L.jsx)(yb,{children:(0,L.jsxs)(bb,{"data-slot":`tooltip-content`,sideOffset:t,className:$(`z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95`,e),...r,children:[n,(0,L.jsx)(xb,{className:`z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground`})]})})}var cS=`sidebar_state`,lS=604800,uS=`16rem`,dS=`18rem`,fS=`3rem`,pS=`b`,mS=I.createContext(null);function hS(){let e=I.useContext(mS);if(!e)throw Error(`useSidebar must be used within a SidebarProvider.`);return e}function gS({defaultOpen:e=!0,open:t,onOpenChange:n,className:r,style:i,children:a,...o}){let s=Cb(),[c,l]=I.useState(!1),[u,d]=I.useState(e),f=t??u,p=I.useCallback(e=>{let t=typeof e==`function`?e(f):e;n?n(t):d(t),document.cookie=`${cS}=${t}; path=/; max-age=${lS}`},[n,f]),m=I.useCallback(()=>s?l(e=>!e):p(e=>!e),[s,p,l]);I.useEffect(()=>{let e=e=>{e.key===pS&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),m())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[m]);let h=f?`expanded`:`collapsed`,g=I.useMemo(()=>({state:h,open:f,setOpen:p,isMobile:s,openMobile:c,setOpenMobile:l,toggleSidebar:m}),[h,f,p,s,c,l,m]);return(0,L.jsx)(mS.Provider,{value:g,children:(0,L.jsx)(iS,{delayDuration:0,children:(0,L.jsx)(`div`,{"data-slot":`sidebar-wrapper`,style:{"--sidebar-width":uS,"--sidebar-width-icon":fS,...i},className:$(`group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar`,r),...o,children:a})})})}function _S({side:e=`left`,variant:t=`sidebar`,collapsible:n=`offcanvas`,className:r,children:i,...a}){let{isMobile:o,state:s,openMobile:c,setOpenMobile:l}=hS();return n===`none`?(0,L.jsx)(`div`,{"data-slot":`sidebar`,className:$(`flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground`,r),...a,children:i}):o?(0,L.jsx)(Zx,{open:c,onOpenChange:l,...a,children:(0,L.jsxs)(eS,{"data-sidebar":`sidebar`,"data-slot":`sidebar`,"data-mobile":`true`,className:`w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden`,style:{"--sidebar-width":dS},side:e,children:[(0,L.jsxs)(tS,{className:`sr-only`,children:[(0,L.jsx)(nS,{children:`Sidebar`}),(0,L.jsx)(rS,{children:`Displays the mobile sidebar.`})]}),(0,L.jsx)(`div`,{className:`flex h-full w-full flex-col`,children:i})]})}):(0,L.jsxs)(`div`,{className:`group peer hidden text-sidebar-foreground md:block`,"data-state":s,"data-collapsible":s===`collapsed`?n:``,"data-variant":t,"data-side":e,"data-slot":`sidebar`,children:[(0,L.jsx)(`div`,{"data-slot":`sidebar-gap`,className:$(`relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear`,`group-data-[collapsible=offcanvas]:w-0`,`group-data-[side=right]:rotate-180`,t===`floating`||t===`inset`?`group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]`:`group-data-[collapsible=icon]:w-(--sidebar-width-icon)`)}),(0,L.jsx)(`div`,{"data-slot":`sidebar-container`,className:$(`fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex`,e===`left`?`left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]`:`right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]`,t===`floating`||t===`inset`?`p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]`:`group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l`,r),...a,children:(0,L.jsx)(`div`,{"data-sidebar":`sidebar`,"data-slot":`sidebar-inner`,className:`flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm`,children:i})})]})}function vS({className:e,onClick:t,...n}){let{toggleSidebar:r}=hS();return(0,L.jsxs)(Xx,{"data-sidebar":`trigger`,"data-slot":`sidebar-trigger`,variant:`ghost`,size:`icon`,className:$(`size-7`,e),onClick:e=>{t?.(e),r()},...n,children:[(0,L.jsx)($f,{}),(0,L.jsx)(`span`,{className:`sr-only`,children:`Toggle Sidebar`})]})}function yS({className:e,...t}){return(0,L.jsx)(`main`,{"data-slot":`sidebar-inset`,className:$(`relative flex w-full flex-1 flex-col bg-background`,`md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2`,e),...t})}function bS({className:e,...t}){return(0,L.jsx)(`div`,{"data-slot":`sidebar-content`,"data-sidebar":`content`,className:$(`flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden`,e),...t})}function xS({className:e,...t}){return(0,L.jsx)(`div`,{"data-slot":`sidebar-group`,"data-sidebar":`group`,className:$(`relative flex w-full min-w-0 flex-col p-2`,e),...t})}function SS({className:e,asChild:t=!1,...n}){let r=t?dp:`div`;return(0,L.jsx)(r,{"data-slot":`sidebar-group-label`,"data-sidebar":`group-label`,className:$(`flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0`,`group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0`,e),...n})}function CS({className:e,...t}){return(0,L.jsx)(`div`,{"data-slot":`sidebar-group-content`,"data-sidebar":`group-content`,className:$(`w-full text-sm`,e),...t})}function wS({className:e,...t}){return(0,L.jsx)(`ul`,{"data-slot":`sidebar-menu`,"data-sidebar":`menu`,className:$(`flex w-full min-w-0 flex-col gap-1`,e),...t})}function TS({className:e,...t}){return(0,L.jsx)(`li`,{"data-slot":`sidebar-menu-item`,"data-sidebar":`menu-item`,className:$(`group/menu-item relative`,e),...t})}var ES=Wf(`peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0`,{variants:{variant:{default:`hover:bg-sidebar-accent hover:text-sidebar-accent-foreground`,outline:`bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]`},size:{default:`h-8 text-sm`,sm:`h-7 text-xs`,lg:`h-12 text-sm group-data-[collapsible=icon]:p-0!`}},defaultVariants:{variant:`default`,size:`default`}});function DS({asChild:e=!1,isActive:t=!1,variant:n=`default`,size:r=`default`,tooltip:i,className:a,...o}){let s=e?dp:`button`,{isMobile:c,state:l}=hS(),u=(0,L.jsx)(s,{"data-slot":`sidebar-menu-button`,"data-sidebar":`menu-button`,"data-size":r,"data-active":t,className:$(ES({variant:n,size:r}),a),...o});return i?(typeof i==`string`&&(i={children:i}),(0,L.jsxs)(aS,{children:[(0,L.jsx)(oS,{asChild:!0,children:u}),(0,L.jsx)(sS,{side:`right`,align:`center`,hidden:l!==`collapsed`||c,...i})]})):u}function OS({className:e,...t}){return(0,L.jsx)(`div`,{"data-slot":`sidebar-menu-badge`,"data-sidebar":`menu-badge`,className:$(`pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none`,`peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground`,`peer-data-[size=sm]/menu-button:top-1`,`peer-data-[size=default]/menu-button:top-1.5`,`peer-data-[size=lg]/menu-button:top-2.5`,`group-data-[collapsible=icon]:hidden`,e),...t})}function kS({notifications:e,activeView:t}){return(0,L.jsx)(_S,{collapsible:`icon`,children:(0,L.jsx)(bS,{children:(0,L.jsxs)(xS,{children:[(0,L.jsx)(SS,{children:`gitxp`}),(0,L.jsx)(CS,{children:(0,L.jsx)(wS,{children:T.map(n=>{let r=e.filter(n.match).length;return(0,L.jsxs)(TS,{children:[(0,L.jsx)(DS,{asChild:!0,isActive:n.id===t,tooltip:n.label,children:(0,L.jsx)(o,{to:`/`,search:{view:n.id},children:(0,L.jsx)(`span`,{children:n.label})})}),r>0?(0,L.jsx)(OS,{children:r}):null]},n.id)})})})]})})})}var AS=1,jS=.9,MS=.8,NS=.17,PS=.1,FS=.999,IS=.9999,LS=.99,RS=/[\\\/_+.#"@\[\(\{&]/,zS=/[\\\/_+.#"@\[\(\{&]/g,BS=/[\s-]/,VS=/[\s-]/g;function HS(e,t,n,r,i,a,o){if(a===t.length)return i===e.length?AS:LS;var s=`${i},${a}`;if(o[s]!==void 0)return o[s];for(var c=r.charAt(a),l=n.indexOf(c,i),u=0,d,f,p,m;l>=0;)d=HS(e,t,n,r,l+1,a+1,o),d>u&&(l===i?d*=AS:RS.test(e.charAt(l-1))?(d*=MS,p=e.slice(i,l-1).match(zS),p&&i>0&&(d*=FS**+p.length)):BS.test(e.charAt(l-1))?(d*=jS,m=e.slice(i,l-1).match(VS),m&&i>0&&(d*=FS**+m.length)):(d*=NS,i>0&&(d*=FS**+(l-i))),e.charAt(l)!==t.charAt(a)&&(d*=IS)),(d<PS&&n.charAt(l-1)===r.charAt(a+1)||r.charAt(a+1)===r.charAt(a)&&n.charAt(l-1)!==r.charAt(a))&&(f=HS(e,t,n,r,l+1,a+2,o),f*PS>d&&(d=f*PS)),d>u&&(u=d),l=n.indexOf(c,l+1);return o[s]=u,u}function US(e){return e.toLowerCase().replace(VS,` `)}function WS(e,t,n){return e=n&&n.length>0?`${e+` `+n.join(` `)}`:e,HS(e,t,US(e),US(t),0,0,{})}var GS=`[cmdk-group=""]`,KS=`[cmdk-group-items=""]`,qS=`[cmdk-group-heading=""]`,JS=`[cmdk-item=""]`,YS=`${JS}:not([aria-disabled="true"])`,XS=`cmdk-item-select`,ZS=`data-value`,QS=(e,t,n)=>WS(e,t,n),$S=I.createContext(void 0),eC=()=>I.useContext($S),tC=I.createContext(void 0),nC=()=>I.useContext(tC),rC=I.createContext(void 0),iC=I.forwardRef((e,t)=>{let n=vC(()=>({search:``,value:e.value??e.defaultValue??``,selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}})),r=vC(()=>new Set),i=vC(()=>new Map),a=vC(()=>new Map),o=vC(()=>new Set),s=gC(e),{label:c,children:l,value:u,onValueChange:d,filter:f,shouldFilter:p,loop:m,disablePointerSelection:h=!1,vimBindings:g=!0,..._}=e,v=_m(),y=_m(),b=_m(),x=I.useRef(null),S=xC();_C(()=>{if(u!==void 0){let e=u.trim();n.current.value=e,C.emit()}},[u]),_C(()=>{S(6,k)},[]);let C=I.useMemo(()=>({subscribe:e=>(o.current.add(e),()=>o.current.delete(e)),snapshot:()=>n.current,setState:(e,t,r)=>{var i,a,o;if(!Object.is(n.current[e],t)){if(n.current[e]=t,e===`search`)O(),E(),S(1,D);else if(e===`value`){if(document.activeElement.hasAttribute(`cmdk-input`)||document.activeElement.hasAttribute(`cmdk-root`)){let e=document.getElementById(b);e?e.focus():(i=document.getElementById(v))==null||i.focus()}if(S(7,()=>{n.current.selectedItemId=A()?.id,C.emit()}),r||S(5,k),s.current?.value!==void 0){let e=t??``;(o=(a=s.current).onValueChange)==null||o.call(a,e);return}}C.emit()}},emit:()=>{o.current.forEach(e=>e())}}),[]),w=I.useMemo(()=>({value:(e,t,r)=>{t!==a.current.get(e)?.value&&(a.current.set(e,{value:t,keywords:r}),n.current.filtered.items.set(e,T(t,r)),S(2,()=>{E(),C.emit()}))},item:(e,t)=>(r.current.add(e),t&&(i.current.has(t)?i.current.get(t).add(e):i.current.set(t,new Set([e]))),S(3,()=>{O(),E(),n.current.value||D(),C.emit()}),()=>{a.current.delete(e),r.current.delete(e),n.current.filtered.items.delete(e);let t=A();S(4,()=>{O(),t?.getAttribute(`id`)===e&&D(),C.emit()})}),group:e=>(i.current.has(e)||i.current.set(e,new Set),()=>{a.current.delete(e),i.current.delete(e)}),filter:()=>s.current.shouldFilter,label:c||e[`aria-label`],getDisablePointerSelection:()=>s.current.disablePointerSelection,listId:v,inputId:b,labelId:y,listInnerRef:x}),[]);function T(e,t){let r=s.current?.filter??QS;return e?r(e,n.current.search,t):0}function E(){if(!n.current.search||s.current.shouldFilter===!1)return;let e=n.current.filtered.items,t=[];n.current.filtered.groups.forEach(n=>{let r=i.current.get(n),a=0;r.forEach(t=>{let n=e.get(t);a=Math.max(n,a)}),t.push([n,a])});let r=x.current;j().sort((t,n)=>{let r=t.getAttribute(`id`),i=n.getAttribute(`id`);return(e.get(i)??0)-(e.get(r)??0)}).forEach(e=>{let t=e.closest(KS);t?t.appendChild(e.parentElement===t?e:e.closest(`${KS} > *`)):r.appendChild(e.parentElement===r?e:e.closest(`${KS} > *`))}),t.sort((e,t)=>t[1]-e[1]).forEach(e=>{let t=x.current?.querySelector(`${GS}[${ZS}="${encodeURIComponent(e[0])}"]`);t?.parentElement.appendChild(t)})}function D(){let e=j().find(e=>e.getAttribute(`aria-disabled`)!==`true`)?.getAttribute(ZS);C.setState(`value`,e||void 0)}function O(){if(!n.current.search||s.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let e=0;for(let t of r.current){let r=T(a.current.get(t)?.value??``,a.current.get(t)?.keywords??[]);n.current.filtered.items.set(t,r),r>0&&e++}for(let[e,t]of i.current)for(let r of t)if(n.current.filtered.items.get(r)>0){n.current.filtered.groups.add(e);break}n.current.filtered.count=e}function k(){var e;let t=A();t&&(t.parentElement?.firstChild===t&&((e=t.closest(GS)?.querySelector(qS))==null||e.scrollIntoView({block:`nearest`})),t.scrollIntoView({block:`nearest`}))}function A(){return x.current?.querySelector(`${JS}[aria-selected="true"]`)}function j(){return Array.from(x.current?.querySelectorAll(YS)||[])}function M(e){let t=j()[e];t&&C.setState(`value`,t.getAttribute(ZS))}function N(e){var t;let n=A(),r=j(),i=r.findIndex(e=>e===n),a=r[i+e];(t=s.current)!=null&&t.loop&&(a=i+e<0?r[r.length-1]:i+e===r.length?r[0]:r[i+e]),a&&C.setState(`value`,a.getAttribute(ZS))}function P(e){let t=A()?.closest(GS),n;for(;t&&!n;)t=e>0?mC(t,GS):hC(t,GS),n=t?.querySelector(YS);n?C.setState(`value`,n.getAttribute(ZS)):N(e)}let ee=()=>M(j().length-1),F=e=>{e.preventDefault(),e.metaKey?ee():e.altKey?P(1):N(1)},te=e=>{e.preventDefault(),e.metaKey?M(0):e.altKey?P(-1):N(-1)};return I.createElement(J.div,{ref:t,tabIndex:-1,..._,"cmdk-root":``,onKeyDown:e=>{var t;(t=_.onKeyDown)==null||t.call(_,e);let n=e.nativeEvent.isComposing||e.keyCode===229;if(!(e.defaultPrevented||n))switch(e.key){case`n`:case`j`:g&&e.ctrlKey&&F(e);break;case`ArrowDown`:F(e);break;case`p`:case`k`:g&&e.ctrlKey&&te(e);break;case`ArrowUp`:te(e);break;case`Home`:e.preventDefault(),M(0);break;case`End`:e.preventDefault(),ee();break;case`Enter`:{e.preventDefault();let t=A();if(t){let e=new Event(XS);t.dispatchEvent(e)}}}}},I.createElement(`label`,{"cmdk-label":``,htmlFor:w.inputId,id:w.labelId,style:wC},c),CC(e,e=>I.createElement(tC.Provider,{value:C},I.createElement($S.Provider,{value:w},e))))}),aC=I.forwardRef((e,t)=>{let n=_m(),r=I.useRef(null),i=I.useContext(rC),a=eC(),o=gC(e),s=o.current?.forceMount??i?.forceMount;_C(()=>{if(!s)return a.item(n,i?.id)},[s]);let c=bC(n,r,[e.value,e.children,r],e.keywords),l=nC(),u=yC(e=>e.value&&e.value===c.current),d=yC(e=>s||a.filter()===!1?!0:!e.search||e.filtered.items.get(n)>0);I.useEffect(()=>{let t=r.current;if(!(!t||e.disabled))return t.addEventListener(XS,f),()=>t.removeEventListener(XS,f)},[d,e.onSelect,e.disabled]);function f(){var e,t;p(),(t=(e=o.current).onSelect)==null||t.call(e,c.current)}function p(){l.setState(`value`,c.current,!0)}if(!d)return null;let{disabled:m,value:h,onSelect:g,forceMount:_,keywords:v,...y}=e;return I.createElement(J.div,{ref:ap(r,t),...y,id:n,"cmdk-item":``,role:`option`,"aria-disabled":!!m,"aria-selected":!!u,"data-disabled":!!m,"data-selected":!!u,onPointerMove:m||a.getDisablePointerSelection()?void 0:p,onClick:m?void 0:f},e.children)}),oC=I.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...a}=e,o=_m(),s=I.useRef(null),c=I.useRef(null),l=_m(),u=eC(),d=yC(e=>i||u.filter()===!1?!0:!e.search||e.filtered.groups.has(o));_C(()=>u.group(o),[]),bC(o,s,[e.value,e.heading,c]);let f=I.useMemo(()=>({id:o,forceMount:i}),[i]);return I.createElement(J.div,{ref:ap(s,t),...a,"cmdk-group":``,role:`presentation`,hidden:!d||void 0},n&&I.createElement(`div`,{ref:c,"cmdk-group-heading":``,"aria-hidden":!0,id:l},n),CC(e,e=>I.createElement(`div`,{"cmdk-group-items":``,role:`group`,"aria-labelledby":n?l:void 0},I.createElement(rC.Provider,{value:f},e))))}),sC=I.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=I.useRef(null),a=yC(e=>!e.search);return!n&&!a?null:I.createElement(J.div,{ref:ap(i,t),...r,"cmdk-separator":``,role:`separator`})}),cC=I.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,a=nC(),o=yC(e=>e.search),s=yC(e=>e.selectedItemId),c=eC();return I.useEffect(()=>{e.value!=null&&a.setState(`search`,e.value)},[e.value]),I.createElement(J.input,{ref:t,...r,"cmdk-input":``,autoComplete:`off`,autoCorrect:`off`,spellCheck:!1,"aria-autocomplete":`list`,role:`combobox`,"aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":s,id:c.inputId,type:`text`,value:i?e.value:o,onChange:e=>{i||a.setState(`search`,e.target.value),n?.(e.target.value)}})}),lC=I.forwardRef((e,t)=>{let{children:n,label:r=`Suggestions`,...i}=e,a=I.useRef(null),o=I.useRef(null),s=yC(e=>e.selectedItemId),c=eC();return I.useEffect(()=>{if(o.current&&a.current){let e=o.current,t=a.current,n,r=new ResizeObserver(()=>{n=requestAnimationFrame(()=>{let n=e.offsetHeight;t.style.setProperty(`--cmdk-list-height`,n.toFixed(1)+`px`)})});return r.observe(e),()=>{cancelAnimationFrame(n),r.unobserve(e)}}},[]),I.createElement(J.div,{ref:ap(a,t),...i,"cmdk-list":``,role:`listbox`,tabIndex:-1,"aria-activedescendant":s,"aria-label":r,id:c.listId},CC(e,e=>I.createElement(`div`,{ref:ap(o,c.listInnerRef),"cmdk-list-sizer":``},e)))}),uC=I.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:a,container:o,...s}=e;return I.createElement(jg,{open:n,onOpenChange:r},I.createElement(Fg,{container:o},I.createElement(Lg,{"cmdk-overlay":``,className:i}),I.createElement(Vg,{"aria-label":e.label,"cmdk-dialog":``,className:a},I.createElement(iC,{ref:t,...s}))))}),dC=I.forwardRef((e,t)=>yC(e=>e.filtered.count===0)?I.createElement(J.div,{ref:t,...e,"cmdk-empty":``,role:`presentation`}):null),fC=I.forwardRef((e,t)=>{let{progress:n,children:r,label:i=`Loading...`,...a}=e;return I.createElement(J.div,{ref:t,...a,"cmdk-loading":``,role:`progressbar`,"aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},CC(e,e=>I.createElement(`div`,{"aria-hidden":!0},e)))}),pC=Object.assign(iC,{List:lC,Item:aC,Input:cC,Group:oC,Separator:sC,Dialog:uC,Empty:dC,Loading:fC});function mC(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function hC(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function gC(e){let t=I.useRef(e);return _C(()=>{t.current=e}),t}var _C=typeof window>`u`?I.useEffect:I.useLayoutEffect;function vC(e){let t=I.useRef();return t.current===void 0&&(t.current=e()),t}function yC(e){let t=nC(),n=()=>e(t.snapshot());return I.useSyncExternalStore(t.subscribe,n,n)}function bC(e,t,n,r=[]){let i=I.useRef(),a=eC();return _C(()=>{var o;let s=(()=>{for(let e of n){if(typeof e==`string`)return e.trim();if(typeof e==`object`&&`current`in e)return e.current?e.current.textContent?.trim():i.current}})(),c=r.map(e=>e.trim());a.value(e,s,c),(o=t.current)==null||o.setAttribute(ZS,s),i.current=s}),i}var xC=()=>{let[e,t]=I.useState(),n=vC(()=>new Map);return _C(()=>{n.current.forEach(e=>e()),n.current=new Map},[e]),(e,r)=>{n.current.set(e,r),t({})}};function SC(e){let t=e.type;return typeof t==`function`?t(e.props):`render`in t?t.render(e.props):e}function CC({asChild:e,children:t},n){return e&&I.isValidElement(t)?I.cloneElement(SC(t),{ref:t.ref},n(t.props.children)):n(t)}var wC={position:`absolute`,width:`1px`,height:`1px`,padding:`0`,margin:`-1px`,overflow:`hidden`,clip:`rect(0, 0, 0, 0)`,whiteSpace:`nowrap`,borderWidth:`0`};function TC({...e}){return(0,L.jsx)(jg,{"data-slot":`dialog`,...e})}function EC({...e}){return(0,L.jsx)(Fg,{"data-slot":`dialog-portal`,...e})}function DC({className:e,...t}){return(0,L.jsx)(Lg,{"data-slot":`dialog-overlay`,className:$(`fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0`,e),...t})}function OC({className:e,children:t,showCloseButton:n=!0,...r}){return(0,L.jsxs)(EC,{"data-slot":`dialog-portal`,children:[(0,L.jsx)(DC,{}),(0,L.jsxs)(Vg,{"data-slot":`dialog-content`,className:$(`fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg`,e),...r,children:[t,n&&(0,L.jsxs)(Xg,{"data-slot":`dialog-close`,className:`absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,children:[(0,L.jsx)(tp,{}),(0,L.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function kC({className:e,...t}){return(0,L.jsx)(`div`,{"data-slot":`dialog-header`,className:$(`flex flex-col gap-2 text-center sm:text-left`,e),...t})}function AC({className:e,...t}){return(0,L.jsx)(Kg,{"data-slot":`dialog-title`,className:$(`text-lg leading-none font-semibold`,e),...t})}function jC({className:e,...t}){return(0,L.jsx)(Jg,{"data-slot":`dialog-description`,className:$(`text-sm text-muted-foreground`,e),...t})}function MC({className:e,...t}){return(0,L.jsx)(pC,{"data-slot":`command`,className:$(`flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground`,e),...t})}function NC({title:e=`Command Palette`,description:t=`Search for a command to run...`,children:n,className:r,showCloseButton:i=!0,...a}){return(0,L.jsxs)(TC,{...a,children:[(0,L.jsxs)(kC,{className:`sr-only`,children:[(0,L.jsx)(AC,{children:e}),(0,L.jsx)(jC,{children:t})]}),(0,L.jsx)(OC,{className:$(`overflow-hidden p-0`,r),showCloseButton:i,children:(0,L.jsx)(MC,{className:`**:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5`,children:n})})]})}function PC({className:e,...t}){return(0,L.jsxs)(`div`,{"data-slot":`command-input-wrapper`,className:`flex h-9 items-center gap-2 border-b px-3`,children:[(0,L.jsx)(ep,{className:`size-4 shrink-0 opacity-50`}),(0,L.jsx)(pC.Input,{"data-slot":`command-input`,className:$(`flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50`,e),...t})]})}function FC({className:e,...t}){return(0,L.jsx)(pC.List,{"data-slot":`command-list`,className:$(`max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto`,e),...t})}function IC({...e}){return(0,L.jsx)(pC.Empty,{"data-slot":`command-empty`,className:`py-6 text-center text-sm`,...e})}function LC({className:e,...t}){return(0,L.jsx)(pC.Group,{"data-slot":`command-group`,className:$(`overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground`,e),...t})}function RC({className:e,...t}){return(0,L.jsx)(pC.Item,{"data-slot":`command-item`,className:$(`relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground`,e),...t})}function zC({className:e,...t}){return(0,L.jsx)(`span`,{"data-slot":`command-shortcut`,className:$(`ml-auto text-xs tracking-widest text-muted-foreground`,e),...t})}function BC({onSelectView:e,onOpenSelected:t,onRefresh:n,onDoneSelected:r,onReadSelected:i,canOpenSelected:a}){let[o,s]=(0,I.useState)(!1);(0,I.useEffect)(()=>{let e=e=>{e.key===`k`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),s(e=>!e))};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[]);let c=e=>{s(!1),e()};return(0,L.jsxs)(NC,{open:o,onOpenChange:s,title:`Commands`,description:`Jump to a view or act on the selection`,children:[(0,L.jsx)(PC,{placeholder:`Type a command...`}),(0,L.jsxs)(FC,{children:[(0,L.jsx)(IC,{children:`No matching command`}),(0,L.jsx)(LC,{heading:`Views`,children:T.map(t=>(0,L.jsx)(RC,{value:`view ${t.label}`,onSelect:()=>c(()=>e(t.id)),children:t.label},t.id))}),(0,L.jsxs)(LC,{heading:`Actions`,children:[(0,L.jsx)(RC,{value:`sync refresh`,onSelect:()=>c(n),children:`Sync now`}),a?(0,L.jsxs)(RC,{value:`open github`,onSelect:()=>c(t),children:[`Open on GitHub`,(0,L.jsx)(zC,{children:`Enter`})]}):null,r===void 0?null:(0,L.jsxs)(RC,{value:`done archive`,onSelect:()=>c(r),children:[`Mark as done`,(0,L.jsx)(zC,{children:`e`})]}),i===void 0?null:(0,L.jsxs)(RC,{value:`read`,onSelect:()=>c(i),children:[`Mark as read`,(0,L.jsx)(zC,{children:`r`})]})]})]})]})}function VC(){let e=n(),t=he({queryKey:[`failed-mutations`],queryFn:()=>u(),refetchInterval:1e4}),r=ge({mutationFn:()=>O(),onSettled:()=>e.invalidateQueries({queryKey:[`failed-mutations`]})}),i=t.data??[];return i.length===0?null:(0,L.jsxs)(`div`,{className:`flex items-center gap-2 border-b bg-destructive/10 px-3 py-2 text-xs`,children:[(0,L.jsxs)(`span`,{className:`text-destructive`,children:[i.length,` action`,i.length===1?``:`s`,` failed`]}),(0,L.jsx)(`span`,{className:`truncate text-muted-foreground`,children:i[0].lastError}),(0,L.jsx)(Xx,{size:`sm`,variant:`outline`,className:`ml-auto h-6 shrink-0 text-xs`,disabled:r.isPending,onClick:()=>r.mutate(),children:r.isPending?`Retrying`:`Retry`})]})}function HC({notifications:e,selectedId:t,onSelect:n,onOpen:r,onDone:i,onRead:a,emptyMessage:o}){let s=(0,I.useRef)(null),c=e.findIndex(e=>e.thread_id===t);(0,I.useEffect)(()=>{s.current?.querySelector(`[data-selected="true"]`)?.scrollIntoView({block:`nearest`})},[t]);let l=t=>{e.length!==0&&n(e[Math.min(Math.max(c===-1?0:c+t,0),e.length-1)].thread_id)};return e.length===0?(0,L.jsx)(`div`,{className:`flex h-full items-center justify-center p-8 text-sm text-muted-foreground`,children:o}):(0,L.jsx)(`ul`,{ref:s,tabIndex:0,onKeyDown:o=>{if(o.key===`ArrowDown`||o.key===`j`){o.preventDefault(),l(1);return}if(o.key===`ArrowUp`||o.key===`k`){o.preventDefault(),l(-1);return}if(o.key===`Enter`){o.preventDefault(),r();return}if(t!==void 0&&e.length!==0){if(o.key===`e`){o.preventDefault();let r=e[Math.min(c+1,e.length-1)];i(t),r.thread_id!==t&&n(r.thread_id);return}o.key===`r`&&(o.preventDefault(),a(t))}},className:`h-full overflow-y-auto outline-none`,"aria-label":`Notifications`,children:e.map(e=>{let i=e.thread_id===t;return(0,L.jsx)(`li`,{"data-selected":i,children:(0,L.jsxs)(`button`,{type:`button`,onClick:()=>n(e.thread_id),onDoubleClick:r,className:$(`flex w-full flex-col gap-1 border-l-2 px-3 py-2 text-left`,i?`border-l-primary bg-accent`:`border-l-transparent hover:bg-accent/50`),children:[(0,L.jsxs)(`span`,{className:`flex items-baseline gap-2`,children:[(0,L.jsx)(`span`,{className:$(`size-1.5 shrink-0 rounded-full`,e.unread===1?`bg-primary`:`bg-transparent`)}),(0,L.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,children:e.repo_full_name}),(0,L.jsx)(`span`,{className:`ml-auto shrink-0 text-xs text-muted-foreground`,children:S(e.reason)})]}),(0,L.jsx)(`span`,{className:$(`line-clamp-2 pl-3.5 text-sm`,e.unread===1?`font-medium`:`text-muted-foreground`),children:e.subject_title})]})},e.thread_id)})})}var UC=Wf(`inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3`,{variants:{variant:{default:`bg-primary text-primary-foreground [a&]:hover:bg-primary/90`,secondary:`bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90`,destructive:`bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90`,outline:`border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,ghost:`[a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,link:`text-primary underline-offset-4 [a&]:hover:underline`}},defaultVariants:{variant:`default`}});function WC({className:e,variant:t=`default`,asChild:n=!1,...r}){let i=n?dp:`span`;return(0,L.jsx)(i,{"data-slot":`badge`,"data-variant":t,className:$(UC({variant:t}),e),...r})}function GC({notification:e}){return e===void 0?(0,L.jsx)(`div`,{className:`flex h-full items-center justify-center p-8 text-sm text-muted-foreground`,children:`Select a notification`}):(0,L.jsxs)(`div`,{className:`flex h-full flex-col gap-4 overflow-y-auto p-6`,children:[(0,L.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,L.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:e.repo_full_name}),(0,L.jsx)(`h2`,{className:`text-lg font-medium`,children:e.subject_title}),(0,L.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,L.jsx)(WC,{variant:`secondary`,children:S(e.reason)}),(0,L.jsx)(WC,{variant:`outline`,children:e.subject_type}),e.unread===1?(0,L.jsx)(WC,{children:`Unread`}):null]})]}),(0,L.jsxs)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm`,children:[(0,L.jsx)(`dt`,{className:`text-muted-foreground`,children:`Updated`}),(0,L.jsx)(`dd`,{children:new Date(e.updated_at).toLocaleString()}),(0,L.jsx)(`dt`,{className:`text-muted-foreground`,children:`Last read`}),(0,L.jsx)(`dd`,{children:e.last_read_at===null?`Never`:new Date(e.last_read_at).toLocaleString()})]}),(0,L.jsx)(Xx,{asChild:!0,variant:`outline`,size:`sm`,className:`self-start`,children:(0,L.jsx)(`a`,{href:_(e),target:`_blank`,rel:`noreferrer`,children:`Open on GitHub`})}),(0,L.jsx)(`p`,{className:`mt-auto text-xs text-muted-foreground`,children:`The pull request itself, its diff and its checks land here next.`})]})}var KC=Is({id:`notifications`,getKey:e=>e.thread_id,sync:{rowUpdateMode:`full`,sync:({begin:e,write:t,commit:n,markReady:r,markError:i,truncate:a,collection:o})=>{let s=!1,c,l=!1,u=async()=>{let i=await C();if(!s){e(),a();for(let e of i)t({type:`insert`,value:e});n(),r()}},d=()=>c?(l=!0,c):(c=u().catch(e=>{s||(console.error(`notifications sync failed`,e),o.status===`loading`&&i(e))}).finally(()=>{c=void 0,l&&!s&&(l=!1,d())}),c);if(typeof window>`u`)return()=>{s=!0};let f=new EventSource(`/api/events`);return f.addEventListener(`change`,()=>{d()}),d(),()=>{s=!0,f.close()}}},onUpdate:async({transaction:e})=>{for(let t of e.mutations)t.changes.unread===0&&await b({data:t.key})},onDelete:async({transaction:e})=>{for(let t of e.mutations)await f({data:t.key})}});function qC(){let{view:e,thread:t}=D.useSearch(),n=y({from:D.fullPath}),r=D.useLoaderData(),{data:i,isLoading:a}=zf(e=>e.from({notification:KC})),o=a?r:i,s=he({queryKey:[`sync-status`],queryFn:()=>E(),refetchInterval:e=>e.state.data?.hasSynced!==!0&&2e3}).data?.hasSynced!==!0,c=(0,I.useMemo)(()=>[...o].sort((e,t)=>t.updated_at.localeCompare(e.updated_at)),[o]),l=T.find(t=>t.id===e)??T[0],u=(0,I.useMemo)(()=>c.filter(l.match),[c,l]),d=u.find(e=>e.thread_id===t),f=e=>{n({search:t=>({...t,thread:e}),replace:!0})},m=e=>{n({search:{view:e},replace:!0})},h=e=>{KC.delete(e)},g=e=>{KC.update(e,e=>{e.unread=0})},v=()=>{d!==void 0&&window.open(_(d),`_blank`,`noreferrer`)};return(0,L.jsxs)(gS,{children:[(0,L.jsx)(kS,{notifications:c,activeView:l.id}),(0,L.jsx)(yS,{className:`h-svh overflow-hidden`,children:(0,L.jsxs)(`div`,{className:`grid h-full grid-cols-[minmax(280px,380px)_1fr]`,children:[(0,L.jsxs)(`div`,{className:`flex min-h-0 flex-col border-r`,children:[(0,L.jsxs)(`header`,{className:`flex items-center gap-2 border-b px-3 py-2`,children:[(0,L.jsx)(vS,{}),(0,L.jsx)(`span`,{className:`text-sm font-medium`,children:l.label}),(0,L.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:s&&c.length===0?`syncing`:u.length}),(0,L.jsx)(`kbd`,{className:`ml-auto rounded border px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:`⌘K`})]}),(0,L.jsx)(VC,{}),(0,L.jsx)(HC,{notifications:u,selectedId:d?.thread_id,onSelect:f,onOpen:v,onDone:h,onRead:g,emptyMessage:s&&c.length===0?`Fetching your notifications from GitHub...`:`Nothing here`})]}),(0,L.jsx)(GC,{notification:d})]})}),(0,L.jsx)(BC,{onSelectView:m,onOpenSelected:v,onRefresh:()=>void p(),onDoneSelected:d===void 0?void 0:()=>h(d.thread_id),onReadSelected:d===void 0?void 0:()=>g(d.thread_id),canOpenSelected:d!==void 0})]})}export{qC as component};