@membank/dashboard 0.10.0 → 0.11.0

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 (28) hide show
  1. package/dist/bin.mjs +73 -1
  2. package/dist/client/assets/AppLink-CcI58QNL.js +3 -0
  3. package/dist/client/assets/WorkspaceMemoryDetail-CKp3CCbn.js +1 -0
  4. package/dist/client/assets/_projectId-Eeq3OhFZ.js +4 -0
  5. package/dist/client/assets/_projectId._memoryId-BFlrz98g.js +1 -0
  6. package/dist/client/assets/collections-gO05Tpa7.js +19 -0
  7. package/dist/client/assets/index--CCYAGMc.js +48 -0
  8. package/dist/client/assets/index-BudjKWgr.css +2 -0
  9. package/dist/client/assets/popupStateMapping-CKjEg8lE.js +1 -0
  10. package/dist/client/assets/preload-helper-DEuj8E0K.js +1 -0
  11. package/dist/client/assets/review-CnySMKKH.js +1 -0
  12. package/dist/client/assets/routes-LNNp11yc.js +1 -0
  13. package/dist/client/assets/spinner-B9RlP5lt.js +1 -0
  14. package/dist/client/assets/textarea-BLDQQzbc.js +1 -0
  15. package/dist/client/index.html +5 -4
  16. package/dist/index.cjs +72 -0
  17. package/dist/index.mjs +73 -1
  18. package/package.json +1 -1
  19. package/dist/client/assets/WorkspaceMemoryDetail-B-SQPmf_.js +0 -1
  20. package/dist/client/assets/_projectId-ChOHT2g6.js +0 -40
  21. package/dist/client/assets/_projectId-DdCE-NRK.js +0 -4
  22. package/dist/client/assets/_projectId._memoryId-j78rWv7Z.js +0 -1
  23. package/dist/client/assets/collections-Ci78mgZL.js +0 -19
  24. package/dist/client/assets/index-DcreRb0E.js +0 -10
  25. package/dist/client/assets/index-RbnYc2mC.css +0 -2
  26. package/dist/client/assets/routes-CDZywPpw.js +0 -1
  27. package/dist/client/assets/typeColors-BREuYmod.js +0 -3
  28. /package/dist/client/assets/{_projectId.index-jEbJri1I.js → _projectId.index-8YNIf2cB.js} +0 -0
@@ -0,0 +1,19 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),l=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u<e.length;u++)a=e[u],s=l+j(a,u),c+=N(a,r,i,s,o);else if(u=m(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+j(a,u++),c+=N(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return N(M(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function P(e,t,n){if(e==null)return e;var r=[],i=0;return N(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function ee(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var F=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)},te={map:P,forEach:function(e,t,n){P(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return P(e,function(){t++}),t},toArray:function(e){return P(e,function(e){return e})||[]},only:function(e){if(!O(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=te,e.Component=v,e.Fragment=r,e.Profiler=a,e.PureComponent=b,e.StrictMode=i,e.Suspense=l,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=w,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return w.H.useMemoCache(e)}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=g({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!T.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return E(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)T.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return E(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=O,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:ee}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=function(e){var t=w.T,n={};w.T=n;try{var r=e(),i=w.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(C,F)}catch(e){F(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),w.T=t}},e.unstable_useCacheRefresh=function(){return w.H.useCacheRefresh()},e.use=function(e){return w.H.use(e)},e.useActionState=function(e,t,n){return w.H.useActionState(e,t,n)},e.useCallback=function(e,t){return w.H.useCallback(e,t)},e.useContext=function(e){return w.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return w.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return w.H.useEffect(e,t)},e.useEffectEvent=function(e){return w.H.useEffectEvent(e)},e.useId=function(){return w.H.useId()},e.useImperativeHandle=function(e,t,n){return w.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return w.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return w.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return w.H.useMemo(e,t)},e.useOptimistic=function(e,t){return w.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return w.H.useReducer(e,t,n)},e.useRef=function(e){return w.H.useRef(e)},e.useState=function(e){return w.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return w.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return w.H.useTransition()},e.version=`19.2.5`})),u=o(((e,t)=>{t.exports=l()})),d=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),f=o(((e,t)=>{t.exports=d()})),p=o((e=>{var t=u();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),m=o(((e,t)=>{t.exports=p()})),h=o((e=>{var t=u(),n=m();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),g=o(((e,t)=>{t.exports=h()})),_=g(),v=c(u(),1),y=v.use,b=typeof window<`u`?v.useLayoutEffect:v.useEffect;function x(e){let t=v.useRef({value:e,prev:null}),n=t.current.value;return e!==n&&(t.current={value:e,prev:n}),t.current.prev}function S(e,t,n={},r={}){v.useEffect(()=>{if(!e.current||r.disabled||typeof IntersectionObserver!=`function`)return;let i=new IntersectionObserver(([e])=>{t(e)},n);return i.observe(e.current),()=>{i.disconnect()}},[t,n,r.disabled,e])}function C(e){let t=v.useRef(null);return v.useImperativeHandle(e,()=>t.current,[]),t}function w(e){return e[e.length-1]}function T(e){return typeof e==`function`}function E(e,t){return T(e)?e(t):e}var D=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable,k=()=>Object.create(null),A=(e,t)=>j(e,t,k);function j(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=ee(e)&&ee(i);if(!a&&!(N(e)&&N(i)))return i;let o=a?e:M(e);if(!o)return i;let s=a?i:M(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:D.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=j(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function M(e){let t=Object.getOwnPropertyNames(e);for(let n of t)if(!O.call(e,n))return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;let r=t;for(let t of n){if(!O.call(e,t))return!1;r.push(t)}return r}function N(e){if(!P(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!P(n)||!n.hasOwnProperty(`isPrototypeOf`))}function P(e){return Object.prototype.toString.call(e)===`[object Object]`}function ee(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function F(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!F(e[r],t[r],n))return!1;return!0}if(N(e)&&N(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!F(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!F(e[o],t[o],n)))return!1;return i===a}return!1}function te(e){let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.status=`pending`,r.resolve=n=>{r.status=`resolved`,r.value=n,t(n),e?.(n)},r.reject=e=>{r.status=`rejected`,n(e)},r}function ne(e){return typeof e?.message==`string`?e.message.startsWith(`Failed to fetch dynamically imported module`)||e.message.startsWith(`error loading dynamically imported module`)||e.message.startsWith(`Importing a module script failed`):!1}function re(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}function ie(e){return e.replace(/[\x00-\x1f\x7f]/g,``)}function I(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return ie(t)}var L=[`http:`,`https:`,`mailto:`,`tel:`];function ae(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function oe(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=I(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=I(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function R(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function se(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function z(){throw Error(`Invariant failed`)}function ce(e){let t=new Map,n,r,i=e=>{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var B=4,V=5;function le(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function ue(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=le(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2<a.length&&a.charCodeAt(r+2)===36){let e=r+3,a=s;if(e<a)return n[0]=3,n[1]=t+r,n[2]=t+e,n[3]=t+a,n[4]=t+s+1,n[5]=i,n}}else if(c===36){let a=r+1,o=r+2;return o===s?(n[0]=2,n[1]=t+r,n[2]=t+a,n[3]=t+o,n[4]=t+s+1,n[5]=e.length,n):(n[0]=1,n[1]=t+r,n[2]=t+o,n[3]=t+s,n[4]=t+s+1,n[5]=i,n)}}return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n}function de(e,t,n,r,i,a,o){o?.(n);let s=r;{let r=n.fullPath??n.from,o=r.length,c=n.options?.caseSensitive??e,l=!!(n.options?.params?.parse&&n.options?.skipRouteOnParseError?.params);for(;s<o;){let e=ue(r,s,t),o,u=s,d=e[5];switch(s=d+1,a++,e[0]){case 0:{let t=r.substring(e[2],e[3]);if(c){let e=i.static?.get(t);if(e)o=e;else{i.static??=new Map;let e=me(n.fullPath??n.from);e.parent=i,e.depth=a,o=e,i.static.set(t,e)}}else{let e=t.toLowerCase(),r=i.staticInsensitive?.get(e);if(r)o=r;else{i.staticInsensitive??=new Map;let t=me(n.fullPath??n.from);t.parent=i,t.depth=a,o=t,i.staticInsensitive.set(e,t)}}break}case 1:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.dynamic?.find(e=>!e.skipOnParamError&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=he(1,n.fullPath??n.from,f,p,m);o=e,e.depth=a,e.parent=i,i.dynamic??=[],i.dynamic.push(e)}break}case 3:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.optional?.find(e=>!e.skipOnParamError&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=he(3,n.fullPath??n.from,f,p,m);o=e,e.parent=i,e.depth=a,i.optional??=[],i.optional.push(e)}break}case 2:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),l=c&&!!(t||s),f=t?l?t:t.toLowerCase():void 0,p=s?l?s:s.toLowerCase():void 0,m=he(2,n.fullPath??n.from,l,f,p);o=m,m.parent=i,m.depth=a,i.wildcard??=[],i.wildcard.push(m)}}i=o}if(l&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=me(n.fullPath??n.from);e.kind=V,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let u=(n.path||!n.children)&&!n.isRoot;if(u&&r.endsWith(`/`)){let e=me(n.fullPath??n.from);e.kind=B,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=n.options?.params?.parse??null,i.skipOnParamError=l,i.parsingPriority=n.options?.skipRouteOnParseError?.priority??0,u&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(let r of n.children)de(e,t,r,s,i,a,o)}function fe(e,t){if(e.skipOnParamError&&!t.skipOnParamError)return-1;if(!e.skipOnParamError&&t.skipOnParamError)return 1;if(e.skipOnParamError&&t.skipOnParamError&&(e.parsingPriority||t.parsingPriority))return t.parsingPriority-e.parsingPriority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function pe(e){if(e.pathless)for(let t of e.pathless)pe(t);if(e.static)for(let t of e.static.values())pe(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())pe(t);if(e.dynamic?.length){e.dynamic.sort(fe);for(let t of e.dynamic)pe(t)}if(e.optional?.length){e.optional.sort(fe);for(let t of e.optional)pe(t)}if(e.wildcard?.length){e.wildcard.sort(fe);for(let t of e.wildcard)pe(t)}}function me(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,skipOnParamError:!1,parsingPriority:0}}function he(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,skipOnParamError:!1,parsingPriority:0,caseSensitive:n,prefix:r,suffix:i}}function ge(e,t){let n=me(`/`),r=new Uint16Array(6);for(let t of e)de(!1,r,t,1,n,0);pe(n),t.masksTree=n,t.flatCache=ce(1e3)}function _e(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=Se(e,t.masksTree);return t.flatCache.set(e,r),r}function ve(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=me(`/`),de(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),Se(r,o,n)}function ye(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=Se(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=we(a.route)),t.matchCache.set(r,a),a}function be(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function xe(e,t=!1,n){let r=me(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return de(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&z(),a[e.id]=e,s!==0&&e.path){let t=be(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),pe(r),{processedTree:{segmentTree:r,singleCache:ce(1e3),matchCache:ce(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function Se(e,t,n=!1){let r=e.split(`/`),i=Ee(e,r,t,n);if(!i)return null;let[a]=Ce(e,r,i);return{route:i.node.route,rawParams:a,parsedParams:i.parsedParams}}function Ce(e,t,n){let r=Te(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s<r.length;o++,s++,c++,l++){let u=r[s];if(u.kind===B)break;if(u.kind===V){l--,o--,c--;continue}let d=t[o],f=c;if(d&&(c+=d.length),u.kind===1){i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0;if(e.charCodeAt(t)===123){let n=u.suffix?.length??0,r=e.substring(t+2,e.length-n-1),i=d.substring(t,d.length-n);a[r]=decodeURIComponent(i)}else{let t=e.substring(1);a[t]=decodeURIComponent(d)}}else if(u.kind===3){if(n.skipped&1<<s){o--,c=f-1;continue}i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0,r=u.suffix?.length??0,p=e.substring(t+3,e.length-r-1),m=u.suffix||u.prefix?d.substring(t,d.length-r):d;m&&(a[p]=decodeURIComponent(m))}else if(u.kind===2){let t=u,n=e.substring(f+(t.prefix?.length??0),e.length-(t.suffix?.length??0)),r=decodeURIComponent(n);a[`*`]=r,a._splat=r;break}}return n.rawParams&&Object.assign(a,n.rawParams),[a,{part:o,node:s,path:c,segment:l}]}function we(e){let t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function Te(e){let t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function Ee(e,t,n,r){if(e===`/`&&n.index)return{node:n.index,skipped:0};let i=!w(t),a=i&&e!==`/`,o=t.length-+!!i,s=[{node:n,index:1,skipped:0,depth:1,statics:0,dynamics:0,optionals:0}],c=null,l=null;for(;s.length;){let n=s.pop(),{node:i,index:u,skipped:d,depth:f,statics:p,dynamics:m,optionals:h}=n,{extract:g,rawParams:_,parsedParams:v}=n;if(i.kind===2&&i.route&&!Ae(l,n))continue;if(i.skipOnParamError){if(!ke(e,t,n))continue;_=n.rawParams,g=n.extract,v=n.parsedParams}r&&i.route&&i.kind!==B&&Ae(c,n)&&(c=n);let y=u===o;if(y&&(i.route&&(!a||i.kind===B||i.kind===2)&&Ae(l,n)&&(l=n),!i.optional&&!i.wildcard&&!i.index&&!i.pathless))continue;let b=y?void 0:t[u],x;if(y&&i.index){let n={node:i.index,index:u,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v},r=!0;if(i.index.skipOnParamError&&(ke(e,t,n)||(r=!1)),r){if(!m&&!h&&!d&&Oe(p,o))return n;Ae(l,n)&&(l=n)}}if(i.wildcard)for(let e=i.wildcard.length-1;e>=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(y||!(n.caseSensitive?b:x??=b.toLowerCase()).startsWith(r)))){if(a){if(y)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}}if(i.optional){let e=d|1<<f,t=f+1;for(let n=i.optional.length-1;n>=0;n--){let r=i.optional[n];s.push({node:r,index:u,skipped:e,depth:t,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}if(!y)for(let e=i.optional.length-1;e>=0;e--){let n=i.optional[e],{prefix:r,suffix:a}=n;if(r||a){let e=n.caseSensitive?b:x??=b.toLowerCase();if(r&&!e.startsWith(r)||a&&!e.endsWith(a))continue}s.push({node:n,index:u+1,skipped:d,depth:t,statics:p,dynamics:m,optionals:h+De(o,u),extract:g,rawParams:_,parsedParams:v})}}if(!y&&i.dynamic&&b)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?b:x??=b.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,depth:f+1,statics:p,dynamics:m+De(o,u),optionals:h,extract:g,rawParams:_,parsedParams:v})}if(!y&&i.staticInsensitive){let e=i.staticInsensitive.get(x??=b.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+De(o,u),dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}if(!y&&i.static){let e=i.static.get(b);e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+De(o,u),dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}if(i.pathless){let e=f+1;for(let t=i.pathless.length-1;t>=0;t--){let n=i.pathless[t];s.push({node:n,index:u,skipped:d,depth:e,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;e<c.index;e++)n+=t[e].length;let r=n===e.length?`/`:e.slice(n);return c.rawParams??=Object.create(null),c.rawParams[`**`]=decodeURIComponent(r),c}return null}function De(e,t){return 2**(e-t-1)}function Oe(e,t){return e===2**(t-1)-1}function ke(e,t,n){try{let[r,i]=Ce(e,t,n);n.rawParams=r,n.extract=i;let a=n.node.parse(r);return n.parsedParams=Object.assign(Object.create(null),n.parsedParams,a),!0}catch{return null}}function Ae(e,t){return e?t.statics>e.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===B)>(e.node.kind===B)||t.node.kind===B==(e.node.kind===B)&&t.depth>e.depth))):!0}function je(e){return Me(e.filter(e=>e!==void 0).join(`/`))}function Me(e){return e.replace(/\/{2,}/g,`/`)}function Ne(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function Pe(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function Fe(e){return Pe(Ne(e))}function Ie(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function Le(e,t,n){return Ie(e,n)===Ie(t,n)}function Re({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t.startsWith(`/`),a=!i&&t===`.`,o;if(r){o=i?t:a?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(a)s=e.split(`/`);else if(i)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&w(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e<t;e++){let r=n[e];r===``?e?e===t-1&&s.push(r):s=[r]:r===`..`?s.pop():r===`.`||s.push(r)}}s.length>1&&(w(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c,l=``;for(let e=0;e<s.length;e++){e>0&&(l+=`/`);let t=s[e];if(!t)continue;c=ue(t,0,c);let n=c[0];if(n===0){l+=t;continue}let r=c[5],i=t.substring(0,c[1]),a=t.substring(c[4],r),o=t.substring(c[2],c[3]);n===1?l+=i||a?`${i}{$${o}}${a}`:`$${o}`:n===2?l+=i||a?`${i}{$}${a}`:`$`:l+=`${i}{-$${o}}${a}`}l=Me(l);let u=l||`/`;return o&&r&&r.set(o,u),u}function ze(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function Be(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>He(e,n)).join(`/`):He(r,n):r}function Ve({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s<o;){let r=s;c=ue(e,r,c);let o=c[5];if(s=o+1,r===o)continue;let u=c[0];if(u===0){l+=`/`+e.substring(r,o);continue}if(u===2){let s=t._splat;a._splat=s,a[`*`]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o);if(!s){i=!0,(u||d)&&(l+=`/`+u+d);continue}let f=Be(`_splat`,t,n);l+=`/`+u+f+d;continue}if(u===1){let s=e.substring(c[2],c[3]);!i&&!(s in t)&&(i=!0),a[s]=t[s];let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Be(s,t,n)??`undefined`;l+=`/`+u+f+d;continue}if(u===3){let i=e.substring(c[2],c[3]),s=t[i];if(s==null)continue;a[i]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Be(i,t,n)??``;l+=`/`+u+f+d;continue}}return e.endsWith(`/`)&&(l+=`/`),{usedParams:a,interpolatedPath:l||`/`,isMissingParams:i}}function He(e,t){let n=encodeURIComponent(e);return t?.(n)??n}var Ue=`Error preloading route! ☝️`,We=f();function Ge({children:e,fallback:t=null}){return Ke()?(0,We.jsx)(v.Fragment,{children:e}):(0,We.jsx)(v.Fragment,{children:t})}function Ke(){return v.useSyncExternalStore(qe,()=>!0,()=>!1)}function qe(){return()=>{}}var Je=v.createContext(null);function Ye(e){return v.useContext(Je)}function Xe(e,t){return e===t}function Ze(e,t,n=Xe){let r=(0,v.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,v.useCallback)(()=>e?.get(),[e]);return(0,_.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Qe=o((e=>{var t=u();function n(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function r(){}var i={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},a=Symbol.for(`react.portal`);function o(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:a,key:r==null?null:``+r,children:e,containerInfo:t,implementation:n}}var s=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function c(e,t){if(e===`font`)return``;if(typeof t==`string`)return t===`use-credentials`?t:``}e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,e.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)throw Error(n(299));return o(e,t,null,r)},e.flushSync=function(e){var t=s.T,n=i.p;try{if(s.T=null,i.p=2,e)return e()}finally{s.T=t,i.p=n,i.d.f()}},e.preconnect=function(e,t){typeof e==`string`&&(t?(t=t.crossOrigin,t=typeof t==`string`?t===`use-credentials`?t:``:void 0):t=null,i.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&i.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin),a=typeof t.integrity==`string`?t.integrity:void 0,o=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?i.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:a,fetchPriority:o}):n===`script`&&i.d.X(e,{crossOrigin:r,integrity:a,fetchPriority:o,nonce:typeof t.nonce==`string`?t.nonce:void 0})}},e.preinitModule=function(e,t){if(typeof e==`string`)if(typeof t==`object`&&t){if(t.as==null||t.as===`script`){var n=c(t.as,t.crossOrigin);i.d.M(e,{crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0})}}else t??i.d.M(e)},e.preload=function(e,t){if(typeof e==`string`&&typeof t==`object`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin);i.d.L(e,n,{crossOrigin:r,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,type:typeof t.type==`string`?t.type:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0,referrerPolicy:typeof t.referrerPolicy==`string`?t.referrerPolicy:void 0,imageSrcSet:typeof t.imageSrcSet==`string`?t.imageSrcSet:void 0,imageSizes:typeof t.imageSizes==`string`?t.imageSizes:void 0,media:typeof t.media==`string`?t.media:void 0})}},e.preloadModule=function(e,t){if(typeof e==`string`)if(t){var n=c(t.as,t.crossOrigin);i.d.m(e,{as:typeof t.as==`string`&&t.as!==`script`?t.as:void 0,crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0})}else i.d.m(e)},e.requestFormReset=function(e){i.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return s.H.useFormState(e,t,n)},e.useFormStatus=function(){return s.H.useHostTransitionStatus()},e.version=`19.2.5`})),$e=o(((e,t)=>{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=Qe()})),et=c($e(),1);function tt(e,t){let n=Ye(),r=C(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:y,style:b,className:x,onClick:w,onBlur:T,onFocus:D,onMouseEnter:O,onMouseLeave:k,onTouchStart:A,ignoreBlocker:j,params:M,search:N,hash:P,state:ee,mask:te,reloadDocument:ne,unsafeRelative:re,from:ie,_fromLocation:I,...L}=e,oe=Ke(),R=v.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),se=Ze(n.stores.location,e=>e,(e,t)=>e.href===t.href),z=v.useMemo(()=>{let e={_fromLocation:se,...R};return n.buildLocation(e)},[n,se,R]),ce=z.maskedLocation?z.maskedLocation.publicHref:z.publicHref,B=z.maskedLocation?z.maskedLocation.external:z.external,V=v.useMemo(()=>ut(ce,B,n.history,y),[y,B,ce,n.history]),le=v.useMemo(()=>{if(V?.external)return ae(V.href,n.protocolAllowlist)?void 0:V.href;if(!dt(s)&&!(typeof s!=`string`||s.indexOf(`:`)===-1))try{return new URL(s),ae(s,n.protocolAllowlist)?void 0:s}catch{}},[s,V,n.protocolAllowlist]),ue=v.useMemo(()=>{if(le)return!1;if(o?.exact){if(!Le(se.pathname,z.pathname,n.basepath))return!1}else{let e=Ie(se.pathname,n.basepath),t=Ie(z.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!F(se.search,z.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:o?.includeHash?oe&&se.hash===z.hash:!0},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,se,le,oe,z.hash,z.pathname,z.search,n.basepath]),de=ue?E(i,{})??rt:nt,fe=ue?nt:E(a,{})??nt,pe=[x,de.className,fe.className].filter(Boolean).join(` `),me=(b||de.style||fe.style)&&{...b,...de.style,...fe.style},[he,ge]=v.useState(!1),_e=v.useRef(!1),ve=e.reloadDocument||le?!1:c??n.options.defaultPreload,ye=l??n.options.defaultPreloadDelay??0,be=v.useCallback(()=>{n.preloadRoute({...R,_builtLocation:z}).catch(e=>{console.warn(e),console.warn(Ue)})},[n,R,z]);S(r,v.useCallback(e=>{e?.isIntersecting&&be()},[be]),ct,{disabled:!!y||ve!==`viewport`}),v.useEffect(()=>{_e.current||!y&&ve===`render`&&(be(),_e.current=!0)},[y,be,ve]);let xe=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;if(!y&&!mt(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,et.flushSync)(()=>{ge(!0)});let t=n.subscribe(`onResolved`,()=>{t(),ge(!1)});n.navigate({...R,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:j})}};if(le)return{...L,ref:r,href:le,...g&&{children:g},..._&&{target:_},...y&&{disabled:y},...b&&{style:b},...x&&{className:x},...w&&{onClick:w},...T&&{onBlur:T},...D&&{onFocus:D},...O&&{onMouseEnter:O},...k&&{onMouseLeave:k},...A&&{onTouchStart:A}};let Se=e=>{if(y||ve!==`intent`)return;if(!ye){be();return}let t=e.currentTarget;if(st.has(t))return;let n=setTimeout(()=>{st.delete(t),be()},ye);st.set(t,n)},Ce=e=>{y||ve!==`intent`||be()},we=e=>{if(y||!ve||!ye)return;let t=e.currentTarget,n=st.get(t);n&&(clearTimeout(n),st.delete(t))};return{...L,...de,...fe,href:V?.href,ref:r,onClick:lt([w,xe]),onBlur:lt([T,we]),onFocus:lt([D,Se]),onMouseEnter:lt([O,Se]),onMouseLeave:lt([k,we]),onTouchStart:lt([A,Ce]),disabled:!!y,target:_,...me&&{style:me},...pe&&{className:pe},...y&&it,...ue&&at,...oe&&he&&ot}}var nt={},rt={className:`active`},it={role:`link`,"aria-disabled":!0},at={"data-status":`active`,"aria-current":`page`},ot={"data-transitioning":`transitioning`},st=new WeakMap,ct={rootMargin:`100px`},lt=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function ut(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function dt(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}function ft(e){return v.forwardRef(function(t,n){return(0,We.jsx)(pt,{...t,_asChild:e,ref:n})})}var pt=v.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=tt(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return v.createElement(`a`,t,o)}return v.createElement(n,a,o)});function mt(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var ht=o((e=>{var t=u().__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;e.c=function(e){return t.H.useMemoCache(e)}})),gt=o(((e,t)=>{t.exports=ht()})),_t={};function vt(e,t){let n=v.useRef(_t);return n.current===_t&&(n.current=e(t)),n}var yt=typeof document<`u`?v.useLayoutEffect:()=>{};function bt(e,t){return function(n,...r){let i=new URL(e);return i.searchParams.set(`code`,n.toString()),r.forEach(e=>i.searchParams.append(`args[]`,e)),`${t} error #${n}; visit ${i} for the full message.`}}var xt=bt(`https://base-ui.com/production-error`,`Base UI`),St=[];function Ct(e){v.useEffect(e,St)}var wt=0,Tt=class e{static create(){return new e}currentId=wt;start(e,t){this.clear(),this.currentId=setTimeout(()=>{this.currentId=wt,t()},e)}isStarted(){return this.currentId!==wt}clear=()=>{this.currentId!==wt&&(clearTimeout(this.currentId),this.currentId=wt)};disposeEffect=()=>this.clear};function Et(){let e=vt(Tt.create).current;return Ct(e.disposeEffect),e}var Dt=typeof navigator<`u`,Ot=Lt(),kt=zt(),At=Rt(),jt=typeof CSS>`u`||!CSS.supports?!1:CSS.supports(`-webkit-backdrop-filter:none`),Mt=Ot.platform===`MacIntel`&&Ot.maxTouchPoints>1?!0:/iP(hone|ad|od)|iOS/.test(Ot.platform);Dt&&/firefox/i.test(At);var Nt=Dt&&/apple/i.test(navigator.vendor);Dt&&/Edg/i.test(At);var Pt=Dt&&/android/i.test(kt)||/android/i.test(At),Ft=Dt&&kt.toLowerCase().startsWith(`mac`)&&!navigator.maxTouchPoints,It=At.includes(`jsdom/`);function Lt(){if(!Dt)return{platform:``,maxTouchPoints:-1};let e=navigator.userAgentData;return e?.platform?{platform:e.platform,maxTouchPoints:navigator.maxTouchPoints}:{platform:navigator.platform??``,maxTouchPoints:navigator.maxTouchPoints??-1}}function Rt(){if(!Dt)return``;let e=navigator.userAgentData;return e&&Array.isArray(e.brands)?e.brands.map(({brand:e,version:t})=>`${e}/${t}`).join(` `):navigator.userAgent}function zt(){if(!Dt)return``;let e=navigator.userAgentData;return e?.platform?e.platform:navigator.platform??``}function Bt(){}var Vt=Object.freeze([]),Ht=Object.freeze({});function Ut(){return typeof window<`u`}function Wt(e){return qt(e)?(e.nodeName||``).toLowerCase():`#document`}function Gt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Kt(e){return((qt(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function qt(e){return Ut()?e instanceof Node||e instanceof Gt(e).Node:!1}function Jt(e){return Ut()?e instanceof Element||e instanceof Gt(e).Element:!1}function Yt(e){return Ut()?e instanceof HTMLElement||e instanceof Gt(e).HTMLElement:!1}function Xt(e){return!Ut()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof Gt(e).ShadowRoot}function Zt(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=ln(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function Qt(e){return/^(table|td|th)$/.test(Wt(e))}function $t(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var en=/transform|translate|scale|rotate|perspective|filter/,tn=/paint|layout|strict|content/,nn=e=>!!e&&e!==`none`,rn;function an(e){let t=Jt(e)?ln(e):e;return nn(t.transform)||nn(t.translate)||nn(t.scale)||nn(t.rotate)||nn(t.perspective)||!sn()&&(nn(t.backdropFilter)||nn(t.filter))||en.test(t.willChange||``)||tn.test(t.contain||``)}function on(e){let t=dn(e);for(;Yt(t)&&!cn(t);){if(an(t))return t;if($t(t))return null;t=dn(t)}return null}function sn(){return rn??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),rn}function cn(e){return/^(html|body|#document)$/.test(Wt(e))}function ln(e){return Gt(e).getComputedStyle(e)}function un(e){return Jt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function dn(e){if(Wt(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||Xt(e)&&e.host||Kt(e);return Xt(t)?t.host:t}function fn(e){let t=dn(e);return cn(t)?e.ownerDocument?e.ownerDocument.body:e.body:Yt(t)&&Zt(t)?t:fn(t)}function pn(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=fn(e),i=r===e.ownerDocument?.body,a=Gt(r);if(i){let e=mn(a);return t.concat(a,a.visualViewport||[],Zt(r)?r:[],e&&n?pn(e):[])}else return t.concat(r,pn(r,[],n))}function mn(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function hn(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}function gn(e,t,n,r){let i=vt(vn).current;return yn(i,e,t,n,r)&&xn(i,[e,t,n,r]),i.callback}function _n(e){let t=vt(vn).current;return bn(t,e)&&xn(t,e),t.callback}function vn(){return{callback:null,cleanup:null,refs:[]}}function yn(e,t,n,r,i){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==r||e.refs[3]!==i}function bn(e,t){return e.refs.length!==t.length||e.refs.some((e,n)=>e!==t[n])}function xn(e,t){if(e.refs=t,t.every(e=>e==null)){e.callback=null;return}e.callback=n=>{if(e.cleanup&&=(e.cleanup(),null),n!=null){let r=Array(t.length).fill(null);for(let e=0;e<t.length;e+=1){let i=t[e];if(i!=null)switch(typeof i){case`function`:{let t=i(n);typeof t==`function`&&(r[e]=t);break}case`object`:i.current=n;break;default:}}e.cleanup=()=>{for(let e=0;e<t.length;e+=1){let n=t[e];if(n!=null)switch(typeof n){case`function`:{let t=r[e];typeof t==`function`?t():n(null);break}case`object`:n.current=null;break;default:}}}}}}var Sn=v[`useInsertionEffect${Math.random().toFixed(1)}`.slice(0,-3)],Cn=Sn&&Sn!==v.useLayoutEffect?Sn:e=>e();function wn(e){let t=vt(Tn).current;return t.next=e,Cn(t.effect),t.trampoline}function Tn(){let e={next:void 0,callback:En,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function En(){}function Dn(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function On(e,t){if(!e||!t)return!1;let n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&Xt(n)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function kn(e){return`composedPath`in e?e.composedPath()[0]:e.target}var An={...v},jn=0;function Mn(e,t=`mui`){let[n,r]=v.useState(e),i=e||n;return v.useEffect(()=>{n??(jn+=1,r(`${t}-${jn}`))},[n,t]),i}var Nn=An.useId;function Pn(e,t){if(Nn!==void 0){let n=Nn();return e??(t?`${t}-${n}`:n)}return Mn(e,t)}var Fn=19;function In(e){return Fn>=e}function Ln(e){if(!v.isValidElement(e))return null;let t=e,n=t.props;return(In(19)?n?.ref:t.ref)??null}function Rn(e,t){if(e&&!t)return e;if(!e&&t)return t;if(e||t)return{...e,...t}}function zn(e,t){let n={};for(let r in e){let i=e[r];if(t?.hasOwnProperty(r)){let e=t[r](i);e!=null&&Object.assign(n,e);continue}i===!0?n[`data-${r.toLowerCase()}`]=``:i&&(n[`data-${r.toLowerCase()}`]=i.toString())}return n}function Bn(e,t){return typeof e==`function`?e(t):e}function Vn(e,t){return typeof e==`function`?e(t):e}var Hn={};function Un(e,t,n,r,i){if(!n&&!r&&!i&&!e)return Gn(t);let a=Gn(e);return t&&(a=Kn(a,t)),n&&(a=Kn(a,n)),r&&(a=Kn(a,r)),i&&(a=Kn(a,i)),a}function Wn(e){if(e.length===0)return Hn;if(e.length===1)return Gn(e[0]);let t=Gn(e[0]);for(let n=1;n<e.length;n+=1)t=Kn(t,e[n]);return t}function Gn(e){return Xn(e)?{...Zn(e,Hn)}:qn(e)}function Kn(e,t){return Xn(t)?Zn(t,e):Jn(e,t)}function qn(e){let t={...e};for(let e in t){let n=t[e];Yn(e,n)&&(t[e]=$n(n))}return t}function Jn(e,t){if(!t)return e;for(let n in t){let r=t[n];switch(n){case`style`:e[n]=Rn(e.style,r);break;case`className`:e[n]=tr(e.className,r);break;default:Yn(n,r)?e[n]=Qn(e[n],r):e[n]=r}}return e}function Yn(e,t){let n=e.charCodeAt(0),r=e.charCodeAt(1),i=e.charCodeAt(2);return n===111&&r===110&&i>=65&&i<=90&&(typeof t==`function`||t===void 0)}function Xn(e){return typeof e==`function`}function Zn(e,t){return Xn(e)?e(t):e??Hn}function Qn(e,t){return t?e?(...n)=>{let r=n[0];if(nr(r)){let i=r;er(i);let a=t(...n);return i.baseUIHandlerPrevented||e?.(...n),a}let i=t(...n);return e?.(...n),i}:$n(t):e}function $n(e){return e&&((...t)=>{let n=t[0];return nr(n)&&er(n),e(...t)})}function er(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function tr(e,t){return t?e?t+` `+e:t:e}function nr(e){return typeof e==`object`&&!!e&&`nativeEvent`in e}function rr(e,t,n={}){let r=t.render,i=ir(t,n);return n.enabled===!1?null:sr(e,r,i,n.state??Ht)}function ir(e,t={}){let{className:n,style:r,render:i}=e,{state:a=Ht,ref:o,props:s,stateAttributesMapping:c,enabled:l=!0}=t,u=l?Bn(n,a):void 0,d=l?Vn(r,a):void 0,f=l?zn(a,c):Ht,p=l&&s?ar(s):void 0,m=l?Rn(f,p)??{}:Ht;return typeof document<`u`&&(l?Array.isArray(o)?m.ref=_n([m.ref,Ln(i),...o]):m.ref=gn(m.ref,Ln(i),o):gn(null,null)),l?(u!==void 0&&(m.className=tr(m.className,u)),d!==void 0&&(m.style=Rn(m.style,d)),m):Ht}function ar(e){return Array.isArray(e)?Wn(e):Un(void 0,e)}var or=Symbol.for(`react.lazy`);function sr(e,t,n,r){if(t){if(typeof t==`function`)return t(n,r);let e=Un(n,t.props);e.ref=n.ref;let i=t;return i?.$$typeof===or&&(i=v.Children.toArray(t)[0]),v.cloneElement(i,e)}if(e&&typeof e==`string`)return cr(e,n);throw Error(xt(8))}function cr(e,t){return e===`button`?(0,v.createElement)(`button`,{type:`button`,...t,key:t.key}):e===`img`?(0,v.createElement)(`img`,{alt:``,...t,key:t.key}):v.createElement(e,t)}function lr(e){return Pn(e,`base-ui`)}function ur(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=ur(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n);return r}function dr(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=ur(e))&&(r&&(r+=` `),r+=t);return r}var fr=(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},pr=(e,t)=>({classGroupId:e,validator:t}),mr=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),hr=`-`,gr=[],_r=`arbitrary..`,vr=e=>{let t=xr(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return br(e);let n=e.split(hr);return yr(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?fr(i,t):t:i||gr}return n[e]||gr}}},yr=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=yr(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(hr):e.slice(t).join(hr),s=a.length;for(let e=0;e<s;e++){let t=a[e];if(t.validator(o))return t.classGroupId}},br=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?_r+r:void 0})(),xr=e=>{let{theme:t,classGroups:n}=e;return Sr(n,t)},Sr=(e,t)=>{let n=mr();for(let r in e){let i=e[r];Cr(i,n,r,t)}return n},Cr=(e,t,n,r)=>{let i=e.length;for(let a=0;a<i;a++){let i=e[a];wr(i,t,n,r)}},wr=(e,t,n,r)=>{if(typeof e==`string`){Tr(e,t,n);return}if(typeof e==`function`){Er(e,t,n,r);return}Dr(e,t,n,r)},Tr=(e,t,n)=>{let r=e===``?t:Or(t,e);r.classGroupId=n},Er=(e,t,n,r)=>{if(kr(e)){Cr(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(pr(n,e))},Dr=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e<a;e++){let[a,o]=i[e];Cr(o,Or(t,a),n,r)}},Or=(e,t)=>{let n=e,r=t.split(hr),i=r.length;for(let e=0;e<i;e++){let t=r[e],i=n.nextPart.get(t);i||(i=mr(),n.nextPart.set(t,i)),n=i}return n},kr=e=>`isThemeGetter`in e&&e.isThemeGetter===!0,Ar=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)}}},jr=`!`,Mr=`:`,Nr=[],Pr=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Fr=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===Mr){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(jr)?(c=s.slice(0,-1),l=!0):s.startsWith(jr)&&(c=s.slice(1),l=!0);let u=a&&a>i?a-i:void 0;return Pr(t,l,c,u)};if(t){let e=t+Mr,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):Pr(Nr,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},Ir=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}},Lr=e=>({cache:Ar(e.cacheSize),parseClassName:Fr(e),sortModifiers:Ir(e),...vr(e)}),Rr=/\s+/,zr=(e,t)=>{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a}=t,o=[],s=e.trim().split(Rr),c=``;for(let e=s.length-1;e>=0;--e){let t=s[e],{isExternal:l,modifiers:u,hasImportantModifier:d,baseClassName:f,maybePostfixModifierPosition:p}=n(t);if(l){c=t+(c.length>0?` `+c:c);continue}let m=!!p,h=r(m?f.substring(0,p):f);if(!h){if(!m){c=t+(c.length>0?` `+c:c);continue}if(h=r(f),!h){c=t+(c.length>0?` `+c:c);continue}m=!1}let g=u.length===0?``:u.length===1?u[0]:a(u).join(`:`),_=d?g+jr:g,v=_+h;if(o.indexOf(v)>-1)continue;o.push(v);let y=i(h,m);for(let e=0;e<y.length;++e){let t=y[e];o.push(_+t)}c=t+(c.length>0?` `+c:c)}return c},Br=(...e)=>{let t=0,n,r,i=``;for(;t<e.length;)(n=e[t++])&&(r=Vr(n))&&(i&&(i+=` `),i+=r);return i},Vr=e=>{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r<e.length;r++)e[r]&&(t=Vr(e[r]))&&(n&&(n+=` `),n+=t);return n},Hr=(e,...t)=>{let n,r,i,a,o=o=>(n=Lr(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=zr(e,n);return i(e,a),a};return a=o,(...e)=>a(Br(...e))},Ur=[],H=e=>{let t=t=>t[e]||Ur;return t.isThemeGetter=!0,t},Wr=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Gr=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Kr=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,qr=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Jr=/\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$/,Yr=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Xr=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Zr=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Qr=e=>Kr.test(e),U=e=>!!e&&!Number.isNaN(Number(e)),$r=e=>!!e&&Number.isInteger(Number(e)),ei=e=>e.endsWith(`%`)&&U(e.slice(0,-1)),ti=e=>qr.test(e),ni=()=>!0,ri=e=>Jr.test(e)&&!Yr.test(e),ii=()=>!1,ai=e=>Xr.test(e),oi=e=>Zr.test(e),si=e=>!W(e)&&!G(e),ci=e=>Ci(e,Di,ii),W=e=>Wr.test(e),li=e=>Ci(e,Oi,ri),ui=e=>Ci(e,ki,U),di=e=>Ci(e,ji,ni),fi=e=>Ci(e,Ai,ii),pi=e=>Ci(e,Ti,ii),mi=e=>Ci(e,Ei,oi),hi=e=>Ci(e,Mi,ai),G=e=>Gr.test(e),gi=e=>wi(e,Oi),_i=e=>wi(e,Ai),vi=e=>wi(e,Ti),yi=e=>wi(e,Di),bi=e=>wi(e,Ei),xi=e=>wi(e,Mi,!0),Si=e=>wi(e,ji,!0),Ci=(e,t,n)=>{let r=Wr.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},wi=(e,t,n=!1)=>{let r=Gr.exec(e);return r?r[1]?t(r[1]):n:!1},Ti=e=>e===`position`||e===`percentage`,Ei=e=>e===`image`||e===`url`,Di=e=>e===`length`||e===`size`||e===`bg-size`,Oi=e=>e===`length`,ki=e=>e===`number`,Ai=e=>e===`family-name`,ji=e=>e===`number`||e===`weight`,Mi=e=>e===`shadow`,Ni=Hr(()=>{let e=H(`color`),t=H(`font`),n=H(`text`),r=H(`font-weight`),i=H(`tracking`),a=H(`leading`),o=H(`breakpoint`),s=H(`container`),c=H(`spacing`),l=H(`radius`),u=H(`shadow`),d=H(`inset-shadow`),f=H(`text-shadow`),p=H(`drop-shadow`),m=H(`blur`),h=H(`perspective`),g=H(`aspect`),_=H(`ease`),v=H(`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(),G,W],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[G,W,c],T=()=>[Qr,`full`,`auto`,...w()],E=()=>[$r,`none`,`subgrid`,G,W],D=()=>[`auto`,{span:[`full`,$r,G,W]},$r,G,W],O=()=>[$r,`auto`,G,W],k=()=>[`auto`,`min`,`max`,`fr`,G,W],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=()=>[Qr,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],P=()=>[Qr,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],ee=()=>[Qr,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],F=()=>[e,G,W],te=()=>[...b(),vi,pi,{position:[G,W]}],ne=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,yi,ci,{size:[G,W]}],ie=()=>[ei,gi,li],I=()=>[``,`none`,`full`,l,G,W],L=()=>[``,U,gi,li],ae=()=>[`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=()=>[U,ei,vi,pi],se=()=>[``,`none`,m,G,W],z=()=>[`none`,U,G,W],ce=()=>[`none`,U,G,W],B=()=>[U,G,W],V=()=>[Qr,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[ti],breakpoint:[ti],color:[ni],container:[ti],"drop-shadow":[ti],ease:[`in`,`out`,`in-out`],font:[si],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[ti],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[ti],shadow:[ti],spacing:[`px`,U],text:[ti],"text-shadow":[ti],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,Qr,W,G,g]}],container:[`container`],columns:[{columns:[U,W,G,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:[$r,`auto`,G,W]}],basis:[{basis:[Qr,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[U,Qr,`auto`,`initial`,`none`,W]}],grow:[{grow:[``,U,G,W]}],shrink:[{shrink:[``,U,G,W]}],order:[{order:[$r,`first`,`last`,`none`,G,W]}],"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,gi,li]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Si,di]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,ei,W]}],"font-family":[{font:[_i,fi,t]}],"font-features":[{"font-features":[W]}],"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,G,W]}],"line-clamp":[{"line-clamp":[U,`none`,G,ui]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,G,W]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,G,W]}],"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:[...ae(),`wavy`]}],"text-decoration-thickness":[{decoration:[U,`from-font`,`auto`,G,li]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[U,`auto`,G,W]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,G,W]}],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`,G,W]}],"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`]},$r,G,W],radial:[``,G,W],conic:[$r,G,W]},bi,mi]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:L()}],"border-w-x":[{"border-x":L()}],"border-w-y":[{"border-y":L()}],"border-w-s":[{"border-s":L()}],"border-w-e":[{"border-e":L()}],"border-w-bs":[{"border-bs":L()}],"border-w-be":[{"border-be":L()}],"border-w-t":[{"border-t":L()}],"border-w-r":[{"border-r":L()}],"border-w-b":[{"border-b":L()}],"border-w-l":[{"border-l":L()}],"divide-x":[{"divide-x":L()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":L()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...ae(),`hidden`,`none`]}],"divide-style":[{divide:[...ae(),`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:[...ae(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[U,G,W]}],"outline-w":[{outline:[``,U,gi,li]}],"outline-color":[{outline:F()}],shadow:[{shadow:[``,`none`,u,xi,hi]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":[`none`,d,xi,hi]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:L()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[U,li]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":L()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":[`none`,f,xi,hi]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[U,G,W]}],"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":[U]}],"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":[G,W]}],"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":[U]}],"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`,G,W]}],filter:[{filter:[``,`none`,G,W]}],blur:[{blur:se()}],brightness:[{brightness:[U,G,W]}],contrast:[{contrast:[U,G,W]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,xi,hi]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:[``,U,G,W]}],"hue-rotate":[{"hue-rotate":[U,G,W]}],invert:[{invert:[``,U,G,W]}],saturate:[{saturate:[U,G,W]}],sepia:[{sepia:[``,U,G,W]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,G,W]}],"backdrop-blur":[{"backdrop-blur":se()}],"backdrop-brightness":[{"backdrop-brightness":[U,G,W]}],"backdrop-contrast":[{"backdrop-contrast":[U,G,W]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,U,G,W]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[U,G,W]}],"backdrop-invert":[{"backdrop-invert":[``,U,G,W]}],"backdrop-opacity":[{"backdrop-opacity":[U,G,W]}],"backdrop-saturate":[{"backdrop-saturate":[U,G,W]}],"backdrop-sepia":[{"backdrop-sepia":[``,U,G,W]}],"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`,G,W]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[U,`initial`,G,W]}],ease:[{ease:[`linear`,`initial`,_,G,W]}],delay:[{delay:[U,G,W]}],animate:[{animate:[`none`,v,G,W]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,G,W]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:z()}],"rotate-x":[{"rotate-x":z()}],"rotate-y":[{"rotate-y":z()}],"rotate-z":[{"rotate-z":z()}],scale:[{scale:ce()}],"scale-x":[{"scale-x":ce()}],"scale-y":[{"scale-y":ce()}],"scale-z":[{"scale-z":ce()}],"scale-3d":[`scale-3d`],skew:[{skew:B()}],"skew-x":[{"skew-x":B()}],"skew-y":[{"skew-y":B()}],transform:[{transform:[G,W,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:V()}],"translate-x":[{"translate-x":V()}],"translate-y":[{"translate-y":V()}],"translate-z":[{"translate-z":V()}],"translate-none":[`translate-none`],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`,G,W]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"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`,G,W]}],fill:[{fill:[`none`,...F()]}],"stroke-w":[{stroke:[U,gi,li,ui]}],stroke:[{stroke:[`none`,...F()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{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`]},orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function Pi(...e){return Ni(dr(e))}function Fi(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ii(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return`just now`;if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}var Li=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,Ri=dr,zi=(e,t)=>n=>{if(t?.variants==null)return Ri(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=Li(t)||Li(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 Ri(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)};function Bi(e){if(!e||typeof document>`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var Vi=e=>{switch(e){case`success`:return Wi;case`info`:return Ki;case`warning`:return Gi;case`error`:return qi;default:return null}},Hi=Array(12).fill(0),Ui=({visible:e,className:t})=>v.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},v.createElement(`div`,{className:`sonner-spinner`},Hi.map((e,t)=>v.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),Wi=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},v.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),Gi=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},v.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),Ki=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},v.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),qi=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},v.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),Ji=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},v.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),v.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),Yi=()=>{let[e,t]=v.useState(document.hidden);return v.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},Xi=1,Zi=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:Xi++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],v.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if($i(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!v.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!v.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!v.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!v.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||Xi++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Qi=(e,t)=>{let n=t?.id||Xi++;return Zi.addToast({title:e,...t,id:n}),n},$i=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,ea=Object.assign(Qi,{success:Zi.success,info:Zi.info,warning:Zi.warning,error:Zi.error,custom:Zi.custom,message:Zi.message,promise:Zi.promise,dismiss:Zi.dismiss,loading:Zi.loading},{getHistory:()=>Zi.toasts,getToasts:()=>Zi.getActiveToasts()});Bi(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function ta(e){return e.label!==void 0}var na=3,ra=`24px`,ia=`16px`,aa=4e3,oa=356,sa=14,ca=45,la=200;function ua(...e){return e.filter(Boolean).join(` `)}function da(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var fa=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:y=``,duration:b,position:x,gap:S,expandByDefault:C,classNames:w,icons:T,closeButtonAriaLabel:E=`Close toast`}=e,[D,O]=v.useState(null),[k,A]=v.useState(null),[j,M]=v.useState(!1),[N,P]=v.useState(!1),[ee,F]=v.useState(!1),[te,ne]=v.useState(!1),[re,ie]=v.useState(!1),[I,L]=v.useState(0),[ae,oe]=v.useState(0),R=v.useRef(n.duration||b||aa),se=v.useRef(null),z=v.useRef(null),ce=c===0,B=c+1<=o,V=n.type,le=n.dismissible!==!1,ue=n.className||``,de=n.descriptionClassName||``,fe=v.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),pe=v.useMemo(()=>n.closeButton??p,[n.closeButton,p]),me=v.useMemo(()=>n.duration||b||aa,[n.duration,b]),he=v.useRef(0),ge=v.useRef(0),_e=v.useRef(0),ve=v.useRef(null),[ye,be]=x.split(`-`),xe=v.useMemo(()=>s.reduce((e,t,n)=>n>=fe?e:e+t.height,0),[s,fe]),Se=Yi(),Ce=n.invert||t,we=V===`loading`;ge.current=v.useMemo(()=>fe*S+xe,[fe,xe]),v.useEffect(()=>{R.current=me},[me]),v.useEffect(()=>{M(!0)},[]),v.useEffect(()=>{let e=z.current;if(e){let t=e.getBoundingClientRect().height;return oe(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),v.useLayoutEffect(()=>{if(!j)return;let e=z.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,oe(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[j,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let Te=v.useCallback(()=>{P(!0),L(ge.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},la)},[n,d,a,ge]);v.useEffect(()=>{if(n.promise&&V===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||Se?(()=>{if(_e.current<he.current){let e=new Date().getTime()-he.current;R.current-=e}_e.current=new Date().getTime()})():R.current!==1/0&&(he.current=new Date().getTime(),e=setTimeout(()=>{n.onAutoClose==null||n.onAutoClose.call(n,n),Te()},R.current)),()=>clearTimeout(e)},[u,i,n,V,Se,Te]),v.useEffect(()=>{n.delete&&(Te(),n.onDismiss==null||n.onDismiss.call(n,n))},[Te,n.delete]);function Ee(){return T?.loading?v.createElement(`div`,{className:ua(w?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":V===`loading`},T.loading):v.createElement(Ui,{className:ua(w?.loader,n?.classNames?.loader),visible:V===`loading`})}let De=n.icon||T?.[V]||Vi(V);return v.createElement(`li`,{tabIndex:0,ref:z,className:ua(_,ue,w?.toast,n?.classNames?.toast,w?.default,w?.[V],n?.classNames?.[V]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":j,"data-promise":!!n.promise,"data-swiped":re,"data-removed":N,"data-visible":B,"data-y-position":ye,"data-x-position":be,"data-index":c,"data-front":ce,"data-swiping":ee,"data-dismissible":le,"data-type":V,"data-invert":Ce,"data-swipe-out":te,"data-swipe-direction":k,"data-expanded":!!(u||C&&j),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${N?I:ge.current}px`,"--initial-height":C?`auto`:`${ae}px`,...m,...n.style},onDragEnd:()=>{F(!1),O(null),ve.current=null},onPointerDown:e=>{e.button!==2&&(we||!le||(se.current=new Date,L(ge.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(F(!0),ve.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(te||!le)return;ve.current=null;let e=Number(z.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(z.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-se.current?.getTime(),i=D===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=ca||a>.11){L(ge.current),n.onDismiss==null||n.onDismiss.call(n,n),A(D===`x`?e>0?`right`:`left`:t>0?`down`:`up`),Te(),ne(!0);return}else{var o,s;(o=z.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=z.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`)}ie(!1),F(!1),O(null)},onPointerMove:t=>{var n,r;if(!ve.current||!le||window.getSelection()?.toString().length>0)return;let i=t.clientY-ve.current.y,a=t.clientX-ve.current.x,o=e.swipeDirections??da(x);!D&&(Math.abs(a)>1||Math.abs(i)>1)&&O(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(D===`y`){if(o.includes(`top`)||o.includes(`bottom`))if(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)s.y=i;else{let e=i*c(i);s.y=Math.abs(e)<Math.abs(i)?e:i}}else if(D===`x`&&(o.includes(`left`)||o.includes(`right`)))if(o.includes(`left`)&&a<0||o.includes(`right`)&&a>0)s.x=a;else{let e=a*c(a);s.x=Math.abs(e)<Math.abs(a)?e:a}(Math.abs(s.x)>0||Math.abs(s.y)>0)&&ie(!0),(n=z.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=z.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},pe&&!n.jsx&&V!==`loading`?v.createElement(`button`,{"aria-label":E,"data-disabled":we,"data-close-button":!0,onClick:we||!le?()=>{}:()=>{Te(),n.onDismiss==null||n.onDismiss.call(n,n)},className:ua(w?.closeButton,n?.classNames?.closeButton)},T?.close??Ji):null,(V||n.icon||n.promise)&&n.icon!==null&&(T?.[V]!==null||n.icon)?v.createElement(`div`,{"data-icon":``,className:ua(w?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Ee():null,n.type===`loading`?null:De):null,v.createElement(`div`,{"data-content":``,className:ua(w?.content,n?.classNames?.content)},v.createElement(`div`,{"data-title":``,className:ua(w?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?v.createElement(`div`,{"data-description":``,className:ua(y,de,w?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),v.isValidElement(n.cancel)?n.cancel:n.cancel&&ta(n.cancel)?v.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{ta(n.cancel)&&le&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),Te())},className:ua(w?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,v.isValidElement(n.action)?n.action:n.action&&ta(n.action)?v.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{ta(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&Te())},className:ua(w?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function pa(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function ma(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?ia:ra;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var ha=v.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=na,toastOptions:g,dir:_=pa(),gap:y=sa,icons:b,containerAriaLabel:x=`Notifications`}=e,[S,C]=v.useState([]),w=v.useMemo(()=>n?S.filter(e=>e.toasterId===n):S.filter(e=>!e.toasterId),[S,n]),T=v.useMemo(()=>Array.from(new Set([i].concat(w.filter(e=>e.position).map(e=>e.position)))),[w,i]),[E,D]=v.useState([]),[O,k]=v.useState(!1),[A,j]=v.useState(!1),[M,N]=v.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),P=v.useRef(null),ee=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),F=v.useRef(null),te=v.useRef(!1),ne=v.useCallback(e=>{C(t=>(t.find(t=>t.id===e.id)?.delete||Zi.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return v.useEffect(()=>Zi.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{C(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{et.flushSync(()=>{C(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[S]),v.useEffect(()=>{if(d!==`system`){N(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?N(`dark`):N(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{N(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{N(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),v.useEffect(()=>{S.length<=1&&k(!1)},[S]),v.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;k(!0),(t=P.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===P.current||P.current?.contains(document.activeElement))&&k(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),v.useEffect(()=>{if(P.current)return()=>{F.current&&(F.current.focus({preventScroll:!0}),F.current=null,te.current=!1)}},[P.current]),v.createElement(`section`,{ref:t,"aria-label":`${x} ${ee}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},T.map((t,n)=>{let[i,a]=t.split(`-`);return w.length?v.createElement(`ol`,{key:t,dir:_===`auto`?pa():_,tabIndex:-1,ref:P,className:c,"data-sonner-toaster":!0,"data-sonner-theme":M,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${E[0]?.height||0}px`,"--width":`${oa}px`,"--gap":`${y}px`,...m,...ma(l,u)},onBlur:e=>{te.current&&!e.currentTarget.contains(e.relatedTarget)&&(te.current=!1,F.current&&=(F.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||te.current||(te.current=!0,F.current=e.relatedTarget)},onMouseEnter:()=>k(!0),onMouseMove:()=>k(!0),onMouseLeave:()=>{A||k(!1)},onDragEnd:()=>k(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||j(!0)},onPointerUp:()=>j(!1)},w.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>v.createElement(fa,{key:n.id,icons:b,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:A,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:ne,toasts:w.filter(e=>e.position==n.position),heights:E.filter(e=>e.position==n.position),setHeights:D,expandByDefault:o,gap:y,expanded:O,swipeDirections:e.swipeDirections}))):null}))}),ga=`__includes_scalar__`,_a=class{},va=class extends _a{constructor(e,t){super(),this.collection=e,this.alias=t,this.type=`collectionRef`}},ya=class extends _a{constructor(e,t){super(),this.query=e,this.alias=t,this.type=`queryRef`}},K=class extends _a{constructor(e){super(),this.path=e,this.type=`ref`}},ba=class extends _a{constructor(e){super(),this.value=e,this.type=`val`}},xa=class extends _a{constructor(e,t){super(),this.name=e,this.args=t,this.type=`func`}},Sa=class extends _a{constructor(e,t){super(),this.name=e,this.args=t,this.type=`agg`}},Ca=class extends _a{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`}};function wa(e){return e instanceof Sa||e instanceof xa||e instanceof K||e instanceof ba||e instanceof Ca}function Ta(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Ea(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Da(e){return typeof e==`object`&&`expression`in e&&e.residual===!0}function Oa(e){return{expression:e,residual:!0}}function ka(e,t){if(e.from.alias===t)return e.from;for(let n of e.join||[])if(n.from.alias===t)return n.from}function Aa(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 Aa(e,t,n)}return{collection:n,path:[r]}}if(t.path.length>1){let[r,...i]=t.path,a=ka(e,r);return a?a.type===`queryRef`?Aa(a.query,new K(i),n):{collection:a.collection,path:i}:void 0}}}var ja=class extends Error{constructor(e){super(e),this.name=`TanStackDBError`}},Ma=class extends ja{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}},Na=class extends ja{constructor(e){super(e),this.name=`CollectionConfigurationError`}},Pa=class extends Na{constructor(){super(`Collection requires a config`)}},Fa=class extends Na{constructor(){super(`Collection requires a sync config`)}},Ia=class extends Na{constructor(){super(`Schema must implement the standard-schema interface`)}},La=class extends Na{constructor(){super(`Schema validation must be synchronous`)}},Ra=class extends ja{constructor(e){super(e),this.name=`CollectionStateError`}},za=class extends Ra{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}},Ba=class extends Ra{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}},Va=class extends Ra{constructor(){super(`Collection is in error state`)}},Ha=class extends Ra{constructor(){super(`Active subscribers count is negative - this should never happen`)}},Ua=class extends ja{constructor(e){super(e),this.name=`CollectionOperationError`}},Wa=class extends Ua{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}},Ga=class extends Ua{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)}`)}},Ka=class extends Ua{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}},qa=class extends Ua{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)}},Ja=class extends Ua{constructor(){super(`The first argument to update is missing`)}},Ya=class extends Ua{constructor(){super(`No keys were passed to update`)}},Xa=class extends Ua{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}},Za=class extends Ua{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.`)}},Qa=class extends Ua{constructor(){super(`No keys were passed to delete`)}},$a=class extends Ua{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}},eo=class extends ja{constructor(e){super(e),this.name=`MissingHandlerError`}},to=class extends eo{constructor(){super(`Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.`)}},no=class extends eo{constructor(){super(`Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.`)}},ro=class extends eo{constructor(){super(`Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.`)}},io=class extends ja{constructor(e){super(e),this.name=`TransactionError`}},ao=class extends io{constructor(){super(`mutationFn is required when creating a transaction`)}},oo=class extends io{constructor(){super(`You can no longer call .mutate() as the transaction is no longer pending`)}},so=class extends io{constructor(){super(`You can no longer call .rollback() as the transaction is already completed`)}},co=class extends io{constructor(){super(`You can no longer call .commit() as the transaction is no longer pending`)}},lo=class extends io{constructor(){super(`No pending sync transaction to write to`)}},uo=class extends io{constructor(){super(`The pending sync transaction is already committed, you can't still write to it.`)}},fo=class extends io{constructor(){super(`No pending sync transaction to commit`)}},po=class extends io{constructor(){super(`The pending sync transaction is already committed, you can't commit it again.`)}},mo=class extends ja{constructor(e){super(e),this.name=`QueryBuilderError`}},ho=class extends mo{constructor(e){super(`Only one source is allowed in the ${e}`)}},go=class extends mo{constructor(e){super(`A sub query passed to a ${e} must have a from clause itself`)}},_o=class extends mo{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.`)}},vo=class extends mo{constructor(e,t){super(`Invalid source for ${e}: Expected an object with a single key-value pair like { alias: collection }. For example: .from({ todos: todosCollection }). Got: ${t}`)}},yo=class extends mo{constructor(){super(`Join condition must be an equality expression`)}},bo=class extends mo{constructor(){super(`Query must have a from clause`)}},xo=class extends mo{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`)}},So=class extends ja{constructor(e){super(e),this.name=`QueryCompilationError`}},Co=class extends So{constructor(){super(`DISTINCT requires a SELECT clause.`)}},wo=class extends So{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().`)}},To=class extends So{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(...)).`)}},Eo=class extends So{constructor(){super(`HAVING clause requires GROUP BY clause`)}},Do=class extends So{constructor(){super(`LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results`)}},Oo=class extends So{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}`)}},ko=class extends So{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.`)}},Ao=class extends So{constructor(e){super(`Unsupported FROM type: ${e}`)}},jo=class extends So{constructor(e){super(`Unknown expression type: ${e}`)}},Mo=class extends So{constructor(){super(`Reference path cannot be empty`)}},No=class extends So{constructor(e){super(`Unknown function: ${e}`)}},Po=class extends So{constructor(e){super(`Collection "${e}" not found during compilation of join`)}},Fo=class extends ja{constructor(e){super(e),this.name=`JoinError`}},Io=class extends Fo{constructor(e){super(`Unsupported join type: ${e}`)}},Lo=class extends Fo{constructor(e){super(`Invalid join condition: both expressions refer to the same source "${e}"`)}},Ro=class extends Fo{constructor(){super(`Invalid join condition: expressions must reference source aliases`)}},zo=class extends Fo{constructor(e){super(`Invalid join condition: left expression refers to an unavailable source "${e}"`)}},Bo=class extends Fo{constructor(e){super(`Invalid join condition: right expression does not refer to the joined source "${e}"`)}},Vo=class extends Fo{constructor(){super(`Invalid join condition`)}},Ho=class extends Fo{constructor(e){super(`Unsupported join source type: ${e}`)}},Uo=class extends ja{constructor(e){super(e),this.name=`GroupByError`}},Wo=class extends Uo{constructor(e){super(`Non-aggregate expression '${e}' in SELECT must also appear in GROUP BY clause`)}},Go=class extends Uo{constructor(e){super(`Unsupported aggregate function: ${e}`)}},Ko=class extends Uo{constructor(e){super(`Aggregate function in HAVING clause must also be in SELECT clause: ${e}`)}},qo=class extends Uo{constructor(e){super(`Unknown expression type in HAVING clause: ${e}`)}},Jo=class extends ja{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`}},Yo=class extends ja{constructor(e){super(e),this.name=`QueryOptimizerError`}},Xo=class extends Yo{constructor(){super(`Cannot combine empty expression list`)}},Zo=class extends So{constructor(e,t,n,r){super(`Internal error: subscription for alias '${e}' (remapped from '${t}', collection '${n}') is missing in join pipeline. Available aliases: ${r.join(`, `)}. This indicates a bug in alias tracking.`)}},Qo=class extends So{constructor(e){super(`Internal error: compiler returned aliases without inputs: ${e.join(`, `)}. This indicates a bug in query compilation. Please report this issue.`)}},$o=class extends So{constructor(){super(`setWindow() can only be called on collections with an ORDER BY clause. Add .orderBy() to your query to enable window movement.`)}};function es(e,t){return ts(e,t,new Map)}function ts(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():!1;if(t instanceof Date)return!1;if(e instanceof RegExp)return t instanceof RegExp?e.source===t.source&&e.flags===t.flags:!1;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)&&ts(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(rs(e)&&rs(t))return e[Symbol.toStringTag]===t[Symbol.toStringTag]?typeof e.equals==`function`?e.equals(t):e.toString()===t.toString():!1;if(rs(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)=>ts(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&&ts(e[r],t[r],n));return n.delete(e),a}return!1}var ns=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function rs(e){if(typeof e!=`object`||!e)return!1;let t=e[Symbol.toStringTag];return typeof t==`string`&&ns.has(t)}var is={direction:`asc`,nulls:`first`,stringSort:`locale`},as=new WeakMap,os=1;function ss(e){if(as.has(e))return as.get(e);let t=os++;return as.set(e,t),t}var cs=(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;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=cs(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(rs(e)&&rs(t)){let n=e.toString(),r=t.toString();return n<r?-1:+(n>r)}let i=typeof e==`object`,a=typeof t==`object`;if(i||a){if(i&&a)return ss(e)-ss(t);if(i)return 1;if(a)return-1}return e<t?-1:+(e>t)},ls=(e,t,n)=>cs(t,e,{...n,nulls:n.nulls===`first`?`last`:`first`});function us(e){return(t,n)=>e.direction===`asc`?cs(t,n,e):ls(t,n,e)}var ds=us({direction:`asc`,nulls:`first`,stringSort:`locale`});function fs(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 ps=128;function ms(e){return e instanceof Date?e.getTime():rs(e)?`__temporal__${e[Symbol.toStringTag]}__${e.toString()}`:(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)&&e.byteLength<=ps?`__u8__${Array.from(e).join(`,`)}`:e}function hs(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?fs(e,t):!1}function q(e){return e==null}function gs(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 _s(e,t){return e===`%Y-%m-%d`?t.toISOString().slice(0,10):t.toISOString()}function vs(e){return e===!0}function J(e,t=!1){return bs(e,t)}function ys(e){return bs(e,!0)}function bs(e,t){switch(e.type){case`val`:{let t=e.value;return()=>t}case`ref`:return t?Ss(e):xs(e);case`func`:return Cs(e,t);default:throw new jo(e.type)}}function xs(e){let[t,...n]=e.path;if(!t)throw new Mo;if(t===`$selected`){if(n.length===0)return e=>e.$selected;if(n.length===1){let e=n[0];return t=>t.$selected?.[e]}else 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]}else 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 Ss(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 Cs(e,t){let n=e.args.map(e=>bs(e,t));switch(e.name){case`eq`:{let e=n[0],t=n[1];return n=>{let r=ms(e(n)),i=ms(t(n));return q(r)||q(i)?null:hs(r,i)}}case`gt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:r>i}}case`gte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:r>=i}}case`lt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:r<i}}case`lte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:r<=i}}case`and`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!1)return!1;q(n)&&(t=!0)}return t?null:!0};case`or`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!0)return!0;q(n)&&(t=!0)}return t?null:!1};case`not`:{let e=n[0];return t=>{let n=e(t);return q(n)?null:!n}}case`in`:{let e=n[0],t=n[1];return n=>{let r=ms(e(n)),i=t(n);return q(r)?null:Array.isArray(i)?i.some(e=>ms(e)===r):!1}}case`like`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:ws(r,i,!1)}}case`ilike`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:ws(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`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=gs(e(t));return n?n.toISOString().slice(0,10):null}}case`datetime`:{let e=n[0];return t=>{let n=gs(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=gs(t(n));return i?_s(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 No(e.name)}}function ws(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 Ts=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)}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 Es(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 Ds=[`$synced`,`$origin`,`$key`,`$collectionId`];function Os(e){return Ds.includes(e)}function ks(e){return e.some(e=>Os(e))}function As(e,t,n){if(ks(t))return;let r=n??{...is,...e.compareOptions};for(let n of e.indexes.values())if(n.matchesField(t)&&n.matchesCompareOptions(r))return n.matchesDirection(r.direction)?n:new Ts(n)}function js(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 Ms(e){let t=new Set;for(let n of e)for(let e of n)t.add(e);return t}function Ns(e,t){return Ps(e,t)}function Ps(e,t){if(e.type===`func`)switch(e.name){case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:return Is(e,t);case`and`:return Ls(e,t);case`or`:return Rs(e,t);case`in`:return zs(e,t)}return{canOptimize:!1,matchingKeys:new Set}}function Fs(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set};let n=new Map;for(let t of e.args)if(t.type===`func`&&[`gt`,`gte`,`lt`,`lte`].includes(t.name)){let e=t;if(e.args.length===2){let t=e.args[0],r=e.args[1],i=null,a=null,o=e.name;if(t.type===`ref`&&r.type===`val`)i=t,a=r;else if(t.type===`val`&&r.type===`ref`)switch(i=r,a=t,o){case`gt`:o=`lt`;break;case`gte`:o=`lte`;break;case`lt`:o=`gt`;break;case`lte`:o=`gte`;break}if(i&&a){let e=i.path.join(`.`),t=a.value;n.has(e)||n.set(e,[]),n.get(e).push({operation:o,value:t})}}}for(let[e,r]of n)if(r.length>=2){let n=As(t,e.split(`.`));if(n&&n.supports(`gt`)&&n.supports(`lt`)){let e,t,i=!0,a=!0;for(let{operation:n,value:o}of r)switch(n){case`gt`:(e===void 0||o>e)&&(e=o,i=!1);break;case`gte`:(e===void 0||o>e)&&(e=o,i=!0);break;case`lt`:(t===void 0||o<t)&&(t=o,a=!1);break;case`lte`:(t===void 0||o<t)&&(t=o,a=!0);break}return{canOptimize:!0,matchingKeys:n.rangeQuery({from:e,to:t,fromInclusive:i,toInclusive:a})}}}return{canOptimize:!1,matchingKeys:new Set}}function Is(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};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`;break}if(i&&a){let e=i.path,n=As(t,e);if(n){let e=a.value,t=o;return n.supports(t)?{canOptimize:!0,matchingKeys:n.lookup(t,e)}:{canOptimize:!1,matchingKeys:new Set}}}return{canOptimize:!1,matchingKeys:new Set}}function Ls(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set};let n=Fs(e,t);if(n.canOptimize)return n;let r=[];for(let n of e.args){let e=Ps(n,t);e.canOptimize&&r.push(e)}return r.length>0?{canOptimize:!0,matchingKeys:js(r.map(e=>e.matchingKeys))}:{canOptimize:!1,matchingKeys:new Set}}function Rs(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set};let n=[];for(let r of e.args){let e=Ps(r,t);e.canOptimize&&n.push(e)}return n.length>0?{canOptimize:!0,matchingKeys:Ms(n.map(e=>e.matchingKeys))}:{canOptimize:!1,matchingKeys:new Set}}function zs(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};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=As(t,e);if(a){if(a.supports(`in`))return{canOptimize:!0,matchingKeys:a.lookup(`in`,i)};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}}}}return{canOptimize:!1,matchingKeys:new Set}}var Bs={enabled:!0,collectionSizeThreshold:1e3,slowQueryThresholdMs:10,onSuggestion:null};function Vs(){return Bs.enabled&&!1}function Hs(e){if(Vs())if(Bs.onSuggestion)try{Bs.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 Us(e,t,n){Vs()&&t>Bs.collectionSizeThreshold&&Hs({type:`collection-size`,collectionId:e,fieldPath:n,message:`Collection has ${t} items. Queries on "${n.join(`.`)}" may benefit from an index.`,collectionSize:t})}function Ws(e){return e.config.autoIndex===`eager`}function Gs(e,t,n,r,i){if(ks(t)||!Ws(n))return;let a=r??{...is,...n.compareOptions};if(!Array.from(n.indexes.values()).find(e=>e.matchesField(t)&&e.matchesCompareOptions(a))){Vs()&&Us(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 Ks(e,t){if(!Ws(t))return;let n=qs(e);for(let{fieldName:e,fieldPath:r}of n)Gs(e,r,t)}function qs(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 Js=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}},Ys=3e4;function Xs(e,t){if(t.length<=Ys)e.push(...t);else for(let n=0;n<t.length;n+=Ys){let r=t.slice(n,n+Ys);e.push(...r)}}function Zs(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 Qs=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 $s(e,t){let[n,r]=e,[i,a]=t;return{onlyInA:[...ec(n,Math.min(r,i)),...ec(Math.max(n,a),r)],onlyInB:[...ec(i,Math.min(a,n)),...ec(Math.max(i,r),a)]}}function ec(e,t){let n=[];for(let r=e;r<t;r++)n.push(r);return n}function tc(e,t){return typeof e==typeof t?e<t?-1:+(e>t):typeof e==`string`?-1:1}function nc(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t instanceof Date?t.toISOString():t)}var rc=Y(),ic=Y(),ac=Y(),oc=Y(),sc=Y();function Y(){return Math.random()*(2**31-1)>>>0}var cc=new ArrayBuffer(8),lc=new DataView(cc),uc=new Uint8Array(cc),dc=class{constructor(){this.hash=rc,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(sc);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(ic);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`:lc.setFloat64(0,e,!0),this.writeByte(uc[0]),this.writeByte(uc[1]),this.writeByte(uc[2]),this.writeByte(uc[3]),this.writeByte(uc[4]),this.writeByte(uc[5]),this.writeByte(uc[6]),this.writeByte(uc[7]);return;case`bigint`:{let t=e;for(t<0n?(t=-t,this.update(oc)):this.update(ac);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}},fc=Y(),pc=Y(),mc=Y(),hc=Y(),gc=Y(),_c=Y(),vc=Y(),yc=Y(),bc=Y(),xc=Y(),Sc=Y(),Cc=Y(),wc=Y(),Tc=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function Ec(e){let t=e[Symbol.toStringTag];return typeof t==`string`&&Tc.has(t)}var Dc=128,Oc=new WeakMap;function kc(e){let t=new dc;return Fc(t,e),t.digest()}function Ac(e){let t=Oc.get(e);if(t!==void 0)return t;let n;if(e instanceof Date)n=jc(e);else if(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)if(e.byteLength<=Dc)n=Mc(e);else return Rc(e);else if(e instanceof File)return Rc(e);else if(Ec(e))n=Nc(e);else{let t=e,r=yc;e instanceof Array&&(r=bc),e instanceof Map&&(r=xc,t=[...e.entries()]),e instanceof Set&&(r=Sc,t=[...e.entries()]),n=Pc(t,r)}return Oc.set(e,n),n}function jc(e){let t=new dc;return t.update(vc),t.update(e.getTime()),t.digest()}function Mc(e){let t=new dc;t.update(Cc),t.update(e.byteLength);for(let n=0;n<e.byteLength;n++)t.writeByte(e[n]);return t.digest()}function Nc(e){let t=new dc;return t.update(wc),t.update(e[Symbol.toStringTag]),t.update(e.toString()),t.digest()}function Pc(e,t){let n=new dc;n.update(t);let r=Object.keys(e);r.sort(zc);for(let t of r)n.update(gc),n.update(t),Fc(n,e[t]);return n.digest()}function Fc(e,t){if(t===null){e.update(mc);return}switch(typeof t){case`undefined`:e.update(hc);return;case`boolean`:e.update(t?fc:pc);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(Ic(t));return;case`function`:e.update(Rc(t));return;default:console.warn(`Ignored input during hashing because it is of type ${typeof t} which is not supported`)}}function Ic(e){let t=Oc.get(e);return t===void 0&&(t=Ac(e)),t}var Lc=1;function Rc(e){let t=Oc.get(e);return t===void 0&&(t=Lc^_c,Lc++,Oc.set(e,t)),t}function zc(e,t){return e.localeCompare(t)}var Bc=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 Xs(n,this.#e),Xs(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`${Qs.getStringId(t)}|${Qs.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):Qs.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 Js(()=>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?kc(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;Xs(this.#e,n)}add(e,t){t!==0&&this.#e.push([e,t])}getInner(){return this.#e}},Vc=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}},Hc=class{#e=[];sendData(e){e instanceof Bc||(e=new Bc(e));for(let t of this.#e)t.unshift(e)}newReader(){let e=[];return this.#e.push(e),new Vc(e)}},Uc=class{constructor(e,t,n){this.id=e,this.inputs=t,this.output=n}hasPendingWork(){return this.inputs.some(e=>!e.isEmpty())}},Wc=class extends Uc{constructor(e,t,n){super(e,[t],n),this.id=e}inputMessages(){return this.inputs[0].drain()}},Gc=class extends Uc{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()}},Kc=class extends Wc{run(){for(let e of this.inputMessages())this.output.sendData(this.inner(e))}},qc=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 Hc;return new Yc(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()}},Jc=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)}},Yc=class extends Jc{sendData(e){this.writer.sendData(e)}},Xc=class extends Wc{run(){let e=this.inputMessages();if(e.length===0)return;let t=new Bc;for(let n of e)t.extend(n);let n=t.consolidate();n.getInner().length>0&&this.output.sendData(n)}};function Zc(){return e=>{let t=new Jc(e.graph,new Hc),n=new Xc(e.graph.getNextOperatorId(),e.connectReader(),t.writer);return e.graph.addOperator(n),t}}var Qc=Symbol(`NO_PREFIX`),$c=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=nl(e),r=this.get(n);if(rl(r)){let[i,a]=r;if(nl(i)!==n)throw Error(`Mismatching prefixes, this should never happen`);if(i===e||kc(i)===kc(e)){let r=a+t;r===0?this.delete(n):this.set(n,[e,r])}else{let a=new el;a.set(kc(i),r),a.set(kc(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}},el=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=kc(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}},tl=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(rl(t))yield t;else if(t===void 0)return;else if(t instanceof el)for(let e of t.values())yield e;else for(let e of t.values())if(rl(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(rl(a)){this.#n(e,a,n,r);return}if(a instanceof el){let i=nl(n);if(i!==Qc){let n=new $c;n.set(Qc,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=nl(n),s=nl(i);if(s===o&&(i===n||kc(i)===kc(n))){let t=a+r;t===0?this.#e.delete(e):this.#e.set(e,[n,t]);return}if(s===Qc&&o===Qc){let a=new el;a.set(kc(i),t),a.set(kc(n),[n,r]),this.#e.set(e,a)}else{let a=new $c;if(s===o){let e=new el;e.set(kc(i),t),e.set(kc(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 Bc(t)}};function nl(e){return Array.isArray(e)&&(typeof e[0]==`string`||typeof e[0]==`number`||typeof e[0]==`bigint`)?e[0]:Qc}function rl(e){return Array.isArray(e)}var il=class extends Wc{#e=new tl;#t=new tl;#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 Bc(t))}};function al(e){return t=>{let n=new Jc(t.graph,new Hc),r=new il(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var ol=class extends Wc{#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=kc(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([[kc(this.#e(i)),i[1]],1]):e>0&&r<=0&&t.push([[kc(this.#e(i)),i[1]],-1])}t.length>0&&this.output.sendData(new Bc(t))}};function sl(e=e=>e){return t=>{let n=new Jc(t.graph,new Hc),r=new ol(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var cl=class extends Kc{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.filter(this.#e)}};function ll(e){return t=>{let n=new Jc(t.graph,new Hc),r=new cl(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var ul=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`;function dl(e,t,n){let r=n[0];if(t!=null&&e>=t)throw Error(e+` >= `+t);if(e.slice(-1)===r||t&&t.slice(-1)===r)throw Error(`trailing zero`);if(t){let i=0;for(;(e[i]||r)===t[i];)i++;if(i>0)return t.slice(0,i)+dl(e.slice(i),t.slice(i),n)}let i=e?n.indexOf(e[0]):0,a=t==null?n.length:n.indexOf(t[0]);return a-i>1?n[Math.round(.5*(i+a))]:t&&t.length>1?t.slice(0,1):n[i]+dl(e.slice(1),null,n)}function fl(e){if(e.length!==pl(e[0]))throw Error(`invalid integer part of order key: `+e)}function pl(e){if(e>=`a`&&e<=`z`)return e.charCodeAt(0)-97+2;if(e>=`A`&&e<=`Z`)return 90-e.charCodeAt(0)+2;throw Error(`invalid order key head: `+e)}function ml(e){let t=pl(e[0]);if(t>e.length)throw Error(`invalid order key: `+e);return e.slice(0,t)}function hl(e,t){if(e===`A`+t[0].repeat(26))throw Error(`invalid order key: `+e);let n=ml(e);if(e.slice(n.length).slice(-1)===t[0])throw Error(`invalid order key: `+e)}function gl(e,t){fl(e);let[n,...r]=e.split(``),i=!0;for(let e=r.length-1;i&&e>=0;e--){let n=t.indexOf(r[e])+1;n===t.length?r[e]=t[0]:(r[e]=t[n],i=!1)}if(i){if(n===`Z`)return`a`+t[0];if(n===`z`)return null;let e=String.fromCharCode(n.charCodeAt(0)+1);return e>`a`?r.push(t[0]):r.pop(),e+r.join(``)}else return n+r.join(``)}function _l(e,t){fl(e);let[n,...r]=e.split(``),i=!0;for(let e=r.length-1;i&&e>=0;e--){let n=t.indexOf(r[e])-1;n===-1?r[e]=t.slice(-1):(r[e]=t[n],i=!1)}if(i){if(n===`a`)return`Z`+t.slice(-1);if(n===`A`)return null;let e=String.fromCharCode(n.charCodeAt(0)-1);return e<`Z`?r.push(t.slice(-1)):r.pop(),e+r.join(``)}else return n+r.join(``)}function vl(e,t,n=ul){if(e!=null&&hl(e,n),t!=null&&hl(t,n),e!=null&&t!=null&&e>=t)throw Error(e+` >= `+t);if(e==null){if(t==null)return`a`+n[0];let e=ml(t),r=t.slice(e.length);if(e===`A`+n[0].repeat(26))return e+dl(``,r,n);if(e<t)return e;let i=_l(e,n);if(i==null)throw Error(`cannot decrement any more`);return i}if(t==null){let t=ml(e),r=e.slice(t.length);return gl(t,n)??t+dl(r,null,n)}let r=ml(e),i=e.slice(r.length),a=ml(t),o=t.slice(a.length);if(r===a)return r+dl(i,o,n);let s=gl(r,n);if(s==null)throw Error(`cannot increment any more`);return s<t?s:r+dl(i,null,n)}function yl(e,t){return[e,t]}function bl(e){return e[0]}function xl(e){return e[1]}function Sl(e){return([t,n],[r,i])=>{let a=e(n,i);return a===0?tc(t,r):a}}var Cl=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}=$s(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=yl(e,vl(n===0?null:xl(this.#e[n-1]),n===this.#e.length?null:xl(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;e<this.#e.length?t.moveOut=this.#e[e]:t.moveOut=null}let e=this.#r-1;e<this.#e.length&&(t.moveIn=this.#e[e])}return t}#i(e){return Zs(this.#e,yl(e,``),(e,t)=>this.#t(bl(e),bl(t)))}},wl=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 Cl))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 Tl(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],1])}}function El(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],-1])}}var Dl=class extends Wc{#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=Sl(r),i.setSizeCallback?.(()=>this.#a()),i.setWindowFn?.(this.#c.bind(this))}createTopK(e,t,n){return new Cl(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 wl(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=>Tl(e,n)),t.moveOuts.forEach(e=>El(e,n)),t.changes&&(r=!0)}r&&this.output.sendData(new Bc(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 Bc(e))}#l(e,t,n,r){let i=this.#t(e,t),a=this.#o(i),o=a.processElement(e,t,n);Tl(o.moveIn,r),El(o.moveOut,r),this.#s(i,a)}};function Ol(e,t){return n=>{let r=new Jc(n.graph,new Hc),i=new Dl(n.graph.getNextOperatorId(),n.connectReader(),r.writer,e,t);return n.graph.addOperator(i),r}}var kl=class extends Gc{#e=new tl;#t=new tl;#n;constructor(e,t,n,r,i=`inner`){super(e,t,n,r),this.#n=i}run(){let e=tl.fromMultiSets(this.inputAMessages()),t=tl.fromMultiSets(this.inputBMessages());if(e.size===0&&t.size===0)return;let n=new Bc;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 Al(e,t=`inner`){return n=>{if(n.graph!==e.graph)throw Error(`Cannot join streams from different graphs`);let r=new Jc(n.graph,new Hc),i=new kl(n.graph.getNextOperatorId(),n.connectReader(),e.connectReader(),r.writer,t);return n.graph.addOperator(i),r}}var jl=class extends Kc{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.map(this.#e)}};function X(e){return t=>{let n=new Jc(t.graph,new Hc),r=new jl(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Ml=class extends Wc{#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 Nl(e){return t=>{let n=new Jc(t.graph,new Hc),r=new Ml(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Pl=class extends Kc{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return this.#e(e),e}};function Fl(e){return t=>{let n=new Jc(t.graph,new Hc),r=new Pl(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Il=class extends Wc{#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,Sl(r));this.#e=new wl(s),i.setSizeCallback?.(()=>this.#e.size),i.setWindowFn?.(this.moveTopK.bind(this))}createTopK(e,t,n){return new Cl(e,t,n)}moveTopK({offset:e,limit:t}){let n=[],r=this.#e.move({offset:e,limit:t});r.moveIns.forEach(e=>Tl(e,n)),r.moveOuts.forEach(e=>El(e,n)),r.changes&&this.output.sendData(new Bc(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 Bc(e))}processElement(e,t,n,r){let i=this.#e.processElement(e,t,n);Tl(i.moveIn,r),El(i.moveOut,r)}};function Ll(e,t){let n=t||{};return t=>{let r=new Jc(t.graph,new Hc),i=new Il(t.graph.getNextOperatorId(),t.connectReader(),r.writer,e,n);return t.graph.addOperator(i),r}}function Rl(e){return`pipe`in e}function zl(e,t={}){let n=Object.fromEntries(Object.entries(t).filter(([e,t])=>!Rl(t)));return Object.fromEntries(Object.entries(t).filter(([e,t])=>Rl(t))),t=>{let r=`__original_key__`;return t.pipe(X(t=>{let i=e(t),a=nc(i),o={};o[r]=i;for(let[e,r]of Object.entries(n))o[e]=r.preMap(t);return[a,o]})).pipe(al(e=>{let t=0;for(let[n,r]of e)t+=r;if(t<=0)return[];let i={};i[r]=e[0]?.[0]?.[r];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(X(([e,t])=>{let i=t[r],a={};Object.assign(a,i);for(let[e,r]of Object.entries(n))r.postMap?a[e]=r.postMap(t[e]):a[e]=t[e];return[e,a]}))}}function Bl(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 Vl(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 Hl(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 Ul(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 Wl(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 Gl(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 Kl(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 ql={sum:Bl,count:Vl,avg:Hl,min:Ul,max:Wl,median:Gl,mode:Kl};function Jl(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(Ol((t,n)=>s(e(t),e(n)),{limit:n,offset:r,setSizeCallback:i,setWindowFn:a,groupKeyFn:o}),Zc())}function Yl(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}),Zc())}function Xl(e,t){return Yl(Ll,e,t)}var Zl=`__virtual_synced__`,Ql=`__virtual_has_local__`;function $l(e){let t=!1,n=!0,r=!1;for(let[i,a]of Object.entries(e)){if(i===`$selected`)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:!0,hasLocal:r}}var{sum:eu,count:tu,avg:nu,min:ru,max:iu}=ql;function au(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`||du(i))continue;let t=r.findIndex(e=>su(i,e));if(t===-1)throw new Wo(e);n.set(e,t)}return{selectToGroupByIndex:n,groupByExpressions:r}}function ou(e,t,n,r,i,a,o){let s={[Zl]:{preMap:([,e])=>$l(e).synced,reduce:e=>{for(let[t,n]of e)if(!t&&n>0)return!1;return!0}},[Ql]:{preMap:([,e])=>$l(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]=cu(n);else if(du(n)){let{transformed:r,extracted:i}=fu(n,l);for(let[e,n]of Object.entries(i))t[e]=cu(n);c[e]=J(r)}}let u=o?([,e])=>({__singleGroup:!0,__correlationKey:e?.[o]?.__correlationKey}):()=>({__singleGroup:!0});if(e=e.pipe(zl(u,t)),e=e.pipe(X(([,e])=>{let t={...e.$selected||{}};if(r){for(let[n,i]of Object.entries(r))i.type===`agg`&&(t[n]=e[n]);uu(t,e,c)}let n=o?e.__correlationKey:void 0,i=n===void 0?`single_group`:`single_group_${nc(n)}`,s={...e,$selected:t},l=e[Zl],u=e[Ql];return s.$synced=l??!0,s.$origin=u?`local`:`remote`,s.$key=i,s.$collectionId=a??s.$collectionId,o&&n!==void 0&&(s[o]={__correlationKey:n}),[i,s]})),n&&n.length>0)for(let t of n){let n=J(lu(Ea(t),r||{},`$selected`));e=e.pipe(ll(([,e])=>vs(n({$selected:e.$selected}))))}if(i&&i.length>0)for(let t of i)e=e.pipe(ll(([,e])=>vs(t({$selected:e.$selected}))));return e}let c=au(t,r),l=t.map(e=>J(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&&(r.__correlationKey=e?.[o]?.__correlationKey),r},d=s,f={},p={value:0};if(r){for(let[e,t]of Object.entries(r))if(t.type===`agg`)d[e]=cu(t);else if(du(t)){let{transformed:n,extracted:r}=fu(t,p);for(let[e,t]of Object.entries(r))d[e]=cu(t);f[e]=J(n)}}if(e=e.pipe(zl(u,d)),e=e.pipe(X(([,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);r===void 0?i[t]=n[t]:i[t]=e[`__key_${r}`]}uu(i,e,f)}else for(let n=0;n<t.length;n++)i[`__key_${n}`]=e[`__key_${n}`];let s=o?e.__correlationKey:void 0,l=[];for(let n=0;n<t.length;n++)l.push(e[`__key_${n}`]);s!==void 0&&l.push(s);let u=l.length===1?l[0]:nc(l),d={...e,$selected:i},p=e[Zl],m=e[Ql];return d.$synced=p??!0,d.$origin=m?`local`:`remote`,d.$key=u,d.$collectionId=a??d.$collectionId,o&&s!==void 0&&(d[o]={__correlationKey:s}),[u,d]})),n&&n.length>0)for(let t of n){let n=J(lu(Ea(t),r||{}));e=e.pipe(ll(([,e])=>n({$selected:e.$selected})))}if(i&&i.length>0)for(let t of i)e=e.pipe(ll(([,e])=>vs(t({$selected:e.$selected}))));return e}function su(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)=>su(e,t.args[n]));case`agg`:return e.name===t.name&&e.args?.length===t.args?.length&&(e.args||[]).every((e,n)=>su(e,t.args[n]));default:return!1}}function cu(e){let t=J(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 eu(n);case`count`:return tu(i);case`avg`:return nu(n);case`min`:return ru(r);case`max`:return iu(r);default:throw new Go(e.name)}}function lu(e,t,n=`$selected`){switch(e.type){case`agg`:{let r=e;for(let[e,i]of Object.entries(t))if(i.type===`agg`&&pu(r,i))return new K([n,e]);throw new Ko(r.name)}case`func`:{let n=e,r=n.args.map(e=>lu(e,t));return new xa(n.name,r)}case`ref`:return e;case`val`:return e;default:throw new qo(e.type)}}function uu(e,t,n){for(let n of Object.keys(t))n.startsWith(`__agg_`)&&(e[n]=t[n]);for(let[t,r]of Object.entries(n))e[t]=r({$selected:e});for(let t of Object.keys(e))t.startsWith(`__agg_`)&&delete e[t]}function du(e){return wa(e)?e.type===`agg`?!0:e.type===`func`&&`args`in e?e.args.some(e=>du(e)):!1:!1}function fu(e,t){if(e.type===`agg`){let n=`__agg_${t.value++}`;return{transformed:new K([`$selected`,n]),extracted:{[n]:e}}}if(e.type===`func`){let n={},r=e.args.map(e=>{let r=fu(e,t);return Object.assign(n,r.extracted),r.transformed});return{transformed:new xa(e.name,r),extracted:n}}return{transformed:e,extracted:{}}}function pu(e,t){return e.name===t.name&&e.args.length===t.args.length&&e.args.every((e,n)=>su(e,t.args[n]))}function mu(e,t,n,r,i,a,o,s,c,l){let u=n.map(e=>({compiledExpression:J(lu(e.expression,r,`$selected`)),compareOptions:hu(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=us(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 us(n.compareOptions)(e,t)}return ds(e,t)},p,m;if(s&&!l){let t,r,o,l=e.from.alias,u=n[0],d=u.expression;if(d.type===`ref`){let n=Aa(e,d,i);if(n){r=n.collection;let i=n.path[0],a=hu(u,r);if(i){let e=us(a);Gs(i,n.path,r,a,e)}if(o=J(new K(n.path),!0),t=As(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=d.path.length>1?String(d.path[0]):e.from.alias}}if(o){let u=n.every(e=>e.expression.type===`ref`)?n.map(t=>{let n=t.expression,r=Aa(e,n,i);return J(r?new K(r.path):t.expression,!0)}):void 0;m={alias:l,offset:c??0,limit:s,comparator:(e,t)=>{if(n.length===1)return f(e&&o(e),t&&o(t));if(u){let n=e=>e&&u.map(t=>t(e));return f(n(e),n(t))}return 0},valueExtractorForRawRow:e=>{if(n.length===1)return o(e);if(u)return u.map(t=>t(e))},firstColumnValueExtractor:o,index:t,orderBy:n};let d=r?.id??i.id;a[d]=m,t&&(p=e=>{a[d].dataNeeded=()=>{let t=e();return Math.max(0,m.limit-t)}})}}return l?t.pipe(Jl(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(Xl(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 hu(e,t){return e.compareOptions.stringSort===void 0?{...t.compareOptions,direction:e.compareOptions.direction,nulls:e.compareOptions.nulls}:e.compareOptions}function gu(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?_u(t.where):void 0,r=yu(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=Ns(r,e);if(i.canOptimize){let t=[];for(let n of i.matchingKeys){let r=e.get(n);r!==void 0&&t.push({type:`insert`,key:n,value:r})}return t}else return t.optimizedOnly?void 0:n(_u(r))}catch(r){console.warn(`${e.id?`[${e.id}] `:``}Error processing where clause, falling back to full scan:`,r);let i=_u(t.where);return t.optimizedOnly?void 0:n(i)}}function _u(e){let t=ys(e);return e=>{try{return vs(t(e))}catch{return!1}}}function vu(e,t){let n=_u(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);(r.length>0||t.length===0)&&e(r)}}function yu(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=hu(i,e);Gs(t[0],t,e,o);let s=As(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=us(r.compareOptions)(bu(e.value,r.expression),bu(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 bu(e,t){if(t.type===`ref`){let n=t,r=e;for(let e of n.path)r=r?.[e];return r}else if(t.type===`val`)return t.value;else return ys(t)(e)}var xu=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=tc(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=tc(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)}},Su=`__tanstack_db_direct`,Cu=class{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,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}=this.pendingSyncedTransactions.reduce((e,t)=>(t.committed?(e.committedSyncedTransactions.push(t),t.truncate&&(e.hasTruncateSync=!0),t.immediate&&(e.hasImmediateSync=!0)):e.uncommittedSyncedTransactions.push(t),e),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1});if(!e||r||i){this.isCommittingSyncTransactions=!0;let e=new Map(this.rowOrigins),i=new Map(this.optimisticUpserts),a=new Set(this.optimisticDeletes),o=r?t.find(e=>e.truncate)?.optimisticSnapshot:null,s,c,l=new Set;for(let e of t){for(let t of e.operations)l.add(t.key);for(let[t]of e.rowMetadataWrites)l.add(t)}let u=this.preSyncVisibleState;if(u.size===0){u=new Map;for(let e of l){let t=this.get(e);t!==void 0&&u.set(e,t)}}let d=[],f=this.config.sync.rowUpdateMode||`partial`,p=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&&p.set(t.key,{type:t.type,value:t.modified});for(let e of t){if(e.truncate){let e=new Set([...this.syncedData.keys(),...o?.upserts.keys()||[]]);for(let t of e){if(o?.deletes.has(t))continue;let e=o?.upserts.get(t)||this.syncedData.get(t);e!==void 0&&d.push({type:`delete`,key:t,value:e})}s=new Set(this.pendingLocalChanges),c=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear(),this.clearOriginTrackingState();for(let e of l)u.delete(e);this._events.emit(`truncate`,{type:`truncate`,collection:this.collection})}for(let t of e.operations){let e=t.key;this.syncedKeys.add(e);let n=this.isLocalOnly||this.pendingLocalChanges.has(e)||this.pendingLocalOrigins.has(e)||s?.has(e)===!0||c?.has(e)===!0?`local`:`remote`;switch(t.type){case`insert`:this.syncedData.set(e,t.value),this.rowOrigins.set(e,n),this.pendingLocalChanges.delete(e),this.pendingLocalOrigins.delete(e),this.pendingOptimisticUpserts.delete(e),this.pendingOptimisticDeletes.delete(e),this.pendingOptimisticDirectUpserts.delete(e),this.pendingOptimisticDirectDeletes.delete(e);break;case`update`:if(f===`partial`){let n=Object.assign({},this.syncedData.get(e),t.value);this.syncedData.set(e,n)}else this.syncedData.set(e,t.value);this.rowOrigins.set(e,n),this.pendingLocalChanges.delete(e),this.pendingLocalOrigins.delete(e),this.pendingOptimisticUpserts.delete(e),this.pendingOptimisticDeletes.delete(e),this.pendingOptimisticDirectUpserts.delete(e),this.pendingOptimisticDirectDeletes.delete(e);break;case`delete`:this.syncedData.delete(e),this.syncedMetadata.delete(e),this.rowOrigins.delete(e),this.pendingLocalChanges.delete(e),this.pendingLocalOrigins.delete(e),this.pendingOptimisticUpserts.delete(e),this.pendingOptimisticDeletes.delete(e),this.pendingOptimisticDirectUpserts.delete(e),this.pendingOptimisticDirectDeletes.delete(e);break}}for(let[t,n]of e.rowMetadataWrites){if(n.type===`delete`){this.syncedMetadata.delete(t);continue}this.syncedMetadata.set(t,n.value)}for(let[t,n]of e.collectionMetadataWrites){if(n.type===`delete`){this.syncedCollectionMetadata.delete(t);continue}this.syncedCollectionMetadata.set(t,n.value)}}if(r){let e=new Set;for(let n of t)for(let t of n.operations)(t.type===`insert`||t.type===`update`)&&e.add(t.key);let n=new Map(o.upserts),r=new Set(o.deletes);for(let[t,i]of n)if(!r.has(t))if(e.has(t)){let e=!1;for(let n=d.length-1;n>=0;n--){let r=d[n];if(r.key===t&&r.type===`insert`){r.value=i,e=!0;break}}e||d.push({type:`insert`,key:t,value:i})}else d.push({type:`insert`,key:t,value:i});if(d.length>0&&r.size>0){let e=[];for(let t of d)t.type===`insert`&&r.has(t.key)||e.push(t);d.length=0,d.push(...e)}this.lifecycle.status!==`ready`&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,r&&o){for(let[e,t]of o.upserts)this.optimisticUpserts.set(e,t);for(let e of o.deletes)this.optimisticDeletes.add(e)}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);break}}for(let t of l){let n=u.get(t),r=this.get(t),o=this.getVirtualPropsSnapshotForState(t,{rowOrigins:e,optimisticUpserts:i,optimisticDeletes:a,completedOptimisticKeys:p}),s=this.getVirtualPropsSnapshotForState(t),c=o.$synced!==s.$synced||o.$origin!==s.$origin,l=n===void 0?void 0:Es(n,t,this.collection.id,()=>o.$synced,()=>o.$origin),f=p.get(t),m=!1;f&&(f.type===`delete`&&n!==void 0&&r===void 0&&es(f.value,n)||r!==void 0&&es(f.value,r))&&(m=!0);let h=c&&n!==void 0&&r!==void 0&&es(n,r);if(!(m&&!h))if(n===void 0&&r!==void 0){let e=p.get(t);if(e){let n=e.value,i=Es(n,t,this.collection.id,()=>o.$synced,()=>o.$origin);d.push({type:`update`,key:t,value:r,previousValue:i})}else d.push({type:`insert`,key:t,value:r})}else n!==void 0&&r===void 0?d.push({type:`delete`,key:t,value:l??n}):n!==void 0&&r!==void 0&&(!es(n,r)||h)&&d.push({type:`update`,key:t,value:r,previousValue:l??n})}this.size=this.calculateSize(),d.length>0&&this.indexes.updateIndexes(d),this.changes.emitEvents(d,!0),this.pendingSyncedTransactions=n,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||=!0}},this.config=e,this.transactions=new xu((e,t)=>e.compareCreatedAt(t)),this.syncedData=new xu(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`})}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=new Map(this.rowOrigins);for(let e of this.transactions.values()){let t=e.metadata[Su]===!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));break}}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);break}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)}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(){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.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.syncedKeys.clear(),this.hasReceivedFirstCommit=!1}};function wu(){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`?!0: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 Tu(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`?!0: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))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 Eu(e){let t=Tu(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`?!0: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`?!0: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 Z(e){if(Du(e))return new K(e.__path);if(e&&typeof e==`object`&&(e.__brand===`ToArrayWrapper`||e.__brand===`ConcatToArrayWrapper`)){let t=e.__brand===`ToArrayWrapper`?`toArray()`:`concat(toArray())`;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 ba(e)}function Du(e){return e&&typeof e==`object`&&e.__refProxy===!0}function Ou(e,t){return new xa(`eq`,[Z(e),Z(t)])}function ku(e,t){return new xa(`gt`,[Z(e),Z(t)])}function Au(e,t){return new xa(`gte`,[Z(e),Z(t)])}function ju(e,t){return new xa(`lt`,[Z(e),Z(t)])}function Mu(e,t,...n){return new xa(`and`,[e,t,...n].map(e=>Z(e)))}function Nu(e,t,...n){return new xa(`or`,[e,t,...n].map(e=>Z(e)))}function Pu(e,t){return new xa(`in`,[Z(e),Z(t)])}var Fu=class{constructor(e){this.query=e,this.__brand=`ToArrayWrapper`}},Iu=class{constructor(e){this.query=e,this.__brand=`ConcatToArrayWrapper`}},Lu=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 Ru(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`?ku:ju)(n,new ba(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(Ou(r.expression,new ba(i)))}let s=(i.compareOptions.direction===`asc`?ku:ju)(i.expression,new ba(a));if(o.length===0)n.push(s);else{let e=[...o,s];n.push(e.reduce((e,t)=>Mu(e,t)))}}return n.length===1?n[0]:n.reduce((e,t)=>Nu(e,t))}var zu=class extends Lu{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.loadedSubsets=[],this.sentKeys=new Set,this.limitedSnapshotRowCount=0,this._status=`ready`,this.pendingLoadSubsetPromises=new Set,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches=new Set,n.onUnsubscribe&&this.on(`unsubscribed`,e=>n.onUnsubscribe(e)),n.whereExpression&&Ks(n.whereExpression,this.collection);let r=e=>{t(e),this.trackSentKeys(e)};this.callback=r,this.filteredCallback=n.whereExpression?vu(this.callback,n):this.callback,this.truncateCleanup=this.collection.on(`truncate`,()=>{this.handleTruncate()})}get status(){return this._status}handleTruncate(){let e=[...this.loadedSubsets],t=this.collection._sync.syncLoadSubsetFn!==null;if(e.length===0||!t){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[];return}this.isBufferingForTruncate=!0,this.truncateBuffer=[],this.pendingTruncateRefetches.clear(),this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[],queueMicrotask(()=>{if(this.isBufferingForTruncate){for(let t of e){let e=this.collection._sync.loadSubset(t);this.loadedSubsets.push(t),this.trackLoadSubsetPromise(e),e instanceof Promise&&(this.pendingTruncateRefetches.add(e),e.catch(()=>{}).finally(()=>{this.pendingTruncateRefetches.delete(e),this.checkTruncateRefetchComplete()}))}this.pendingTruncateRefetches.size===0&&this.flushTruncateBuffer()}})}checkTruncateRefetchComplete(){this.pendingTruncateRefetches.size===0&&this.isBufferingForTruncate&&this.flushTruncateBuffer()}flushTruncateBuffer(){this.isBufferingForTruncate=!1;let e=this.truncateBuffer.flat();e.length>0&&this.filteredCallback(e),this.truncateBuffer=[]}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})}trackLoadSubsetPromise(e){e instanceof Promise&&(this.pendingLoadSubsetPromises.add(e),this.setStatus(`loadingSubset`),e.finally(()=>{this.pendingLoadSubsetPromises.delete(e),this.pendingLoadSubsetPromises.size===0&&this.setStatus(`ready`)}))}hasLoadedInitialState(){return this.loadedInitialState}hasSentAtLeastOneSnapshot(){return this.snapshotSent}emitEvents(e){let t=this.filterAndFlipChanges(e);this.isBufferingForTruncate?t.length>0&&this.truncateBuffer.push(t):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=Mu(e,n)}else t.where=n}}else this.loadedInitialState=!0;let n={where:t.where,subscription:this,orderBy:e?.orderBy,limit:e?.limit},r=this.collection._sync.loadSubset(n);e?.onLoadSubsetResult?.(r),this.loadedSubsets.push(n),(e?.trackLoadSubsetPromise??!0)&&this.trackLoadSubsetPromise(r);let i=this.collection.currentStateAsChanges(t);if(i===void 0)return!1;let a=i.filter(e=>!this.sentKeys.has(e.key));for(let e of a)this.sentKeys.add(e.key);return this.snapshotSent=!0,this.callback(a),!0}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?_u(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:Ou(n,new ba(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`?J(new K(_.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+=p.length,p.length>0&&(this.lastSentKey=p[p.length-1].key);let b;if(n!==void 0&&n.length>0){let t=Ru(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=Mu(Au(r,new ba(i)),ju(r,new ba(e)))}else a=Ou(r,new ba(i));b={whereFrom:t,whereCurrent:a,lastKey:this.lastSentKey}}}let x={where:l,limit:t,orderBy:e,cursor:b,offset:r??y,subscription:this},S=this.collection._sync.loadSubset(x);a?.(S),this.loadedSubsets.push(x),i&&this.trackLoadSubsetPromise(S)}filterAndFlipChanges(e){if(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};else if(r.type===`delete`&&!t)continue;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}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(){this.truncateCleanup?.(),this.truncateCleanup=void 0,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches.clear();for(let e of this.loadedSubsets)this.collection._sync.unloadSubset(e);this.loadedSubsets=[],this.emitInner(`unsubscribed`,{type:`unsubscribed`,subscription:this}),this.clearListeners()}},Bu=class{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){for(let e of this.changeSubscriptions)e.emitEvents([])}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,t=!1){if(this.shouldBatchEvents&&!t){this.batchedEvents.push(...e);return}let n=e;if(t&&(this.batchedEvents.length>0&&(n=[...this.batchedEvents,...e]),this.batchedEvents=[],this.shouldBatchEvents=!1),n.length===0)return;let r=n.map(e=>this.enrichChangeWithVirtualProps(e));for(let e of this.changeSubscriptions)e.emitEvents(r)}subscribeChanges(e,t={}){if(this.addSubscriber(),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=Z(n(wu())));let a=new zu(this.collection,e,{...r,whereExpression:i,onUnsubscribe:()=>{this.removeSubscriber(),this.changeSubscriptions.delete(a)}});return 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),a}addSubscriber(){let e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer(),(this.lifecycle.status===`cleaned-up`||this.lifecycle.status===`idle`)&&this.sync.startSync(),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 Ha;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}},Vu=e=>setTimeout(()=>{e({didTimeout:!0,timeRemaining:()=>50})},0),Hu=e=>{clearTimeout(e)},Uu=typeof window<`u`&&`requestIdleCallback`in window?(e,t)=>window.requestIdleCallback(e,t):(e,t)=>Vu(e),Wu=typeof window<`u`&&`cancelIdleCallback`in window?e=>window.cancelIdleCallback(e):Hu,Gu=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)}};Gu.instance=null;var Ku=Gu,qu=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:[`cleaned-up`,`idle`],"cleaned-up":[`loading`,`error`]}[e].includes(t))throw new Ba(e,t,this.id)}setStatus(e,t=!1){if(e===`ready`&&!t)throw new Ra(`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 za(e,this.id);case`cleaned-up`:this.sync.startSync();break}}markReady(){if(this.validateStatusTransition(this.status,`ready`),this.status===`loading`){if(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()}}startGCTimer(){let e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||Ku.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Ku.getInstance().cancel(this),this.idleCallbackId!==null&&(Wu(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Wu(this.idleCallbackId),this.idleCallbackId=Uu(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(),Ku.getInstance().cancel(this),this.hasBeenReady=!1;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.events.cleanup(),!0}else return this.scheduleIdleCleanup(),!1}onFirstReady(e){if(this.hasBeenReady){e();return}this.onFirstReadyCallbacks.push(e)}cleanup(){this.idleCallbackId!==null&&(Wu(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}},Ju=Symbol(`liveQueryInternal`),Yu=class{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,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}startSync(){if(!(this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`)){this.lifecycle.setStatus(`loading`);try{let e=Xu(this.config.sync.sync({collection:this.collection,begin:e=>{this.state.pendingSyncedTransactions.push({committed:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:e?.immediate})},write:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!t)throw new lo;if(t.committed)throw new uo;let n;n=`key`in e?e.key:this.config.getKey(e.value),this.state.pendingLocalChanges.has(n)&&this.state.pendingLocalOrigins.add(n);let r=e.type;if(e.type===`insert`){let i=this.state.syncedData.has(n),a=t.deletedKeys.has(n),o=t.truncate===!0;if(i&&!a&&!o){let t=this.state.syncedData.get(n);if(t!==void 0&&es(t,e.value))r=`update`;else{let e=this.config.utils[Ju];throw new qa(n,this.id,{hasCustomGetKey:e?.hasCustomGetKey??!1,hasJoins:e?.hasJoins??!1,hasDistinct:e?.hasDistinct??!1})}}}let i={...e,type:r,key:n};t.operations.push(i),r===`delete`?(t.deletedKeys.add(n),t.rowMetadataWrites.set(n,{type:`delete`})):r===`insert`?i.metadata===void 0?t.rowMetadataWrites.set(n,{type:`delete`}):t.rowMetadataWrites.set(n,{type:`set`,value:i.metadata}):i.metadata!==void 0&&t.rowMetadataWrites.set(n,{type:`set`,value:i.metadata})},commit:()=>{let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new fo;if(e.committed)throw new po;e.committed=!0,this.state.commitPendingTransactions()},markReady:()=>{this.lifecycle.markReady()},truncate:()=>{let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new lo;if(e.committed)throw new uo;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()}));if(this.syncCleanupFn=e?.cleanup??null,this.syncLoadSubsetFn=e?.loadSubset??null,this.syncUnloadSubsetFn=e?.unloadSubset??null,this.syncMode===`on-demand`&&!this.syncLoadSubsetFn)throw new Na(`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.setStatus(`error`),e}}}getActivePendingSyncTransaction(){let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new lo;if(e.committed)throw new uo;return e}createSyncMetadataApi(){return{row:{get:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],n=t?.rowMetadataWrites.get(e);if(n)return n.type===`delete`?void 0:n.value;if(!t?.truncate)return this.state.syncedMetadata.get(e)},set:(e,t)=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:`set`,value:t})},delete:e=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:`delete`})}},collection:{get:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(e);return t?t.type===`delete`?void 0:t.value:this.state.syncedCollectionMetadata.get(e)},set:(e,t)=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:`set`,value:t})},delete:e=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:`delete`})},list:e=>{let t=new Map(this.state.syncedCollectionMetadata),n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(n)for(let[e,r]of n.collectionMetadataWrites)r.type===`delete`?t.delete(e):t.set(e,r.value);return Array.from(t.entries()).filter(([t])=>e?t.startsWith(e):!0).map(([e,t])=>({key:e,value:t}))}}}}preload(){return this.preloadPromise?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.`),this.preloadPromise=new Promise((e,t)=>{if(this.lifecycle.status===`ready`){e();return}if(this.lifecycle.status===`error`){t(new Va);return}if(this.lifecycle.onFirstReady(()=>{e()}),this.lifecycle.status===`idle`||this.lifecycle.status===`cleaned-up`)try{this.startSync()}catch(e){t(e);return}}),this.preloadPromise)}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}trackLoadPromise(e){let t=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),t&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:`start`}),e.finally(()=>{let t=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),t&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:`end`})})}loadSubset(e){if(this.syncMode===`eager`)return!0;if(this.syncLoadSubsetFn){let t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}cleanup(){try{this.syncCleanupFn&&=(this.syncCleanupFn(),null)}catch(e){queueMicrotask(()=>{if(e instanceof Error){let t=new Jo(this.id,e);throw t.cause=e,t.stack=e.stack,t}else throw new Jo(this.id,e)})}this.preloadPromise=null}};function Xu(e){if(typeof e==`function`)return{cleanup:e};if(typeof e==`object`)return e}var Zu=1;function Qu(e,t){return e===t?0:e<t?-1:1}function $u(e){return{kind:`constructor`,...e.name?{name:e.name}:{}}}function ed(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=>ed(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=>ed(e)??null).sort((e,t)=>Qu(td(e),td(t)))};if(e instanceof Map)return{__type:`map`,entries:Array.from(e.entries()).map(([e,t])=>({key:ed(e)??null,value:ed(t)??null})).sort((e,t)=>Qu(td(e.key),td(t.key)))};if(e instanceof RegExp)return{__type:`regexp`,value:e.toString()};let t={},n=Object.entries(e).sort(([e],[t])=>Qu(e,t));for(let[e,r]of n){let n=ed(r);n!==void 0&&(t[e]=n)}return t}function td(e){return e===null?`null`:Array.isArray(e)?`[${e.map(td).join(`,`)}]`:typeof e==`object`?`{${Object.keys(e).sort((e,t)=>Qu(e,t)).map(t=>`${JSON.stringify(t)}:${td(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function nd(e,t,n,r,i){let a=$u(r),o=ed(t)??null,s=ed(i);return{signatureVersion:Zu,signature:td(ed({signatureVersion:Zu,expression:o,options:s??null})??null),indexId:e,name:n,expression:t,resolver:a,...s===void 0?{}:{options:s}}}function rd(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>rd(e));let t={};for(let[n,r]of Object.entries(e))t[n]=rd(r);return t}function id(e){return JSON.parse(JSON.stringify(e))}var ad=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=Z(e(wu())),i=t.indexType??this.defaultIndexType;if(!i)throw new Na(`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=nd(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:id(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:rd(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);break}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}},od=new Set([`find`,`findLast`,`findIndex`,`findLastIndex`,`filter`,`map`,`flatMap`,`forEach`,`some`,`every`,`reduce`,`reduceRight`]),sd=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]),cd=new Set([`set`,`delete`,`clear`,`add`]),ld=new Set([`entries`,`keys`,`values`,`forEach`]);function ud(e){return typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof RegExp)&&!rs(e)}function dd(e,t,n,r){if(od.has(e))return function(...i){let a=i[0];if(typeof a!=`function`)return t.apply(n.copy_,i);let o=(e,t)=>{if(ud(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 fd(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(ud(i)){let{proxy:n}=t(i,{tracker:e,prop:String(r)});a=n}return r++,{done:!1,value:a}},[Symbol.iterator](){return this}}}}function pd(e,t,n){return function(...r){let i=e.apply(t.copy_,r);return n(t),i}}function md(e,t,n,r,i,a,o){if(ld.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 Q(...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 hd(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]=hd(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,hd(e,t))}),n}if(e instanceof Set){let n=new Set;return t.set(e,n),e.forEach(e=>{n.add(hd(e,t))}),n}if(rs(e))return e;let n={};t.set(e,n);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=hd(e[r],t));let r=Object.getOwnPropertySymbols(e);for(let i of r)n[i]=hd(e[i],t);return n}var gd=0;function _d(){return gd+=1,gd}function vd(e,t){let n=new Map;function r(e,t){if(Q(`Object ID:`,e.constructor.name),n.has(e))return n.get(e);{let r=vd(e,t);return n.set(e,r),r}}let i=new Map,a={copy_:hd(e),originalObject:hd(e),proxyCount:_d(),modified:!1,assigned_:{},parent:t,target:e};Q(`createChangeProxy called for target`,e,a.proxyCount);function o(e){e.modified||=!0,e.parent&&(Q(`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(Q(`checkIfReverted called with assigned keys:`,Object.keys(e.assigned_)),Object.keys(e.assigned_).length===0&&Object.getOwnPropertySymbols(e.assigned_).length===0)return Q(`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(Q(`Checking property ${String(t)}, current:`,n,`original:`,r),!es(n,r))return Q(`Property ${String(t)} is different, returning false`),!1}else if(e.assigned_[t]===!1)return Q(`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(!es(t,r))return Q(`Symbol property is different, returning false`),!1}else if(e.assigned_[n]===!1)return Q(`Symbol property was deleted, returning false`),!1;return Q(`All properties match original values, returning true`),!0}function c(e,t){Q(`checkParentStatus called for child prop:`,t);let n=s(e);Q(`Parent checkIfReverted returned:`,n),n&&(Q(`Parent is fully reverted, clearing tracking`),e.modified=!1,e.assigned_={},e.parent&&(Q(`Continuing up the parent chain`),c(e.parent.tracker,e.parent.prop)))}function l(e){if(Q(`createObjectProxy`,e),i.has(e))return Q(`proxyCache found match`),i.get(e);let n=new Proxy(e,{get(e,t){Q(`get`,e,t);let n=a.copy_[t]??a.originalObject[t],s=a.originalObject[t];if(Q(`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(sd.has(e))return pd(n,a,o);let i=dd(e,n,a,r);if(i)return i;if(t===Symbol.iterator)return fd(a,r)}if(e instanceof Map||e instanceof Set){let i=t.toString();if(cd.has(i))return pd(n,a,o);let s=md(i,t,n,e,a,r,o);if(s)return s}return n.bind(e)}if(ud(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(Q(`set called for property ${String(n)}, current:`,i,`new:`,r),es(i,r))Q(`Value unchanged, not tracking`);else{let e=a.originalObject[n],i=es(r,e);if(Q(`value:`,r,`original:`,e,`isRevertToOriginal:`,i),i){Q(`Reverting property ${String(n)} to original value`),delete a.assigned_[n.toString()],Q(`Updating copy with original value for ${String(n)}`),a.copy_[n]=hd(e),Q(`Checking if all properties reverted`);let r=s(a);Q(`All reverted:`,r),r?(Q(`All properties reverted, clearing tracking`),a.modified=!1,a.assigned_={},t&&(Q(`Updating parent for property:`,t.prop),c(t.tracker,t.prop))):(Q(`Some properties still changed, keeping modified flag`),a.modified=!0)}else Q(`Setting new value for property ${String(n)}`),a.copy_[n]=r,a.assigned_[n.toString()]=!0,Q(`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]=hd(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){Q(`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(Q(`getChanges called, modified:`,a.modified),Q(a),!a.modified)return Q(`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 Q(`Returning copy:`,e),e}}}function yd(e){let t=e.map(e=>vd(e));return{proxies:t.map(e=>e.proxy),getChanges:()=>t.map(e=>e.getChanges())}}function bd(e,t){let{proxy:n,getChanges:r}=vd(e);return t(n),r()}function xd(e,t){let{proxies:n,getChanges:r}=yd(e);return t(n),r()}function Sd(){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}}function Cd(e){return typeof e==`object`&&!!e&&typeof e.hasPendingGraphRun==`function`}var wd=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=Cd(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))}},Td=[],Ed=[],Dd=0;function Od(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 kd(e){let t=new Pd(e);return Td.push(t),t}function Ad(){if(Ed.length>0)return Ed.slice(-1)[0]}function jd(e){wd.clear(e.id),Ed.push(e)}function Md(e){try{wd.flush(e.id)}finally{Ed=Ed.filter(t=>t.id!==e.id)}}function Nd(e){let t=Td.findIndex(t=>t.id===e.id);t!==-1&&Td.splice(t,1)}var Pd=class{constructor(e){if(e.mutationFn===void 0)throw new ao;this.id=e.id??crypto.randomUUID(),this.mutationFn=e.mutationFn,this.state=`pending`,this.mutations=[],this.isPersisted=Sd(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=Dd++,this.metadata=e.metadata??{}}setState(e){this.state=e,(e===`completed`||e===`failed`)&&Nd(this)}mutate(e){if(this.state!==`pending`)throw new oo;jd(this);try{e()}finally{Md(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){for(let t of e){let e=this.mutations.findIndex(e=>e.globalKey===t.globalKey);if(e>=0){let n=this.mutations[e],r=Od(n,t);r===null?this.mutations.splice(e,1):this.mutations[e]=r}else this.mutations.push(t)}}rollback(e){let t=e?.isSecondaryRollback??!1;if(this.state===`completed`)throw new so;if(this.setState(`failed`),!t){let e=new Set;this.mutations.forEach(t=>e.add(t.globalKey));for(let t of Td)t.state===`pending`&&t.mutations.some(t=>e.has(t.globalKey))&&t.rollback({isSecondaryRollback:!0})}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 co;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}},Fd=class{constructor(e,t){this.insert=(e,t)=>{this.lifecycle.validateCollectionUsable(`insert`);let n=this.state,r=Ad();if(!r&&!this.config.onInsert)throw new to;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 Ka(r);o.add(r);let i=this.generateGlobalKey(r,e),s={mutationId:crypto.randomUUID(),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=kd({metadata:{[Su]:!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=Ad();if(!r&&!this.config.onDelete)throw new ro;if(Array.isArray(e)&&e.length===0)throw new Qa;let i=Array.isArray(e)?e:[e],a=[];for(let e of i){if(!this.state.has(e))throw new $a(e);let r=this.generateGlobalKey(e,this.state.get(e)),i={mutationId:crypto.randomUUID(),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=kd({autoCommit:!0,metadata:{[Su]:!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}ensureStandardSchema(e){if(e&&`~standard`in e)return e;throw new Ia}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 La;if(`issues`in a&&a.issues)throw new Ma(t,a.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));let o=a.value;return Object.fromEntries(Object.keys(e).map(e=>[e,o[e]]))}}let i=r[`~standard`].validate(e);if(i instanceof Promise)throw new La;if(`issues`in i&&i.issues)throw new Ma(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 Wa(t):new Ga(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 Ja;let r=this.state;this.lifecycle.validateCollectionUsable(`update`);let i=Ad();if(!i&&!this.config.onUpdate)throw new no;let a=Array.isArray(e),o=a?e:[e];if(a&&o.length===0)throw new Ya;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 Xa(e);return t}),u;u=a?xd(l,s):[bd(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 Za(s,d);let f=this.generateGlobalKey(d,o);return{mutationId:crypto.randomUUID(),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=kd({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=kd({metadata:{[Su]:!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}},Id=class extends Lu{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 Ld(e){let t=new Rd(e);return e.utils?t.utils=e.utils:t.utils={},t}var Rd=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 Pa;if(!e.sync)throw new Fa;if(e.id?this.id=e.id:this.id=crypto.randomUUID(),this.config={...e,autoIndex:e.autoIndex??`off`},this.config.autoIndex===`eager`&&!e.defaultIndexType)throw new Na(`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 Bu,this._events=new Id,this._indexes=new ad,this._lifecycle=new qu(e,this.id),this._mutations=new Fd(e,this.id),this._state=new Cu(e),this._sync=new Yu(e,this.id),this.comparisonOpts=zd(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}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status===`ready`}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}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 gu(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 zd(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}}else return{stringSort:`locale`}}function Bd(e){let t=Vd(e),n=e,r,i=0;for(;i<10&&!es(n,r);)r=n,n=Wd(n),i++;return{optimizedQuery:Kd(n),sourceWhereClauses:t}}function Vd(e){let t=new Map;if(!e.where||e.where.length===0)return t;let n=Qd(Yd(e.where).map(e=>Zd(e))),r=Ud(e);for(let[i,a]of n.singleSource)Hd(e,i)&&!r.has(i)&&t.set(i,a);return t}function Hd(e,t){if(e.from.alias===t)return e.from.type===`collectionRef`;if(e.join){for(let n of e.join)if(n.from.alias===t)return n.from.type===`collectionRef`}return!1}function Ud(e){let t=new Set;if(e.join){let n=e.from.alias;for(let r of e.join){let e=r.from.alias;(r.type===`left`||r.type===`full`)&&t.add(e),(r.type===`right`||r.type===`full`)&&t.add(n)}}return t}function Wd(e){return Gd({...e,from:e.from.type===`queryRef`?new ya(Wd(e.from.query),e.from.alias):e.from,join:e.join?.map(e=>({...e,from:e.from.type===`queryRef`?new ya(Wd(e.from.query),e.from.alias):e.from}))})}function Gd(e){if(!e.where||e.where.length===0)return e;if(!e.join||e.join.length===0){if(e.where.length>1){let t=pf(Yd(e.where));return{...e,where:[t]}}return e}let t=$d(e,Qd(Yd(e.where.filter(e=>!Da(e))).map(e=>Zd(e)))),n=e.where.filter(e=>Da(e));return n.length>0&&(t.where=[...t.where||[],...n]),t}function Kd(e){return{...e,from:qd(e.from),join:e.join?.map(e=>({...e,from:qd(e.from)}))}}function qd(e){if(e.type===`collectionRef`)return e;let t=Kd(e.query);if(Jd(t)){let n=qd(t.from);return n.type===`collectionRef`?new va(n.collection,e.alias):new ya(n.query,e.alias)}return new ya(t,e.alias)}function Jd(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 Yd(e){let t=[];for(let n of e){let e=Ta(n);t.push(...Xd(e))}return t}function Xd(e){if(e.type===`func`&&e.name===`and`){let t=[];for(let n of e.args)t.push(...Xd(n));return t}else return[e]}function Zd(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);break}}return r(e),{expression:e,touchedSources:t,hasNamespaceOnlyRef:n}}function Qd(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,pf(n));return{singleSource:r,multiSource:n.length>0?pf(n):void 0}}function $d(e,t){let n=new Set,r=Ud(e),i=new Map;for(let[e,n]of t.singleSource)r.has(e)||i.set(e,n);let a=tf(e.from,i,n),o=e.join?e.join.map(e=>({...e,from:tf(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(Oa(r)):s.push(r);let l=s.length>1?[pf(s.flatMap(e=>Xd(Ta(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 ef(e){return{from:e.from.type===`collectionRef`?new va(e.from.collection,e.from.alias):new ya(ef(e.from.query),e.from.alias),select:e.select,join:e.join?e.join.map(e=>({type:e.type,left:e.left,right:e.right,from:e.from.type===`collectionRef`?new va(e.from.collection,e.from.alias):new ya(ef(e.from.query),e.from.alias)})):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 tf(e,t,n){let r=t.get(e.alias);if(!r)return e.type===`collectionRef`?new va(e.collection,e.alias):new ya(ef(e.query),e.alias);if(e.type===`collectionRef`){let t={from:new va(e.collection,e.alias),where:[r]};return n.add(e.alias),new ya(t,e.alias)}if(!cf(e.query,r,e.alias)||ff(e.query,r,e.alias))return new ya(ef(e.query),e.alias);let i=e.query.where||[],a={...ef(e.query),where:[...i,r]};return n.add(e.alias),new ya(a,e.alias)}function nf(e,t,n){return e.select?lf(e.select)||df(e.select,t,n):!1}function rf(e){return e.groupBy&&e.groupBy.length>0}function af(e){return e.having&&e.having.length>0}function of(e){return e.orderBy&&e.orderBy.length>0&&(e.limit!==void 0||e.offset!==void 0)}function sf(e){return e.fnSelect||e.fnWhere&&e.fnWhere.length>0||e.fnHaving&&e.fnHaving.length>0}function cf(e,t,n){return!(nf(e,t,n)||rf(e)||af(e)||of(e)||sf(e))}function lf(e){for(let t of Object.values(e))if(typeof t==`object`){let e=t;if(e.type===`agg`||!(`type`in e)&&lf(e))return!0}return!1}function uf(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(...uf(n));break}return t}function df(e,t,n){let r=new Set;for(let[t,n]of Object.entries(e))t.startsWith(`__SPREAD_SENTINEL__`)||n instanceof K||r.add(t);let i=uf(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 ff(e,t,n){let r=uf(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 K)||a.path.length<2)return!0;let[o,s]=a.path;if(o!==n&&o!==e.from.alias||s!==r[1])return!0}return!1}function pf(e){if(e.length===0)throw new Xo;return e.length===1?e[0]:new xa(`and`,e)}function mf(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=e;for(let e of t)y=hf(y,e,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v);return y}function hf(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=t.from.type===`collectionRef`,{alias:b,input:x,collectionId:S}=vf(t.from,a,c,l,u,d,f,p,o,s,h,g,_,v);n[b]=x,y&&(g[b]=S);let C=c[r],w=c[S];if(!C)throw new Po(r);if(!w)throw new Po(S);let{activeSource:T,lazySource:E}=bf(t.type,C,w),D=Object.keys(n),{mainExpr:O,joinedExpr:k}=gf(t.left,t.right,D,b),A=J(O),j=J(k),M=e.pipe(X(([e,t])=>[ms(A(t)),[e,t]])),N=x.pipe(X(([e,t])=>{let n={[b]:t};return[ms(j(n)),[e,n]]}));if(![`inner`,`left`,`right`,`full`].includes(t.type))throw new Io(t.type);if(T){let e=T===`main`?t.from:m.from,n=e.type===`queryRef`&&(e.query.limit||e.query.offset),r=O.type===`func`||k.type===`func`;if(!n&&!r){let e=T===`main`?b:i;d.add(e);let t=T===`main`?M:N,n=Aa(m,T===`main`?k:O,E),r=n.collection,a=n.path[0];a&&Gs(a,n.path,r);let o=t.pipe(Fl(t=>{let i=_[e]||e,a=l[i];if(!a)throw new Zo(i,e,E.id,Object.keys(l));if(a.hasLoadedInitialState())return;let o=[...new Set(t.getInner().map(([[e]])=>e).filter(e=>e!=null))];if(o.length===0)return;let s=new K(n.path);if(!a.requestSnapshot({where:Pu(s,o),optimizedOnly:!0})){let e=r.id,t=n.path.join(`.`);console.warn(`[TanStack DB]${e?` [${e}]`:``} Join requires an index on "${t}" for efficient 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.`),a.requestSnapshot()}}));T===`main`?M=o:N=o}}return M.pipe(Al(N,t.type),yf(t.type))}function gf(e,t,n,r){let i=n.filter(e=>e!==r),a=_f(e),o=_f(t);if(a&&i.includes(a)&&o===r)return{mainExpr:e,joinedExpr:t};if(a===r&&o&&i.includes(o))return{mainExpr:t,joinedExpr:e};throw!a||!o?new Ro:a===o?new Lo(a):i.includes(a)?o===r?new Vo:new Bo(r):new zo(a)}function _f(e){switch(e.type){case`ref`:return e.path[0]||null;case`func`:{let t=new Set;for(let n of e.args){let e=_f(n);e&&t.add(e)}return t.size===1?Array.from(t)[0]:null}default:return null}}function vf(e,t,n,r,i,a,o,s,c,l,u,d,f,p){switch(e.type){case`collectionRef`:{let n=t[e.alias];if(!n)throw new Oo(e.alias,e.collection.id,Object.keys(t));return d[e.alias]=e.collection.id,{alias:e.alias,input:n,collectionId:e.collection.id}}case`queryRef`:{let m=u(l.get(e.query)||e.query,t,n,r,i,a,o,s,c,l);Object.assign(d,m.aliasToCollectionId),Object.assign(f,m.aliasRemapping);let h=l.has(e.query),g=e.query.from.alias;if(!(!h&&e.alias===g))for(let[e,t]of m.sourceWhereClauses)p.set(e,t);let _=Object.keys(m.aliasToCollectionId).find(e=>m.aliasToCollectionId[e]===m.collectionId);_&&_!==e.alias&&(f[e.alias]=_);let v=m.pipeline.pipe(X(e=>{let[t,[n,r]]=e;return[t,n]}));return{alias:e.alias,input:v,collectionId:m.collectionId}}default:throw new Ho(e.type)}}function yf(e){return function(t){return t.pipe(ll(t=>{let[n,[r,i]]=t,a=r?.[1],o=i?.[1];return e===`inner`?!!(a&&o):e===`left`?!!a:e===`right`?!!o:!0}),X(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 bf(e,t,n){switch(e){case`left`:return{activeSource:`main`,lazySource:n};case`right`:return{activeSource:`joined`,lazySource:t};case`inner`:return t.size<n.size?{activeSource:`main`,lazySource:n}:{activeSource:`joined`,lazySource:t};default:return{activeSource:void 0,lazySource:void 0}}}function xf(e){return e instanceof ba?e.value:e}function Sf(e,t,n){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]=xf(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]=xf(n)}else{let e=t[n];(typeof e!=`object`||!e)&&(t[n]={}),t=t[n]}}}}function Cf(e,t,n){let r=e.alias.split(`.`);if(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]]=xf(e.compiled(t))}}function wf([e,t],n){let r={};for(let e of n)e.kind===`merge`?Sf(e,t,r):Cf(e,t,r);return[e,{...t,$selected:r}]}function Tf(e,t,n){let r=[];return Of([],t,r),e.pipe(X(e=>wf(e,r)))}function Ef(e){return e.type===`agg`}function Df(e){return e&&typeof e==`object`&&!wa(e)}function Of(e,t,n){for(let[r,i]of Object.entries(t)){if(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=J(s?i:new K(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(t&&t.type===`includesSubquery`){n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});continue}if(Df(t)){Of([...e,r],t,n);continue}if(Ef(t)||du(t))n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});else{if(t===void 0||!wa(t)){n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>t});continue}if(t instanceof ba){let i=t.value;n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>i})}else n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:J(t)})}}}var kf=Symbol(`includesRouting`);function Af(e,t,n,r,i,a,o,s,c=new WeakMap,l=new WeakMap,u,d){let f=c.get(e);if(f)return f;Mf(e);let{optimizedQuery:p,sourceWhereClauses:m}=Bd(e),h=p;l.set(h,e),Lf(h,e,l);let g={...t},_={},v={},y={},{alias:b,input:x,collectionId:S}=Nf(h.from,g,n,r,i,a,o,s,c,l,_,v,m);y[b]=x;let C=x;if(u&&d){let e=d.path.slice(1);C=x.pipe(X(([t,n])=>[Wf(n,e),[t,n]])).pipe(Al(u,`inner`)).pipe(ll(([e,[t]])=>t!=null),X(([e,[t,n]])=>{let[r,i]=t,a={...i,__correlationKey:e};return n!=null&&(a.__parentContext=n),[n==null?r:`${String(r)}::${JSON.stringify(n)}`,a]})),y[b]=C}let w=C.pipe(X(([e,t])=>{let{__parentContext:n,...r}=t,i={[b]:r};return n&&(Object.assign(i,n),i.__parentContext=n),[e,i]}));if(h.join&&h.join.length>0&&(w=mf(w,h.join,y,S,b,g,c,l,n,r,i,a,o,s,e,Af,_,v,m)),h.where&&h.where.length>0)for(let e of h.where){let t=J(Ta(e));w=w.pipe(ll(([e,n])=>vs(t(n))))}if(h.fnWhere&&h.fnWhere.length>0)for(let e of h.fnWhere)w=w.pipe(ll(([t,n])=>vs(e(n))));let T=[],E=[];if(h.select){let e=Bf(h.select);e.length>0&&(h={...h,select:{...h.select}});for(let{key:t,subquery:u}of e){let e=J(u.correlationField),d;if(u.parentProjection&&u.parentProjection.length>0){let t=u.parentProjection.map(e=>({alias:e.path[0],field:e.path.slice(1),compiled:J(e)}));d=w.pipe(X(([n,r])=>{let i={};for(let e of t){i[e.alias]||(i[e.alias]={});let t=e.compiled(r),n=i[e.alias];for(let t=0;t<e.field.length-1;t++)n[e.field[t]]||(n[e.field[t]]={}),n=n[e.field[t]];n[e.field[e.field.length-1]]=t}return[e(r),i]}))}else d=w.pipe(X(([t,n])=>[e(n),null]));d=d.pipe(al(e=>e.map(([e,t])=>[e,+(t>0)])));let f=u.childCorrelationField.path[0],p=u.query.from.type===`collectionRef`?u.query.from.collection:null,y=zf(u.query,u.childCorrelationField,p);if(y){let e=y.collection,t=y.path,n=t[0];a.add(f),n&&Gs(n,t,e),d=d.pipe(Fl(e=>{let n=r[v[f]||f];if(!n||n.hasLoadedInitialState())return;let i=[...new Set(e.getInner().map(([[e]])=>e).filter(e=>e!=null))];if(i.length===0)return;let a=new K(t);n.requestSnapshot({where:Pu(a,i)})}))}let b=Af(u.parentFilters&&u.parentFilters.length>0?{...u.query,where:[...u.query.where||[],...u.parentFilters]}:u.query,g,n,r,i,a,o,s,c,l,d,u.childCorrelationField);Object.assign(_,b.aliasToCollectionId),Object.assign(v,b.aliasRemapping);for(let[e,t]of b.sourceWhereClauses)m.set(e,t);if(T.push({pipeline:b.pipeline,fieldName:u.fieldName,correlationField:u.correlationField,childCorrelationField:u.childCorrelationField,hasOrderBy:!!(u.query.orderBy&&u.query.orderBy.length>0),childCompilationResult:b,parentProjection:u.parentProjection,materialization:u.materialization,scalarField:u.scalarField}),u.parentProjection&&u.parentProjection.length>0){let t=u.parentProjection.map(e=>({alias:e.path[0],field:e.path.slice(1),compiled:J(e)})),n=e;E.push({fieldName:u.fieldName,getRouting:e=>{let r={};for(let n of t){r[n.alias]||(r[n.alias]={});let t=n.compiled(e),i=r[n.alias];for(let e=0;e<n.field.length-1;e++)i[n.field[e]]||(i[n.field[e]]={}),i=i[n.field[e]];i[n.field[n.field.length-1]]=t}return{correlationKey:n(e),parentContext:r}}})}else E.push({fieldName:u.fieldName,getRouting:t=>({correlationKey:e(t),parentContext:null})});Uf(h.select,t)}}if(h.distinct&&!h.fnSelect&&!h.select)throw new Co;if(h.fnSelect&&h.groupBy&&h.groupBy.length>0)throw new wo;w=h.fnSelect?w.pipe(X(([e,t])=>{let n=h.fnSelect(t);return[e,{...t,$selected:n}]})):h.select?Tf(w,h.select):w.pipe(X(([e,t])=>{let n=!h.join&&!h.groupBy?t[b]:t;return[e,{...t,$selected:n}]})),E.length>0&&(w=w.pipe(X(([e,t])=>{let n={};for(let{fieldName:e,getRouting:r}of E)n[e]=r(t);return t.$selected[kf]=n,[e,t]})));let D=u?b:void 0;if(h.groupBy&&h.groupBy.length>0?w=ou(w,h.groupBy,h.having,h.select,h.fnHaving,S,D):h.select&&Object.values(h.select).some(e=>e.type===`agg`||du(e))&&(w=ou(w,[],h.having,h.select,h.fnHaving,S,D)),h.having&&(!h.groupBy||h.groupBy.length===0)&&!(h.select&&Object.values(h.select).some(e=>e.type===`agg`)))throw new Eo;if(h.fnHaving&&h.fnHaving.length>0&&(!h.groupBy||h.groupBy.length===0))for(let e of h.fnHaving)w=w.pipe(ll(([t,n])=>e(n)));if(h.distinct&&(w=w.pipe(sl(([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,r=t?.__parentContext;return r==null?n:JSON.stringify([n,r])}:void 0,r={collectionId:S,pipeline:mu(e,w,h.orderBy,h.select||{},n[S],o,s,h.limit,h.offset,t).pipe(X(([e,[t,n]])=>{let r=t.$selected,i=If(Ff(r),t);if(u){let r=t[b]?.__correlationKey,a=t.__parentContext??null;return delete i.__correlationKey,delete i.__parentContext,[e,[i,n,r,a]]}return[e,[i,n]]})),sourceWhereClauses:m,aliasToCollectionId:_,aliasRemapping:v,includes:T.length>0?T:void 0};return c.set(e,r),r}else if(h.limit!==void 0||h.offset!==void 0)throw new Do;let O={collectionId:S,pipeline:w.pipe(X(([e,t])=>{let n=t.$selected,r=If(Ff(n),t);if(u){let n=t[b]?.__correlationKey,i=t.__parentContext??null;return delete r.__correlationKey,delete r.__parentContext,[e,[r,void 0,n,i]]}return[e,[r,void 0]]})),sourceWhereClauses:m,aliasToCollectionId:_,aliasRemapping:v,includes:T.length>0?T:void 0};return c.set(e,O),O}function jf(e){let t=new Set;if(e.from.type===`collectionRef`&&t.add(e.from.alias),e.join)for(let n of e.join)n.from.type===`collectionRef`&&t.add(n.from.alias);return t}function Mf(e,t=new Set){let n=jf(e);for(let e of n)if(t.has(e))throw new ko(e,Array.from(t));let r=new Set([...t,...n]);if(e.from.type===`queryRef`&&Mf(e.from.query,r),e.join)for(let t of e.join)t.from.type===`queryRef`&&Mf(t.from.query,r)}function Nf(e,t,n,r,i,a,o,s,c,l,u,d,f){switch(e.type){case`collectionRef`:{let n=t[e.alias];if(!n)throw new Oo(e.alias,e.collection.id,Object.keys(t));return u[e.alias]=e.collection.id,{alias:e.alias,input:n,collectionId:e.collection.id}}case`queryRef`:{let p=Af(l.get(e.query)||e.query,t,n,r,i,a,o,s,c,l);Object.assign(u,p.aliasToCollectionId),Object.assign(d,p.aliasRemapping);let m=l.has(e.query),h=e.query.from.alias;if(!(!m&&e.alias===h))for(let[e,t]of p.sourceWhereClauses)f.set(e,t);let g=Object.keys(p.aliasToCollectionId).find(e=>p.aliasToCollectionId[e]===p.collectionId);g&&g!==e.alias&&(d[e.alias]=g);let _=p.pipeline.pipe(X(e=>{let[t,[n,r]]=e;return[t,Ff(n)]}));return{alias:e.alias,input:_,collectionId:p.collectionId}}default:throw new Ao(e.type)}}function Pf(e){return e instanceof ba||e&&typeof e==`object`&&`type`in e&&e.type===`val`}function Ff(e){return Pf(e)?e.value:e}function If(e,t){if(!e||typeof e!=`object`)return e;let n=!1;for(let r of Ds)if(e[r]==null&&r in t){n=!0;break}if(!n)return e;for(let n of Ds)e[n]==null&&n in t&&(e[n]=t[n]);return e}function Lf(e,t,n){if(e.from.type===`queryRef`&&t.from.type===`queryRef`&&(n.set(e.from.query,t.from.query),Lf(e.from.query,t.from.query,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),Lf(i.from.query,a.from.query,n))}}function Rf(e,t){if(e.from.alias===t)return e.from;for(let n of e.join||[])if(n.from.alias===t)return n.from}function zf(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 zf(e,t,n)}return{collection:n,path:[r]}}if(t.path.length>1){let[r,...i]=t.path,a=Rf(e,r);return a?a.type===`queryRef`?zf(a.query,new K(i),n):{collection:a.collection,path:i}:void 0}}}function Bf(e){let t=[];for(let[n,r]of Object.entries(e))n.startsWith(`__SPREAD_SENTINEL__`)||(r instanceof Ca?t.push({key:n,subquery:r}):Vf(r)&&Hf(r,n));return t}function Vf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.type!=`string`}function Hf(e,t){for(let[n,r]of Object.entries(e))if(!n.startsWith(`__SPREAD_SENTINEL__`)){if(r instanceof Ca)throw Error(`Includes subqueries must be at the top level of select(). Found nested includes at "${t}.${n}".`);Vf(r)&&Hf(r,`${t}.${n}`)}}function Uf(e,t){e[t]=new ba(null)}function Wf(e,t){let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}function Gf(e,t){let n=e.type;if(n===`val`)return new ba(e.value);if(n===`ref`){let n=e.path;if(Array.isArray(n)){if(n[0]===t&&n.length>1)return new K(n.slice(1));if(n.length===1&&n[0]!==void 0)return new K([n[0]])}return new K(Array.isArray(n)?n:[String(n)])}else{let n=[];for(let r of e.args){let e=Gf(r,t);n.push(e)}return new xa(e.name,n)}}function Kf(e,t){return e.map(e=>{let n=Gf(e.expression,t);return{...e,expression:n}})}var qf=new WeakMap;function Jf(e){return e.utils?.[Ju]?.getBuilder?.()}function Yf(e,t){qf.set(e,t)}function Xf(e){return qf.get(e)}var Zf=class e{constructor(e={}){this.query={},this.query={...e}}_createRefForSource(t,n){let r;try{r=Object.keys(t)}catch{throw new vo(n,t===null?`null`:`undefined`)}if(Array.isArray(t))throw new vo(n,`array`);if(r.length!==1)throw r.length===0?new vo(n,`empty object`):r.every(e=>!isNaN(Number(e)))?new vo(n,`string`):new ho(n);let i=r[0],a=t[i],o;if(a instanceof Rd)o=new va(a,i);else if(a instanceof e){let e=a._getQuery();if(!e.from)throw new go(n);o=new ya(e,i)}else throw new _o(i);return[i,o]}from(t){let[,n]=this._createRefForSource(t,`from clause`);return new e({...this.query,from:n})}join(t,n,r=`left`){let[i,a]=this._createRefForSource(t,`join clause`),o=n(Tu([...this._getCurrentAliases(),i])),s,c;if(o.type===`func`&&o.name===`eq`&&o.args.length===2)s=o.args[0],c=o.args[1];else throw new yo;let l={from:a,type:r,left:s,right:c},u=this.query.join||[];return new e({...this.query,join:[...u,l]})}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(t){let n=t(Tu(this._getCurrentAliases())),r=Du(n)?Z(n):n;if(!wa(r))throw new xo(Qf(r));let i=this.query.where||[];return new e({...this.query,where:[...i,r]})}having(t){let n=this._getCurrentAliases(),r=t(this.query.select||this.query.fnSelect?Eu(n):Tu(n)),i=Du(r)?Z(r):r;if(!wa(i))throw new xo(Qf(i));let a=this.query.having||[];return new e({...this.query,having:[...a,i]})}select(t){let n=this._getCurrentAliases(),r=t(Tu(n));Du(r)&&r.__path.length===1&&(r={[`__SPREAD_SENTINEL__${r.__path[0]}__0`]:!0});let i=tp(r,n);return new e({...this.query,select:i,fnSelect:void 0})}orderBy(t,n=`asc`){let r=this._getCurrentAliases(),i=t(this.query.select||this.query.fnSelect?Eu(r):Tu(r)),a=typeof n==`string`?{direction:n,nulls:`first`}:{direction:n.direction??`asc`,nulls:n.nulls??`first`,stringSort:n.stringSort,locale:n.stringSort===`locale`?n.locale:void 0,localeOptions:n.stringSort===`locale`?n.localeOptions:void 0},o=e=>({expression:Z(e),compareOptions:a}),s=Array.isArray(i)?i.map(e=>o(e)):[o(i)],c=this.query.orderBy||[];return new e({...this.query,orderBy:[...c,...s]})}groupBy(t){let n=t(Tu(this._getCurrentAliases())),r=Array.isArray(n)?n.map(e=>Z(e)):[Z(n)],i=this.query.groupBy||[];return new e({...this.query,groupBy:[...i,...r]})}limit(t){return new e({...this.query,limit:t})}offset(t){return new e({...this.query,offset:t})}distinct(){return new e({...this.query,distinct:!0})}findOne(){return new e({...this.query,singleResult:!0})}_getCurrentAliases(){let e=[];if(this.query.from&&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 t=this;return{select(n){return new e({...t.query,select:void 0,fnSelect:n})},where(n){return new e({...t.query,fnWhere:[...t.query.fnWhere||[],n]})},having(n){return new e({...t.query,fnHaving:[...t.query.fnHaving||[],n]})}}}_getQuery(){if(!this.query.from)throw new bo;return this.query}};function Qf(e){return e===null?`null`:e===void 0?`undefined`:typeof e==`object`?`object`:typeof e}function $f(e){return e===void 0?Z(null):e instanceof Sa||e instanceof xa||e instanceof K||e instanceof ba?e:Z(e)}function ep(e){return typeof e==`object`&&!!e&&!wa(e)&&!e.__refProxy}function tp(e,t=[]){if(!ep(e))return $f(e);let n={};for(let[r,i]of Object.entries(e)){if(typeof r==`string`&&r.startsWith(`__SPREAD_SENTINEL__`)){n[r]=i;continue}if(i instanceof Zf){n[r]=ip(i,r,t,`collection`);continue}if(i instanceof Fu){if(!(i.query instanceof Zf))throw Error(`toArray() must wrap a subquery builder`);n[r]=ip(i.query,r,t,`array`);continue}if(i instanceof Iu){if(!(i.query instanceof Zf))throw Error(`concat(toArray(...)) must wrap a subquery builder`);n[r]=ip(i.query,r,t,`concat`);continue}n[r]=tp(i,t)}return n}function np(e){let t=[];switch(e.type){case`ref`:t.push(e);break;case`func`:for(let n of e.args??[])t.push(...np(n));break}return t}function rp(e,t){return np(typeof e==`object`&&`expression`in e?e.expression:e).some(e=>e.path[0]!=null&&t.includes(e.path[0]))}function ip(e,t,n,r){let i=e._getQuery(),a=[i.from.alias];if(i.join)for(let e of i.join)a.push(e.from.alias);let o,s,c=-1,l=-1;if(i.where)for(let e=0;e<i.where.length;e++){let t=i.where[e],r=typeof t==`object`&&`expression`in t?t.expression:t;if(r.type===`func`&&r.name===`eq`&&r.args.length===2){let t=ap(r.args[0],r.args[1],n,a);if(t){o=t.parentRef,s=t.childRef,c=e;break}}if(r.type===`func`&&r.name===`and`&&r.args.length>=2){for(let t=0;t<r.args.length;t++){let i=r.args[t];if(i.type===`func`&&i.name===`eq`&&i.args.length===2){let r=ap(i.args[0],i.args[1],n,a);if(r){o=r.parentRef,s=r.childRef,c=e,l=t;break}}}if(o)break}}if(!o||!s||c===-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 u=[...i.where];if(l>=0){let e=u[c],t=(typeof e==`object`&&`expression`in e?e.expression:e).args.filter((e,t)=>t!==l);if(t.length===1)u[c]=typeof e==`object`&&`expression`in e&&e.residual?{expression:t[0],residual:!0}:t[0];else{let n=new xa(`and`,t);u[c]=typeof e==`object`&&`expression`in e&&e.residual?{expression:n,residual:!0}:n}}else u.splice(c,1);let d=[],f=[];for(let e of u)rp(e,n)?f.push(e):d.push(e);let p;if(f.length>0){let e=new Set;p=[];for(let t of f){let r=typeof t==`object`&&`expression`in t?t.expression:t;for(let t of np(r))t.path[0]!=null&&n.includes(t.path[0])&&!e.has(t.path.join(`.`))&&(e.add(t.path.join(`.`)),p.push(t))}}let m={...i,where:d.length>0?d:void 0},h=m.select,g=h===void 0||ep(h),_=m,v;if(r===`concat`&&(h===void 0||g))throw Error(`concat(toArray(...)) for "${t}" requires the subquery to select a scalar value`);if(!g){if(r===`collection`)throw Error(`Includes subquery for "${t}" must select an object when materializing as a Collection`);v=ga,_={...m,select:{[v]:h}}}return new Ca(_,o,s,t,f.length>0?f:void 0,p,r,v)}function ap(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 op(e){return sp(e(new Zf))}function sp(e){return e._getQuery()}function cp(e){let t={};function n(e){e.type===`collectionRef`?t[e.collection.id]=e.collection:e.type===`queryRef`&&r(e.query)}function r(e){if(e.from&&n(e.from),e.join&&Array.isArray(e.join))for(let t of e.join)t.from&&n(t.from);e.select&&i(e.select)}function i(e){for(let[t,n]of Object.entries(e))typeof t==`string`&&t.startsWith(`__SPREAD_SENTINEL__`)||(n instanceof Ca?r(n.query):dp(n)&&i(n))}return r(e),t}function lp(e){let t=e.from;if(t.type===`collectionRef`)return t.collection;if(t.type===`queryRef`)return lp(t.query);throw Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(e)}`)}function up(e){let t=new Map;function n(e){if(e)if(e.type===`collectionRef`){let{id:n}=e.collection,r=t.get(n);r?r.add(e.alias):t.set(n,new Set([e.alias]))}else e.type===`queryRef`&&i(e.query)}function r(e){for(let[t,n]of Object.entries(e))typeof t==`string`&&t.startsWith(`__SPREAD_SENTINEL__`)||(n instanceof Ca?i(n.query):dp(n)&&r(n))}function i(e){if(e){if(n(e.from),e.join)for(let t of e.join)n(t.from);e.select&&r(e.select)}}return i(e),t}function dp(e){return!(typeof e!=`object`||!e||e instanceof Ca||`type`in e&&typeof e.type==`string`||e.__refProxy)}function fp(e){let t=typeof e.query==`function`?op(e.query):sp(e.query);if(e.requireObjectResult&&t.select&&!dp(t.select))throw new To;return t}function pp(e,t,n){let r=[];for(let e of t){let t=n(e.value);e.type===`insert`?r.push([[t,e.value],1]):e.type===`update`?(r.push([[t,e.previousValue],-1]),r.push([[t,e.value],1])):r.push([[t,e.value],-1])}return r.length!==0&&e.sendData(new Bc(r)),r.length}function*mp(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 hp(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 gp(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 _p(e,t){let{orderBy:n,limit:r,offset:i}=e,a=r!==void 0&&i!==void 0?r+i:r,o=n?Kf(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 vp(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=nc({minValues:l??null,offset:s,limit:i});if(n===u)return;let d=Kf(a,r);return{minValues:l,normalizedOrderBy:d,loadRequestKey:u}}var yp=Symbol.for(`@tanstack/db.collection-config-builder`),bp=class{constructor(e,t,n,r){this.alias=e,this.collectionId=t,this.collection=n,this.collectionConfigBuilder=r,this.biggest=void 0,this.subscriptionLoadingPromises=new Map,this.sentToD2Keys=new Set}subscribe(){let e=this.getWhereClauseForAlias();if(e){let t=Gf(e,this.alias);return this.subscribeToChanges(t)}return this.subscribeToChanges()}subscribeToChanges(e){let t=this.getOrderByInfo(),n=e=>{e instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(e)},r=e=>{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())}},i;if(t)i=this.subscribeToOrderedChanges(e,t,r,n);else{let t=!this.collectionConfigBuilder.isLazyAlias(this.alias);i=this.subscribeToMatchingChanges(e,t,r)}return i.status===`loadingSubset`&&this.ensureLoadingPromise(i),this.collectionConfigBuilder.currentSyncState.unsubscribeCallbacks.add(()=>{let e=this.subscriptionLoadingPromises.get(i);e&&(this.subscriptionLoadingPromises.delete(i),e.resolve()),i.unsubscribe()}),i}sendChangesToPipeline(e,t){let n=hp(Array.isArray(e)?e:[...e],this.sentToD2Keys),r=this.collectionConfigBuilder.currentSyncState.inputs[this.alias],i=pp(r,n,this.collection.config.getKey)>0?t:void 0;this.collectionConfigBuilder.scheduleGraphRun(i,{alias:this.alias})}subscribeToMatchingChanges(e,t,n){let r=e=>{this.sendChangesToPipeline(e)},i=_p(this.collectionConfigBuilder.query,this.alias),a=t?e=>{e instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(e)}:void 0;return this.collection.subscribeChanges(r,{...t&&{includeInitialState:t},whereExpression:e,onStatusChange:n,orderBy:i.orderBy,limit:i.limit,onLoadSubsetResult:a})}subscribeToOrderedChanges(e,t,n,r){let{orderBy:i,offset:a,limit:o,index:s}=t,c=e=>{e instanceof Promise&&(this.pendingOrderedLoadPromise=e,e.finally(()=>{this.pendingOrderedLoadPromise===e&&(this.pendingOrderedLoadPromise=void 0)})),r(e)};this.orderedLoadSubsetResult=c;let l={},u=this.collection.subscribeChanges(e=>{let n=Array.isArray(e)?e:[...e];this.trackSentValues(n,t.comparator);let r=mp(n);this.sendChangesToPipelineWithTracking(r,l.current)},{whereExpression:e,onStatusChange:n});l.current=u;let d=this.collection.on(`truncate`,()=>{this.biggest=void 0,this.lastLoadRequestKey=void 0,this.pendingOrderedLoadPromise=void 0,this.sentToD2Keys.clear()});u.on(`unsubscribed`,()=>{d()});let f=Kf(i,this.alias);return s?(u.setOrderByIndex(s),u.requestLimitedSnapshot({limit:a+o,orderBy:f,trackLoadSubsetPromise:!1,onLoadSubsetResult:c})):u.requestSnapshot({orderBy:f,limit:a+o,trackLoadSubsetPromise:!1,onLoadSubsetResult:c}),u}loadMoreIfNeeded(e){let t=this.getOrderByInfo();if(!t)return!0;let{dataNeeded:n,index:r}=t;if(!n||!r||this.pendingOrderedLoadPromise)return!0;let i=n();return i>0&&this.loadNextItems(i,e),!0}sendChangesToPipelineWithTracking(e,t){if(!this.getOrderByInfo()){this.sendChangesToPipeline(e);return}let n=t;n[yp]??=this.loadMoreIfNeeded.bind(this,t),this.sendChangesToPipeline(e,n[yp])}loadNextItems(e,t){let n=this.getOrderByInfo();if(!n)return;let r=vp(n,this.biggest,this.lastLoadRequestKey,this.alias,e);r&&(this.lastLoadRequestKey=r.loadRequestKey,t.requestLimitedSnapshot({orderBy:r.normalizedOrderBy,limit:e,minValues:r.minValues,trackLoadSubsetPromise:!1,onLoadSubsetResult:this.orderedLoadSubsetResult}))}getWhereClauseForAlias(){let e=this.collectionConfigBuilder.sourceWhereClausesCache;if(e)return e.get(this.alias)}getOrderByInfo(){let e=this.collectionConfigBuilder.optimizableOrderByCollections[this.collectionId];if(e&&e.alias===this.alias)return e}trackSentValues(e,t){let n=gp(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.liveQueryCollection._sync.trackLoadPromise(n)}},xp=0,Sp=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.aliasDependencies={},this.builderDependencies=new Set,this.pendingGraphRuns=new Map,this.subscriptions={},this.lazySourcesCallbacks={},this.lazySources=new Set,this.optimizableOrderByCollections={},this.id=e.id||`live-query-${++xp}`,this.query=fp({query:e.query,requireObjectResult:!0}),this.collections=cp(this.query);let t=up(this.query);this.collectionByAlias={};for(let[e,n]of t.entries()){let t=this.collections[e];if(t)for(let e of n)this.collectionByAlias[e]=t}this.query.orderBy&&this.query.orderBy.length>0&&(this.compare=Cp(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??lp(this.query).compareOptions,this.compileBasePipeline()}hasJoins(e){return!!(e.join&&e.join.length>0||e.from.type===`queryRef`&&this.hasJoins(e.from.query))}getConfig(){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),setWindow:this.setWindow.bind(this),getWindow:this.getWindow.bind(this),[Ju]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(e){if(!this.windowFn)throw new $o;return this.currentWindow=e,this.windowFn(e),this.maybeRunGraphFn?.(),this.liveQueryCollection?.isLoadingSubset?new Promise(e=>{let t=this.liveQueryCollection.on(`loadingSubset:change`,n=>{n.isLoadingSubset||(t(),e())})}):!0}getWindow(){if(!(!this.windowFn||!this.currentWindow))return{offset:this.currentWindow.offset??0,limit:this.currentWindow.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}"`)}isLazyAlias(e){return this.lazySources.has(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(),r.flushPendingChanges?.(),e?.(),i=!0;i||e?.(),r.messagesCount===0&&(t(),n()),this.updateLiveQueryStatus(this.currentSyncConfig)}}finally{this.isGraphRunning=!1}}}scheduleGraphRun(e,t){let n=t?.contextId??Ad()?.id,r=t?.jobId??this,i=(()=>{if(t?.dependencies)return t.dependencies;let e=new Set(this.builderDependencies);if(t?.alias){let n=this.aliasDependencies[t.alias];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;wd.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.currentSyncConfig=e;let t={messagesCount:0,subscribedToAllCollections:!1,unsubscribeCallbacks:new Set},n=this.extendPipelineWithChangeProcessing(e,t);this.currentSyncState=n,this.unsubscribeFromSchedulerClears=wd.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);return this.maybeRunGraphFn=()=>this.scheduleGraphRun(i),this.scheduleGraphRun(i),()=>{t.unsubscribeCallbacks.forEach(e=>e()),this.currentSyncConfig=void 0,this.currentSyncState=void 0,this.pendingGraphRuns.clear(),this.graphCache=void 0,this.inputsCache=void 0,this.pipelineCache=void 0,this.sourceWhereClausesCache=void 0,this.includesCache=void 0,this.lazySources.clear(),this.optimizableOrderByCollections={},this.lazySourcesCallbacks={},Object.keys(this.subscriptions).forEach(e=>delete this.subscriptions[e]),this.compiledAliasToCollectionId={},this.unsubscribeFromSchedulerClears?.(),this.unsubscribeFromSchedulerClears=void 0}}compileBasePipeline(){this.graphCache=new qc,this.inputsCache=Object.fromEntries(Object.keys(this.collectionByAlias).map(e=>[e,this.graphCache.newInput()]));let e=Af(this.query,this.inputsCache,this.collections,this.subscriptions,this.lazySourcesCallbacks,this.lazySources,this.optimizableOrderByCollections,e=>{this.windowFn=e});this.pipelineCache=e.pipeline,this.sourceWhereClausesCache=e.sourceWhereClauses,this.compiledAliasToCollectionId=e.aliasToCollectionId,this.includesCache=e.includes;let t=Object.keys(this.compiledAliasToCollectionId).filter(e=>!Object.hasOwn(this.inputsCache,e));if(t.length>0)throw new Qo(t)}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(Nl(e=>{let n=e.getInner();t.messagesCount+=n.length,n.reduce(Lp,s)}));let c=this.setupIncludesOutput(this.includesCache,t);return t.flushPendingChanges=()=>{let t=s.size>0,i=Fp(c);if(!t&&!i)return;let a=s;if(this.config.getKey){let e=new Map;for(let[,t]of s){let n=this.config.getKey(t.value),r=e.get(n);r?(r.inserts+=t.inserts,r.deletes+=t.deletes,t.inserts>0&&(r.value=t.value,t.orderByIndex!==void 0&&(r.orderByIndex=t.orderByIndex))):e.set(n,{...t})}a=e}t&&(n(),a.forEach(this.applyChanges.bind(this,e)),r()),s=new Map,Pp(c,e.collection,this.id,t?a:null,e)},i.finalize(),t.graph=i,t.inputs=a,t.pipeline=o,t}setupIncludesOutput(e,t){return!e||e.length===0?[]:e.map(e=>{let n={fieldName:e.fieldName,childCorrelationField:e.childCorrelationField,hasOrderBy:e.hasOrderBy,materialization:e.materialization,scalarField:e.scalarField,childRegistry:new Map,pendingChildChanges:new Map,correlationToParentKeys:new Map};return e.pipeline.pipe(Nl(e=>{let r=e.getInner();t.messagesCount+=r.length;for(let[[e,t],i]of r){let[r,a,o,s]=t,c=Mp(o,s),l=n.pendingChildChanges.get(c);l||(l=new Map,n.pendingChildChanges.set(c,l));let u=l.get(e)||{deletes:0,inserts:0,value:r,orderByIndex:a};i<0?u.deletes+=Math.abs(i):i>0&&(u.inserts+=i,u.value=r),l.set(e,u)}})),e.childCompilationResult.includes&&(n.nestedSetups=Ep(e.childCompilationResult.includes,t),n.nestedRoutingIndex=new Map,n.nestedRoutingReverseIndex=new Map),n})}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){let{status:r}=n;if(r===`error`){this.transitionToError(`Source collection '${t}' entered error state`);return}if(r===`cleaned-up`){this.transitionToError(`Source collection '${t}' 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}this.updateLiveQueryStatus(e)}updateLiveQueryStatus(e){let{markReady:t}=e;if(this.isInErrorState)return;let n=this.currentSyncState?.subscribedToAllCollections,r=this.allCollectionsReady(),i=this.liveQueryCollection?.isLoadingSubset;n&&r&&!i&&t()}transitionToError(e){this.isInErrorState=!0,console.error(`[Live Query Error] ${e}`),this.liveQueryCollection?._lifecycle.setStatus(`error`)}allCollectionsReady(){return Object.values(this.collections).every(e=>e.isReady())}subscribeToAllCollections(e,t){let n=Object.entries(this.compiledAliasToCollectionId);if(n.length===0)throw Error(`Compiler returned no alias metadata for query '${this.id}'. This should not happen; please report.`);let r=n.map(([n,r])=>{let i=this.collectionByAlias[n]??this.collections[r],a=Xf(i);a&&a!==this?(this.aliasDependencies[n]=[a],this.builderDependencies.add(a)):this.aliasDependencies[n]=[];let o=new bp(n,r,i,this),s=i.on(`status:change`,t=>{this.handleSourceStatusChange(e,r,t)});t.unsubscribeCallbacks.add(s);let c=o.subscribe();return this.subscriptions[n]=c,o.loadMoreIfNeeded.bind(o,c)});return t.subscribedToAllCollections=!0,()=>(r.map(e=>e()),!0)}};function Cp(e){return(t,n)=>{let r=e.get(t),i=e.get(n);return r&&i?r<i?-1:+(r>i):0}}function wp(e){return e.materialization!==`collection`}function Tp(e,t){if(!t)return e.materialization===`array`?[]:e.materialization===`concat`?``:void 0;if(e.materialization===`collection`)return t.collection;let n=[...t.collection.toArray],r=e.scalarField?n.map(t=>t?.[e.scalarField]):n;return e.materialization===`array`?r:r.map(e=>String(e??``)).join(``)}function Ep(e,t){return e.map(e=>{let n=new Map;e.pipeline.pipe(Nl(e=>{let r=e.getInner();t.messagesCount+=r.length;for(let[[e,t],i]of r){let[r,a,o,s]=t,c=Mp(o,s),l=n.get(c);l||(l=new Map,n.set(c,l));let u=l.get(e)||{deletes:0,inserts:0,value:r,orderByIndex:a};i<0?u.deletes+=Math.abs(i):i>0&&(u.inserts+=i,u.value=r),l.set(e,u)}}));let r={compilationResult:e,buffer:n};return e.childCompilationResult.includes&&(r.nestedSetups=Ep(e.childCompilationResult.includes,t)),r})}function Dp(e){return e.map(e=>{let t={fieldName:e.compilationResult.fieldName,childCorrelationField:e.compilationResult.childCorrelationField,hasOrderBy:e.compilationResult.hasOrderBy,materialization:e.compilationResult.materialization,scalarField:e.compilationResult.scalarField,childRegistry:new Map,pendingChildChanges:new Map,correlationToParentKeys:new Map};return e.nestedSetups&&(t.nestedSetups=e.nestedSetups,t.nestedRoutingIndex=new Map,t.nestedRoutingReverseIndex=new Map),t})}function Op(e){let t=new Set;if(!e.nestedSetups)return t;for(let n=0;n<e.nestedSetups.length;n++){let r=e.nestedSetups[n],i=[];for(let[a,o]of r.buffer){let r=e.nestedRoutingIndex.get(a);if(r===void 0)continue;let s=e.childRegistry.get(r);if(!s||!s.includesStates)continue;let c=s.includesStates[n];for(let[e,t]of o){let n=c.pendingChildChanges.get(a);n||(n=new Map,c.pendingChildChanges.set(a,n));let r=n.get(e);r?(r.inserts+=t.inserts,r.deletes+=t.deletes,t.inserts>0&&(r.value=t.value,t.orderByIndex!==void 0&&(r.orderByIndex=t.orderByIndex))):n.set(e,{...t})}t.add(r),i.push(a)}for(let e of i)r.buffer.delete(e)}return t}function kp(e,t,n){if(e.nestedSetups){for(let r of e.nestedSetups)for(let[,i]of n)if(i.inserts>0){let n=i.value[kf]?.[r.compilationResult.fieldName],a=n?.correlationKey,o=Mp(a,n?.parentContext??null);if(a!=null){e.nestedRoutingIndex.set(o,t);let n=e.nestedRoutingReverseIndex.get(t);n||(n=new Set,e.nestedRoutingReverseIndex.set(t,n)),n.add(o)}}else if(i.deletes>0&&i.inserts===0){let n=i.value[kf]?.[r.compilationResult.fieldName],a=n?.correlationKey,o=Mp(a,n?.parentContext??null);if(a!=null){e.nestedRoutingIndex.delete(o);let n=e.nestedRoutingReverseIndex.get(t);n&&(n.delete(o),n.size===0&&e.nestedRoutingReverseIndex.delete(t))}}}}function Ap(e,t){if(!e.nestedRoutingReverseIndex)return;let n=e.nestedRoutingReverseIndex.get(t);if(n){for(let t of n)e.nestedRoutingIndex.delete(t);e.nestedRoutingReverseIndex.delete(t)}}function jp(e){for(let t of e)if(t.buffer.size>0||t.nestedSetups&&jp(t.nestedSetups))return!0;return!1}function Mp(e,t){return t==null?e:JSON.stringify([e,t])}function Np(e,t,n,r,i){let a=new WeakMap,o=r?new WeakMap:null,s=null,c=o?Cp(o):void 0,l={collection:Ld({id:`__child-collection:${e}-${t}-${nc(n)}`,getKey:e=>a.get(e),compare:c,sync:{rowUpdateMode:`full`,sync:e=>(s=e,()=>{s=null})},startSync:!0,gcTime:0}),get syncMethods(){return s},resultKeys:a,orderByIndices:o};return i&&(l.includesStates=Dp(i)),l}function Pp(e,t,n,r,i){for(let a of e){if(r){for(let[e,i]of r)if(i.inserts>0){let r=i.value,o=r[kf]?.[a.fieldName],s=o?.correlationKey,c=Mp(s,o?.parentContext??null);if(s!=null){if(!a.childRegistry.has(c)){let e=Np(n,a.fieldName,c,a.hasOrderBy,a.nestedSetups);a.childRegistry.set(c,e)}let i=a.correlationToParentKeys.get(c);i||(i=new Set,a.correlationToParentKeys.set(c,i)),i.add(e);let o=Tp(a,a.childRegistry.get(c));r[a.fieldName]=o;let s=t.get(e);s&&s!==r&&(s[a.fieldName]=o)}}}let e=wp(a)?new Set(a.pendingChildChanges.keys()):null,o=new Map;if(a.pendingChildChanges.size>0){for(let[e,r]of a.pendingChildChanges){let i=a.childRegistry.get(e);if(i||(i=Np(n,a.fieldName,e,a.hasOrderBy,a.nestedSetups),a.childRegistry.set(e,i)),a.materialization===`collection`&&Ip(t,a.fieldName,e,a.correlationToParentKeys,i.collection),i.syncMethods){i.syncMethods.begin();for(let[e,t]of r)i.resultKeys.set(t.value,e),i.orderByIndices&&t.orderByIndex!==void 0&&i.orderByIndices.set(t.value,t.orderByIndex),t.inserts>0&&t.deletes===0?i.syncMethods.write({value:t.value,type:`insert`}):t.inserts>t.deletes||t.inserts===t.deletes&&i.syncMethods.collection.has(i.syncMethods.collection.getKeyFromItem(t.value))?i.syncMethods.write({value:t.value,type:`update`}):t.deletes>0&&i.syncMethods.write({value:t.value,type:`delete`});i.syncMethods.commit()}kp(a,e,r),o.set(e,{entry:i,childChanges:r})}a.pendingChildChanges.clear()}let s=Op(a);for(let[,{entry:e,childChanges:t}]of o)e.includesStates&&Pp(e.includesStates,e.collection,e.collection.id,t,e.syncMethods);for(let e of s){if(o.has(e))continue;let t=a.childRegistry.get(e);t?.includesStates&&Pp(t.includesStates,t.collection,t.collection.id,null,t.syncMethods)}let c=new Set;if(a.nestedSetups)for(let[e,t]of a.childRegistry)o.has(e)||s.has(e)||t.includesStates&&Fp(t.includesStates)&&(Pp(t.includesStates,t.collection,t.collection.id,null,t.syncMethods),c.add(e));let l=wp(a)?new Set([...e||[],...s,...c]):null;if(i&&l&&l.size>0){let e=[];for(let n of l){let r=a.correlationToParentKeys.get(n);if(!r)continue;let o=a.childRegistry.get(n);for(let n of r){let r=t.get(n);if(r){let t=i.collection.getKeyFromItem(r),n={...r};r[a.fieldName]=Tp(a,o),e.push({type:`update`,key:t,value:r,previousValue:n})}}}e.length>0&&t._changes.emitEvents(e,!0)}if(r){for(let[e,t]of r)if(t.deletes>0&&t.inserts===0){let n=t.value[kf]?.[a.fieldName],r=n?.correlationKey,i=Mp(r,n?.parentContext??null);if(r!=null){let t=a.correlationToParentKeys.get(i);t&&(t.delete(e),t.size===0&&(Ap(a,i),a.childRegistry.delete(i),a.correlationToParentKeys.delete(i)))}}}}if(r)for(let[,e]of r)delete e.value[kf]}function Fp(e){for(let t of e)if(t.pendingChildChanges.size>0||t.nestedSetups&&jp(t.nestedSetups))return!0;return!1}function Ip(e,t,n,r,i){let a=r.get(n);if(a)for(let n of a){let r=e.get(n);r&&(r[t]=i)}}function Lp(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):r>0&&(o.inserts+=r,o.value=i,a!==void 0&&(o.orderByIndex=a)),e.set(t,o),e}function Rp(e){return new Sp(e).getConfig()}function zp(e){if(typeof e==`function`)return Bp(Rp({query:e}));{let t=e,n=Rp(t);return t.utils&&(n.utils={...n.utils,...t.utils}),Bp(n)}}function Bp(e){let t=Ld(e),n=Jf(e);return n&&Yf(t,n),t}var Vp=1;function Hp(e,t=[]){let n=e&&typeof e==`object`&&typeof e.subscribeChanges==`function`&&typeof e.startSyncImmediate==`function`&&typeof e.id==`string`,r=(0,v.useRef)(null),i=(0,v.useRef)(null),a=(0,v.useRef)(null),o=(0,v.useRef)(0),s=(0,v.useRef)(null),c=!r.current||n&&a.current!==e||!n&&(i.current===null||i.current.length!==t.length||i.current.some((e,n)=>e!==t[n]));if(c)if(n)e.config?.syncMode===`on-demand`&&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.
15
+
16
+ Instead, use a query builder function:
17
+ const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))
18
+
19
+ Or switch to syncMode "eager" if you want all data to sync automatically.`),e.startSyncImmediate(),r.current=e,a.current=e;else if(typeof e==`function`){let n=e(new Zf);if(n==null)r.current=null;else if(n instanceof Rd)n.startSyncImmediate(),r.current=n;else if(n instanceof Zf)r.current=zp({query:e,startSync:!0,gcTime:Vp});else if(n&&typeof n==`object`)r.current=zp({startSync:!0,gcTime:Vp,...n});else throw Error(`useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof n}`);i.current=[...t]}else r.current=zp({startSync:!0,gcTime:Vp,...e}),i.current=[...t];c&&(o.current=0,s.current=null);let l=(0,v.useRef)(null);(!l.current||c)&&(l.current=e=>{if(!r.current)return()=>{};let t=r.current.subscribeChanges(()=>{o.current+=1,e()});return r.current.status===`ready`&&(o.current+=1,e()),()=>{t.unsubscribe()}});let u=(0,v.useRef)(null);(!u.current||c)&&(u.current=()=>{let e=o.current,t=r.current;return(!s.current||s.current.version!==e||s.current.collection!==t)&&(s.current={collection:t,version:e}),s.current});let d=(0,v.useSyncExternalStore)(l.current,u.current),f=(0,v.useRef)(null),p=(0,v.useRef)(null);if(!f.current||f.current.version!==d.version||f.current.collection!==d.collection){if(!d.collection)p.current={state:void 0,data:void 0,collection:void 0,status:`disabled`,isLoading:!1,isReady:!0,isIdle:!1,isError:!1,isCleanedUp:!1,isEnabled:!1};else{let e=Array.from(d.collection.entries()),t=d.collection.config.singleResult,n=null,r=null;p.current={get state(){return n||=new Map(e),n},get data(){return r||=e.map(([,e])=>e),t?r[0]:r},collection:d.collection,status:d.collection.status,isLoading:d.collection.status===`loading`,isReady:d.collection.status===`ready`,isIdle:d.collection.status===`idle`,isError:d.collection.status===`error`,isCleanedUp:d.collection.status===`cleaned-up`,isEnabled:!0}}f.current=d}return p.current}var Up=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Wp=new class extends Up{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},Gp={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Kp=new class{#e=Gp;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function qp(e){setTimeout(e,0)}var Jp=typeof window>`u`||`Deno`in globalThis;function Yp(){}function Xp(e,t){return typeof e==`function`?e(t):e}function Zp(e){return typeof e==`number`&&e>=0&&e!==1/0}function Qp(e,t){return Math.max(e+(t||0)-Date.now(),0)}function $p(e,t){return typeof e==`function`?e(t):e}function em(e,t){return typeof e==`function`?e(t):e}function tm(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==rm(o,t.options))return!1}else if(!am(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function nm(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(im(t.options.mutationKey)!==im(a))return!1}else if(!am(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function rm(e,t){return(t?.queryKeyHashFn||im)(e)}function im(e){return JSON.stringify(e,(e,t)=>um(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function am(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>am(e[n],t[n])):!1}var om=Object.prototype.hasOwnProperty;function sm(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=lm(e)&&lm(t);if(!r&&!(um(e)&&um(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:om.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=sm(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function cm(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function lm(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function um(e){if(!dm(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!dm(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function dm(e){return Object.prototype.toString.call(e)===`[object Object]`}function fm(e){return new Promise(t=>{Kp.setTimeout(t,e)})}function pm(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:sm(e,t)}function mm(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function hm(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var gm=Symbol();function _m(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===gm?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function vm(e,t,n){let r=!1,i;return Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ym=(()=>{let e=()=>Jp;return{isServer(){return e()},setIsServer(t){e=t}}})();function bm(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var xm=qp;function Sm(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=xm,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var $=Sm(),Cm=new class extends Up{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function wm(e){return Math.min(1e3*2**e,3e4)}function Tm(e){return(e??`online`)===`online`?Cm.isOnline():!0}var Em=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Dm(e){let t=!1,n=0,r,i=bm(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new Em(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>Wp.isFocused()&&(e.networkMode===`always`||Cm.isOnline())&&e.canRun(),u=()=>Tm(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(ym.isServer()?0:3),o=e.retryDelay??wm,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),fm(s).then(()=>l()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var Om=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Zp(this.gcTime)&&(this.#e=Kp.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ym.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(Kp.clearTimeout(this.#e),this.#e=void 0)}};function km(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{vm(e,()=>t.signal,()=>n=!0)},u=_m(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=await u((()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})()),{maxPages:o}=t.options,s=i?hm:mm;return{pages:s(e.pages,a,o),pageParams:s(e.pageParams,r,o)}};if(i&&a.length){let e=i===`backward`,t=e?jm:Am,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:Am(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function Am(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function jm(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Mm=class extends Om{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Fm(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Fm(this.options);e.data!==void 0&&(this.setState(Pm(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=pm(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(Yp).catch(Yp):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>em(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===gm||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>$p(e.options.staleTime,this)===`static`):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!Qp(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=_m(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?km(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=Dm({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Em&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Em){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Nm(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Pm(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),$.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Nm(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Tm(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Pm(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Fm(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Im=class extends Up{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=bm(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Rm(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zm(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zm(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=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 em(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),t._defaulted&&!cm(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Bm(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||em(this.options.enabled,this.#t)!==em(t.enabled,this.#t)||$p(this.options.staleTime,this.#t)!==$p(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||em(this.options.enabled,this.#t)!==em(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Hm(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.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);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Yp)),t}#g(){this.#b();let e=$p(this.options.staleTime,this.#t);if(ym.isServer()||this.#r.isStale||!Zp(e))return;let t=Qp(this.#r.dataUpdatedAt,e)+1;this.#d=Kp.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.#p=e,!(ym.isServer()||em(this.options.enabled,this.#t)===!1||!Zp(this.#p)||this.#p===0)&&(this.#f=Kp.setInterval(()=>{(this.options.refetchIntervalInBackground||Wp.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(Kp.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(Kp.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Rm(e,t),o=i&&Bm(e,n,t,r);(a||o)&&(l={...l,...Nm(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=pm(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=pm(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Vm(e,t),refetch:this.refetch,promise:this.#o,isEnabled:em(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=bm())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!cm(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);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)})})()}))}#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()}#C(e){$.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function Lm(e,t){return em(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&em(t.retryOnMount,e)===!1)}function Rm(e,t){return Lm(e,t)||e.state.data!==void 0&&zm(e,t,t.refetchOnMount)}function zm(e,t,n){if(em(t.enabled,e)!==!1&&$p(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&Vm(e,t)}return!1}function Bm(e,t,n,r){return(e!==t||em(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Vm(e,n)}function Vm(e,t){return em(t.enabled,e)!==!1&&e.isStaleByTime($p(t.staleTime,e))}function Hm(e,t){return!cm(e.getCurrentResult(),t)}var Um=class extends Om{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Wm(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=Dm({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),$.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Wm(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Gm=class extends Up{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new Um({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Km(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Km(e);if(typeof t==`string`){let n=this.#t.get(t);if(n)if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Km(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}else return!0}runNext(e){let t=Km(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){$.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>nm(t,e))}findAll(e={}){return this.getAll().filter(t=>nm(e,t))}notify(e){$.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return $.batch(()=>Promise.all(e.map(e=>e.continue().catch(Yp))))}};function Km(e){return e.options.scope?.id}var qm=class extends Up{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??rm(r,t),a=this.get(i);return a||(a=new Mm({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){$.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>tm(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>tm(e,t)):t}notify(e){$.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){$.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){$.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Jm=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new qm,this.#t=e.mutationCache||new Gm,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Wp.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=Cm.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime($p(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=Xp(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return $.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;$.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return $.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=$.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(Yp).catch(Yp)}invalidateQueries(e,t={}){return $.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=$.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(Yp)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(Yp)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime($p(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Yp).catch(Yp)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Yp).catch(Yp)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return Cm.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(im(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{am(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(im(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{am(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=rm(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===gm&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Ym=class extends ja{constructor(e){super(e),this.name=`QueryCollectionError`}},Xm=class extends Ym{constructor(){super(`[QueryCollection] queryKey must be provided.`),this.name=`QueryKeyRequiredError`}},Zm=class extends Ym{constructor(){super(`[QueryCollection] queryFn must be provided.`),this.name=`QueryFnRequiredError`}},Qm=class extends Ym{constructor(){super(`[QueryCollection] queryClient must be provided.`),this.name=`QueryClientRequiredError`}},$m=class extends Ym{constructor(){super(`[QueryCollection] getKey must be provided.`),this.name=`GetKeyRequiredError`}},eh=class extends Ym{constructor(){super(`Collection must be in 'ready' state for manual sync operations. Sync not initialized yet.`),this.name=`SyncNotInitializedError`}},th=class extends Ym{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name=`DuplicateKeyInBatchError`}},nh=class extends Ym{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name=`UpdateOperationItemNotFoundError`}},rh=class extends Ym{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name=`DeleteOperationItemNotFoundError`}},ih=new WeakMap;function ah(e,t){let n=Array.isArray(e)?e:[e],r=[];for(let e of n)if(e.type===`delete`){let t=Array.isArray(e.key)?e.key:[e.key];for(let e of t)r.push({type:`delete`,key:e})}else{let n=Array.isArray(e.data)?e.data:[e.data];for(let i of n){let n;if(e.type===`update`)n=t.getKey(i);else{let r=t.collection.validateData(i,e.type===`upsert`?`insert`:e.type);n=t.getKey(r)}r.push({type:e.type,key:n,data:i})}}return r}function oh(e,t){let n=new Set;for(let r of e){if(n.has(r.key))throw new th(r.key);if(n.add(r.key),r.type===`update`){if(!t.collection._state.syncedData.has(r.key))throw new nh(r.key)}else if(r.type===`delete`&&!t.collection._state.syncedData.has(r.key))throw new rh(r.key)}}function sh(e,t){let n=ah(e,t);oh(n,t),t.begin({immediate:!0});for(let e of n)switch(e.type){case`insert`:{let n=t.collection.validateData(e.data,`insert`);t.write({type:`insert`,value:n});break}case`update`:{let n={...t.collection._state.syncedData.get(e.key),...e.data},r=t.collection.validateData(n,`update`,e.key);t.write({type:`update`,value:r});break}case`delete`:{let n=t.collection._state.syncedData.get(e.key);t.write({type:`delete`,value:n});break}case`upsert`:{let n=t.collection._state.syncedData.has(e.key),r=t.collection.validateData(e.data,n?`update`:`insert`,e.key);n?t.write({type:`update`,value:r}):t.write({type:`insert`,value:r});break}}t.commit();let r=Array.from(t.collection._state.syncedData.values());t.updateCacheData?t.updateCacheData(r):t.queryClient.setQueryData(t.queryKey,r)}function ch(e){function t(){let t=e();if(!t)throw new eh;return t}return{writeInsert(e){let n={type:`insert`,data:e},r=t(),i=ih.get(r);if(i?.isActive){i.operations.push(n);return}sh(n,r)},writeUpdate(e){let n={type:`update`,data:e},r=t(),i=ih.get(r);if(i?.isActive){i.operations.push(n);return}sh(n,r)},writeDelete(e){let n={type:`delete`,key:e},r=t(),i=ih.get(r);if(i?.isActive){i.operations.push(n);return}sh(n,r)},writeUpsert(e){let n={type:`upsert`,data:e},r=t(),i=ih.get(r);if(i?.isActive){i.operations.push(n);return}sh(n,r)},writeBatch(e){let n=t();if(ih.get(n)?.isActive)throw Error(`Cannot nest writeBatch calls. Complete the current batch before starting a new one.`);let r={operations:[],isActive:!0};ih.set(n,r);try{let t=e();if(t&&typeof t==`object`&&`then`in t&&typeof t.then==`function`)throw Error(`writeBatch does not support async callbacks. The callback must be synchronous.`);r.operations.length>0&&sh(r.operations,n)}finally{r.isActive=!1,ih.delete(n)}}}}function lh(e){if(!e)return;let t={};return e.where&&(t.where=uh(e.where)),e.orderBy?.length&&(t.orderBy=e.orderBy.map(e=>{let t={expression:uh(e.expression),direction:e.compareOptions.direction,nulls:e.compareOptions.nulls,stringSort:e.compareOptions.stringSort};return e.compareOptions.stringSort===`locale`?{...t,locale:e.compareOptions.locale,localeOptions:e.compareOptions.localeOptions}:t})),e.limit!==void 0&&(t.limit=e.limit),e.offset!==void 0&&(t.offset=e.offset),Object.keys(t).length===0?void 0:JSON.stringify(t)}function uh(e){if(!e)return null;switch(e.type){case`val`:return{type:`val`,value:dh(e.value)};case`ref`:return{type:`ref`,path:[...e.path]};case`func`:return{type:`func`,name:e.name,args:e.args.map(e=>uh(e))};default:return null}}function dh(e){if(e===void 0)return{__type:`undefined`};if(typeof e==`number`){if(Number.isNaN(e))return{__type:`nan`};if(e===1/0)return{__type:`infinity`,sign:1};if(e===-1/0)return{__type:`infinity`,sign:-1}}return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:e instanceof Date?{__type:`date`,value:e.toJSON()}:Array.isArray(e)?e.map(e=>dh(e)):typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,dh(t)])):e}var fh=`queryCollection:gc:`,ph=class{constructor(e,t,n){this.state=e,this.refetchFn=t,this.refetch=t,this.writeInsert=n.writeInsert,this.writeUpdate=n.writeUpdate,this.writeDelete=n.writeDelete,this.writeUpsert=n.writeUpsert,this.writeBatch=n.writeBatch}async clearError(){this.state.lastError=void 0,this.state.errorCount=0,this.state.lastErrorUpdatedAt=0,await this.refetchFn({throwOnError:!0})}get lastError(){return this.state.lastError}get isError(){return!!this.state.lastError}get errorCount(){return this.state.errorCount}get isFetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isFetching)}get isRefetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isRefetching)}get isLoading(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isLoading)}get dataUpdatedAt(){return Math.max(0,...Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().dataUpdatedAt))}get fetchStatus(){return Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().fetchStatus)}};function mh(e){let{queryKey:t,queryFn:n,select:r,queryClient:i,enabled:a,refetchInterval:o,retry:s,retryDelay:c,staleTime:l,persistedGcTime:u,getKey:d,onInsert:f,onUpdate:p,onDelete:m,meta:h,...g}=e,_=g.syncMode??`eager`,v=typeof t==`function`?t({}):t,y=e=>{typeof t==`function`&&(e.length>=v.length&&v.every((t,n)=>es(t,e[n]))||console.warn(`[QueryCollection] queryKey function must return keys that extend the base key prefix. Base: ${JSON.stringify(v)}, Got: ${JSON.stringify(e)}. This can cause stale cache issues.`))};if(!t)throw new Xm;if(!n)throw new Zm;if(!i)throw new Qm;if(!d)throw new $m;let b={lastError:void 0,errorCount:0,lastErrorUpdatedAt:0,observers:new Map},x=new Map,S=new Map,C=new Map,w=new Map,T=new Map,E=(e,t)=>{let n=C.get(e)||new Set;n.add(t),C.set(e,n);let r=S.get(t)||new Set;r.add(e),S.set(t,r)},D=(e,t)=>{let n=C.get(e)||new Set;n.delete(t),C.set(e,n);let r=S.get(t)||new Set;return r.delete(e),S.set(t,r),n.size===0},O=e=>{let{begin:f,write:p,commit:m,markReady:g,collection:v,metadata:O}=e,k=O,A=!1,j=!1,M=new Set,N=new Map,P=new Map,ee=Promise.resolve(),F=e=>O?.row.get(e)??v._state.syncedMetadata.get(e),te=e=>{let t=F(e)?.queryCollection;if(!t||typeof t!=`object`)return new Set;let n=t.owners;return!n||typeof n!=`object`?new Set:new Set(Object.keys(n))},ne=(e,t)=>{if(!O)return;let n={...F(e)??{}};if(t.size===0){delete n.queryCollection,Object.keys(n).length===0?O.row.delete(e):O.row.set(e,n);return}O.row.set(e,{...n,queryCollection:{owners:Object.fromEntries(Array.from(t.values()).map(e=>[e,!0]))}})},re=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.queryHash===t){if(n.mode===`until-revalidated`)return{queryHash:t,mode:`until-revalidated`};if(n.mode===`ttl`&&typeof n.expiresAt==`number`&&Number.isFinite(n.expiresAt))return{queryHash:t,mode:`ttl`,expiresAt:n.expiresAt}}},ie=e=>(ee=ee.then(e,e),ee),I=e=>{let t=P.get(e);t&&(clearTimeout(t),P.delete(e))},L=e=>{let t=S.get(e);if(t)return new Set(t);let n=new Set;for(let[t]of v._state.syncedData.entries()){let r=te(t);r.size!==0&&(C.set(t,new Set(r)),r.forEach(e=>{let n=S.get(e)||new Set;n.add(t),S.set(e,n)}),r.has(e)&&n.add(t))}return n},ae=async e=>{let t=S.get(e);if(t&&Array.from(t).every(e=>v.has(e))){let e=new Map;return t.forEach(t=>{let n=v.get(t),r=C.get(t);n&&r&&e.set(t,{value:n,owners:new Set(r)})}),e}let n=k?.row.scanPersisted;if(!n){let t=new Map;return L(e).forEach(e=>{let n=v.get(e),r=C.get(e);n&&r&&t.set(e,{value:n,owners:new Set(r)})}),t}let r=new Map;return(await n()).forEach(t=>{let n=t.metadata?.queryCollection;if(!n||typeof n!=`object`)return;let i=n.owners;if(!i||typeof i!=`object`)return;let a=new Set(Object.keys(i));a.size!==0&&(C.set(t.key,new Set(a)),a.forEach(e=>{let n=S.get(e)||new Set;n.add(t.key),S.set(e,n)}),a.has(e)&&r.set(t.key,{value:t.value,owners:a}))}),r},oe=async e=>{if(!O)return;let t=await ae(e),n=[];f(),t.forEach(({value:t,owners:r},i)=>{r.delete(e),ne(i,r),D(i,e)&&n.push(t)}),n.forEach(e=>{p({type:`delete`,value:e})}),O.collection.delete(`${fh}${e}`),m()},R=e=>{if(e.mode!==`ttl`)return;I(e.queryHash);let t=Math.max(0,e.expiresAt-Date.now()),n=setTimeout(()=>{P.delete(e.queryHash),ie(async()=>{let t=O?.collection.get(`${fh}${e.queryHash}`),n=re(t,e.queryHash);!n||n.mode!==`ttl`||n.expiresAt>Date.now()||await oe(e.queryHash)})},t);P.set(e.queryHash,n)},se=async()=>{if(!O)return;let e=O.collection.list(fh),t=Date.now();for(let{key:n,value:r}of e){let e=re(r,n.slice(fh.length));e&&(e.mode===`ttl`&&e.expiresAt<=t?await oe(e.queryHash):e.mode===`ttl`&&R(e))}},z=e=>{if(typeof t==`function`)return t(e);if(_===`on-demand`){let n=lh(e);return n===void 0?t:[...t,n]}else return t},ce=O?.collection.list(fh),B=!ce||ce.length===0?(j=!0,Promise.resolve()):ie(async()=>{try{await se()}finally{j=!0}}),V=(e={},t=n)=>{if(!j)return B.then(()=>{let n=V(e,t);return n===!0?void 0:n});let r=z(e),d=im(r),f={...h,loadSubsetOptions:e},p=O?.collection.get(`${fh}${d}`);if(re(p,d)!==void 0&&M.add(d),I(d),y(r),b.observers.has(d)){T.set(d,(T.get(d)||0)+1);let e=b.observers.get(d),t=e.getCurrentResult();return t.isSuccess?!0:t.isError?Promise.reject(t.error):i.getQueryData(r)===void 0?new Promise((t,n)=>{let r=e.subscribe(e=>{queueMicrotask(()=>{e.isSuccess?(r(),t()):e.isError&&(r(),n(e.error))})})}):!0}let m=new Im(i,{queryKey:r,queryFn:t,meta:f,structuralSharing:!0,notifyOnChangeProps:`all`,...a!==void 0&&{enabled:a},...o!==void 0&&{refetchInterval:o},...s!==void 0&&{retry:s},...c!==void 0&&{retryDelay:c},...l!==void 0&&{staleTime:l}}),g=i.getQueryCache().find({queryKey:r,exact:!0})?.gcTime,_=u??g;if(x.set(d,r),b.observers.set(d,m),_===void 0?N.delete(d):N.set(d,_),T.set(d,(T.get(d)||0)+1),i.getQueryData(r)!==void 0)return(A||v.subscriberCount>0)&&pe(m,d),!0;let S=new Promise((e,t)=>{let n=m.subscribe(r=>{queueMicrotask(()=>{r.isSuccess?(n(),e()):r.isError&&(n(),t(r.error))})})});return(A||v.subscriberCount>0)&&pe(m,d),S},le=(e,t,n)=>{let i=im(e);if(v.status===`cleaned-up`)return;b.lastError=void 0,b.errorCount=0;let a=t.data,o=r?r(a):a;if(!Array.isArray(o)||o.some(e=>typeof e!=`object`)){let t=r?`@tanstack/query-db-collection: select() must return an array of objects. Got: ${typeof o} for queryKey ${JSON.stringify(e)}`:`@tanstack/query-db-collection: queryFn must return an array of objects. Got: ${typeof o} for queryKey ${JSON.stringify(e)}`;console.error(t);return}let s=new Map(v._state.syncedData.entries()),c=n!==void 0,l=c?new Set(n.keys()):L(i),u=new Map;o.forEach(e=>{let t=d(e);u.set(t,e)}),f(),O&&O.collection.delete(`${fh}${i}`),l.forEach(e=>{let t=c?n.get(e)?.value:s.get(e);if(!t)return;let r=u.get(e);if(r)es(t,r)||p({type:`update`,value:r});else{let n=te(e);n.delete(i),ne(e,n),D(e,i)&&p({type:`delete`,value:t})}}),u.forEach((e,t)=>{let n=te(t);n.has(i)||(n.add(i),ne(t,n)),E(t,i),s.has(t)||p({type:`insert`,value:e})}),m(),M.delete(i),I(i),g()},ue=async(e,t)=>{let n=await ae(im(e));v.status!==`cleaned-up`&&le(e,t,n)},de=e=>{let t=im(e);return n=>{if(n.isSuccess){if(v.deferDataRefresh){v.deferDataRefresh.then(()=>{let e=b.observers.get(t);e&&e.refetch().catch(()=>{})});return}M.has(t)?ue(e,n).catch(t=>{console.error(`[QueryCollection] Error reconciling query ${String(e)}:`,t)}):le(e,n)}else n.isError&&((n.errorUpdatedAt!==b.lastErrorUpdatedAt||n.error!==b.lastError)&&(b.lastError=n.error,b.errorCount++,b.lastErrorUpdatedAt=n.errorUpdatedAt),console.error(`[QueryCollection] Error observing query ${String(e)}:`,n.error),g())}},fe=e=>w.has(e),pe=(e,t)=>{if(!fe(t)){let n=de(x.get(t)),r=e.subscribe(n);w.set(t,r);let i=e.getCurrentResult();(i.isSuccess||i.isError)&&n(i)}},me=()=>{b.observers.forEach(pe)},he=()=>{w.forEach(e=>{e()}),w.clear()};A=!0;let ge=v.on(`subscribers:change`,({subscriberCount:e})=>{e>0?me():e===0&&he()});if(_===`eager`){let e=V({});e instanceof Promise&&e.catch(()=>{})}else j?g():B.then(()=>{g()});me(),b.observers.forEach((e,t)=>{de(x.get(t))(e.getCurrentResult())});let _e=e=>{w.get(e)?.(),w.delete(e),I(e),M.delete(e);let t=S.get(e)??new Set,n=new Map,r=[];t.forEach(t=>{let i=C.get(t);if(!i)return;let a=new Set(i);a.delete(e),n.set(t,a),a.size===0&&v.has(t)&&r.push(v.get(t))});let i=O!==void 0&&n.size>0,a=i||r.length>0;a&&f(),n.forEach((e,t)=>{e.size===0?C.delete(t):C.set(t,e),i&&ne(t,e)}),r.length>0&&r.forEach(e=>{p({type:`delete`,value:e})}),a&&m(),b.observers.delete(e),S.delete(e),x.delete(e),T.delete(e),N.delete(e)},ve=e=>{let t=T.get(e)||0,n=b.observers.get(e),r=N.get(e);if(t<=0&&(w.get(e)?.(),w.delete(e)),n?.hasListeners()??!1){T.set(e,0);return}if(t>0&&console.warn(`[cleanupQueryIfIdle] Invariant violation: refcount=${t} but no listeners. Cleaning up to prevent leak.`,{hashedQueryKey:e}),r!==void 0&&O&&k?.row.scanPersisted){f(),O.collection.set(`${fh}${e}`,{queryHash:e,mode:r===1/0?`until-revalidated`:`ttl`,...r===1/0?{}:{expiresAt:Date.now()+r}}),m(),r!==1/0&&R({queryHash:e,mode:`ttl`,expiresAt:Date.now()+r}),w.get(e)?.(),w.delete(e),b.observers.delete(e),x.delete(e),T.set(e,0);return}_e(e)},ye=e=>{_e(e)},be=i.getQueryCache().subscribe(e=>{let t=e.query.queryHash;e.type===`removed`&&x.has(t)&&ve(t)});return{loadSubset:_===`eager`?void 0:V,unloadSubset:_===`eager`?void 0:e=>{let t=im(z(e)),n=(T.get(t)||0)-1;n<=0?(T.set(t,0),ve(t)):T.set(t,n)},cleanup:async()=>{ge(),he(),P.forEach(e=>{clearTimeout(e)}),P.clear();let e=[...x.values()],t=[...b.observers.keys()];for(let e of t)ye(e);be(),await Promise.all(e.map(async e=>{await i.cancelQueries({queryKey:e,exact:!0}),i.removeQueries({queryKey:e,exact:!0})}))}}},k=async e=>{let t=[...x.values()].map(t=>b.observers.get(im(t)).refetch({throwOnError:e?.throwOnError}));return Promise.all(t)},A=(e,t)=>{r?i.setQueryData(e,e=>{if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return t;let n=r(e);if(Array.isArray(n)){for(let r of Object.keys(e))if(e[r]===n)return{...e,[r]:t}}if(Array.isArray(e.data))return{...e,data:t};if(Array.isArray(e.items))return{...e,items:t};if(Array.isArray(e.results))return{...e,results:t};for(let n of Object.keys(e))if(Array.isArray(e[n]))return{...e,[n]:t};return e}):i.setQueryData(e,t)},j=e=>{let t=i.getQueryCache().findAll({queryKey:v});if(t.length>0)for(let n of t)A(n.queryKey,e);else A(v,e)},M=null,N=e=>{let{begin:n,write:r,commit:a,collection:o}=e;return M={collection:o,queryClient:i,queryKey:typeof t==`function`?t({}):t,getKey:d,begin:n,write:r,commit:a,updateCacheData:j},O(e)},P=ch(()=>M),ee=f?async e=>{let t=await f(e)??{};return t.refetch!==!1&&await k(),t}:void 0,F=p?async e=>{let t=await p(e)??{};return t.refetch!==!1&&await k(),t}:void 0,te=m?async e=>{let t=await m(e)??{};return t.refetch!==!1&&await k(),t}:void 0,ne=new ph(b,k,P);return{...g,getKey:d,syncMode:_,sync:{sync:N},onInsert:ee,onUpdate:F,onDelete:te,utils:ne}}var hh=`/api`;async function gh(e,t){let n=await fetch(`${hh}${e}`,t);if(!n.ok)throw Error(`${n.status} ${n.statusText}`);return n.json()}function _h(e){let t=e.toString();return t?`?${t}`:``}function vh(e,t){return gh(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})}function yh(e,t){return gh(`/memories/${e}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})}function bh(e){return gh(`/memories/${e}`,{method:`DELETE`})}function xh(){return gh(`/projects`)}function Sh(e,t){return gh(`/projects/${e}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:t})})}function Ch(e,t){return vh(`/memories/${e}/projects`,{projectId:t})}function wh(e,t){return gh(`/memories/${e}/projects/${t}`,{method:`DELETE`})}function Th(){return gh(`/syntheses`)}function Eh(e){return gh(`/projects/${e}/synthesis`,{method:`POST`})}function Dh(e){return gh(`/projects/${e}/synthesis/in-flight`,{method:`DELETE`})}function Oh(e){return gh(`/projects/${e}/stats`)}function kh(e,t){return gh(`/projects/${e}/activity${t===void 0?``:`?days=${t}`}`)}function Ah(e){return gh(`/activity${e===void 0?``:`?days=${e}`}`)}function jh(e){return gh(`/memories/${e}/history`)}function Mh(e,t){return vh(`/memories/${e}/revert`,{version:t})}function Nh(e){return gh(`/projects/${e}/synthesis/history`)}function Ph(e,t){return vh(`/projects/${e}/synthesis/revert`,{version:t})}function Fh(e){return gh(`/memories/flagged-clusters${e?`?projectId=${encodeURIComponent(e)}`:``}`)}function Ih(e,t,n){return vh(`/memories/merge`,{keepId:e,dropIds:t,mergedContent:n})}function Lh(e){return vh(`/memories/delete-many`,{ids:e})}function Rh(e){return vh(`/memories/resolve-many`,{ids:e})}function zh(e){return vh(`/memories/merge-suggest`,{ids:e})}function Bh(e){let t=new URLSearchParams;return e.scope!==void 0&&t.set(`scope`,e.scope),e.type!==void 0&&t.set(`type`,e.type),e.since!==void 0&&t.set(`since`,e.since),e.limit!==void 0&&t.set(`limit`,String(e.limit)),gh(`/activity/events${_h(t)}`)}var Vh=new Jm,Hh=Ld(mh({queryKey:[`memories`],queryFn:async()=>{let e=await fetch(`/api/memories`);if(!e.ok)throw Error(`${e.status}`);return e.json()},queryClient:Vh,getKey:e=>e.id,onUpdate:async({transaction:e})=>{try{await Promise.all(e.mutations.map(e=>{let t=e.changes;return yh(e.original.id,{content:t.content,tags:t.tags,type:t.type,pinned:t.pinned})}))}catch{ea.error(`Failed to save — changes may not have been stored`)}},onDelete:async({transaction:e})=>{try{await Promise.all(e.mutations.map(e=>bh(e.original.id)))}catch{ea.error(`Failed to delete — try again`)}}})),Uh=Ld(mh({queryKey:[`syntheses`],queryFn:Th,queryClient:Vh,getKey:e=>e.id})),Wh=Ld(mh({queryKey:[`projects`],queryFn:xh,queryClient:Vh,getKey:e=>e.id,onUpdate:async({transaction:e})=>{await Promise.all(e.mutations.map(e=>{let t=e.changes;return t.name===void 0?Promise.resolve():Sh(e.original.id,t.name)}))}}));export{an as $,E as $t,Pi as A,Je as At,kn as B,_e as Bt,zh as C,vt as Ct,ea as D,$e as Dt,ha as E,ft as Et,Un as F,je as Ft,on as G,ce as Gt,gn as H,ve as Ht,In as I,Re as It,Wt as J,se as Jt,Kt as K,z as Kt,Pn as L,Fe as Lt,lr as M,Me as Mt,rr as N,ze as Nt,zi as O,Ze as Ot,er as P,Ve as Pt,Gt as Q,R as Qt,Dn as R,Ne as Rt,Eh as S,yt as St,Ou as T,pt as Tt,hn as U,ge as Ut,wn as V,ye as Vt,ln as W,xe as Wt,pn as X,oe as Xt,un as Y,te as Yt,dn as Z,F as Zt,wh as _,jt as _t,Ch as a,A as an,Xt as at,Mh as b,Ct as bt,Bh as c,b as cn,sn as ct,jh as d,m as dn,Bt as dt,ae as en,Jt as et,kh as f,f as fn,Pt as ft,yh as g,Nt as gt,Ih as h,c as hn,Ft as ht,Uh as i,w as in,Zt as it,Ii as j,Ge as jt,Fi as k,Ye as kt,Fh as l,x as ln,Vt as lt,Nh as m,o as mn,It as mt,Wh as n,N as nn,cn as nt,Lh as o,j as on,Qt as ot,Oh as p,u as pn,Mt as pt,mn as q,L as qt,Vh as r,re as rn,qt as rt,bh as s,y as sn,$t as st,Hh as t,ne as tn,Yt as tt,Ah as u,g as un,Ht as ut,Dh as v,Tt as vt,Hp as w,gt as wt,Ph as x,xt,Rh as y,Et as yt,On as z,Pe as zt};