@membank/dashboard 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +103 -3
- package/dist/client/assets/WorkspaceCenter-F8ctl0ZL.js +1 -0
- package/dist/client/assets/WorkspaceMemoryDetail-BLFoEX3q.js +1 -0
- package/dist/client/assets/_projectId-D3UHHv9-.js +1 -0
- package/dist/client/assets/_projectId._memoryId-CZOJ7L4F.js +1 -0
- package/dist/client/assets/_projectId.index-Dc3jTh6p.js +1 -0
- package/dist/client/assets/collections-y7eMFwFc.js +19 -0
- package/dist/client/assets/empty-C4Q9vAt-.js +1 -0
- package/dist/client/assets/global-BZgjloNm.js +1 -0
- package/dist/client/assets/global._memoryId-DbiHUsW4.js +1 -0
- package/dist/client/assets/global.index-w6voN-YE.js +1 -0
- package/dist/client/assets/index-B3Ej81eU.js +10 -0
- package/dist/client/assets/index-DHtBroPC.css +2 -0
- package/dist/client/assets/input-BdBFU9te.js +1 -0
- package/dist/client/assets/preload-helper-DYD3iRAO.js +1 -0
- package/dist/client/assets/routes-DdtLVWUF.js +1 -0
- package/dist/client/assets/schemas-jSuIeSIL.js +39 -0
- package/dist/client/assets/skeleton-BDvkvqhf.js +1 -0
- package/dist/client/assets/types-DT_fBrSI.js +1 -0
- package/dist/client/assets/useRenderElement-DhejdWAQ.js +1 -0
- package/dist/client/index.html +7 -2
- package/dist/index.cjs +102 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +103 -3
- package/package.json +7 -5
- package/dist/client/assets/MagnifyingGlass.es-ERvQA8v5.js +0 -1
- package/dist/client/assets/index-BCPCyhdz.js +0 -119
- package/dist/client/assets/index-ByUTKMgP.css +0 -1
- package/dist/client/assets/memories-C4n5opTn.js +0 -1
- package/dist/client/assets/memories._id-CrT5UPVk.js +0 -1
- package/dist/client/assets/memories.index-Bg5p8A21.js +0 -1
- package/dist/client/assets/native-select-Boj2GMjk.js +0 -1
|
@@ -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 ee(e,t){return E(e.type,t,e.props)}function D(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function O(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var k=/\/+/g;function A(e,t){return typeof e==`object`&&e&&e.key!=null?O(``+e.key):t.toString(36)}function j(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 M(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,M(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+A(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(k,`$&/`)+`/`),M(o,r,i,``,function(e){return e})):o!=null&&(D(o)&&(o=ee(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(k,`$&/`)+`/`)+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+A(a,u),c+=M(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+A(a,u++),c+=M(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return M(j(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 N(e,t,n){if(e==null)return e;var r=[],i=0;return M(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function P(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:N,forEach:function(e,t,n){N(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return N(e,function(){t++}),t},toArray:function(e){return N(e,function(e){return e})||[]},only:function(e){if(!D(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=D,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:P}},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){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`})),m=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=p()})),h=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)}})),g=o(((e,t)=>{t.exports=h()}));function _(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=_(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n);return r}function v(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=_(e))&&(r&&(r+=` `),r+=t);return r}var y=(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},b=(e,t)=>({classGroupId:e,validator:t}),x=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),S=`-`,C=[],w=`arbitrary..`,T=e=>{let t=D(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return ee(e);let n=e.split(S);return E(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?y(i,t):t:i||C}return n[e]||C}}},E=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=E(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(S):e.slice(t).join(S),s=a.length;for(let e=0;e<s;e++){let t=a[e];if(t.validator(o))return t.classGroupId}},ee=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?w+r:void 0})(),D=e=>{let{theme:t,classGroups:n}=e;return O(n,t)},O=(e,t)=>{let n=x();for(let r in e){let i=e[r];k(i,n,r,t)}return n},k=(e,t,n,r)=>{let i=e.length;for(let a=0;a<i;a++){let i=e[a];A(i,t,n,r)}},A=(e,t,n,r)=>{if(typeof e==`string`){j(e,t,n);return}if(typeof e==`function`){M(e,t,n,r);return}N(e,t,n,r)},j=(e,t,n)=>{let r=e===``?t:P(t,e);r.classGroupId=n},M=(e,t,n,r)=>{if(F(e)){k(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(b(n,e))},N=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e<a;e++){let[a,o]=i[e];k(o,P(t,a),n,r)}},P=(e,t)=>{let n=e,r=t.split(S),i=r.length;for(let e=0;e<i;e++){let t=r[e],i=n.nextPart.get(t);i||(i=x(),n.nextPart.set(t,i)),n=i}return n},F=e=>`isThemeGetter`in e&&e.isThemeGetter===!0,te=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)}}},ne=`!`,re=`:`,ie=[],I=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),L=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===re){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(ne)?(c=s.slice(0,-1),l=!0):s.startsWith(ne)&&(c=s.slice(1),l=!0);let u=a&&a>i?a-i:void 0;return I(t,l,c,u)};if(t){let e=t+re,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):I(ie,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},ae=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}},oe=e=>({cache:te(e.cacheSize),parseClassName:L(e),sortModifiers:ae(e),...T(e)}),R=/\s+/,se=(e,t)=>{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a}=t,o=[],s=e.trim().split(R),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+ne: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},ce=(...e)=>{let t=0,n,r,i=``;for(;t<e.length;)(n=e[t++])&&(r=le(n))&&(i&&(i+=` `),i+=r);return i},le=e=>{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r<e.length;r++)e[r]&&(t=le(e[r]))&&(n&&(n+=` `),n+=t);return n},z=(e,...t)=>{let n,r,i,a,o=o=>(n=oe(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=se(e,n);return i(e,a),a};return a=o,(...e)=>a(ce(...e))},ue=[],B=e=>{let t=t=>t[e]||ue;return t.isThemeGetter=!0,t},de=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,fe=/^\((?:(\w[\w-]*):)?(.+)\)$/i,pe=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,me=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,he=/\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$/,ge=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,_e=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ve=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ye=e=>pe.test(e),V=e=>!!e&&!Number.isNaN(Number(e)),be=e=>!!e&&Number.isInteger(Number(e)),xe=e=>e.endsWith(`%`)&&V(e.slice(0,-1)),Se=e=>me.test(e),Ce=()=>!0,we=e=>he.test(e)&&!ge.test(e),Te=()=>!1,Ee=e=>_e.test(e),De=e=>ve.test(e),Oe=e=>!H(e)&&!U(e),ke=e=>We(e,Je,Te),H=e=>de.test(e),Ae=e=>We(e,Ye,we),je=e=>We(e,Xe,V),Me=e=>We(e,Qe,Ce),Ne=e=>We(e,Ze,Te),Pe=e=>We(e,Ke,Te),Fe=e=>We(e,qe,De),Ie=e=>We(e,$e,Ee),U=e=>fe.test(e),Le=e=>Ge(e,Ye),Re=e=>Ge(e,Ze),ze=e=>Ge(e,Ke),Be=e=>Ge(e,Je),Ve=e=>Ge(e,qe),He=e=>Ge(e,$e,!0),Ue=e=>Ge(e,Qe,!0),We=(e,t,n)=>{let r=de.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Ge=(e,t,n=!1)=>{let r=fe.exec(e);return r?r[1]?t(r[1]):n:!1},Ke=e=>e===`position`||e===`percentage`,qe=e=>e===`image`||e===`url`,Je=e=>e===`length`||e===`size`||e===`bg-size`,Ye=e=>e===`length`,Xe=e=>e===`number`,Ze=e=>e===`family-name`,Qe=e=>e===`number`||e===`weight`,$e=e=>e===`shadow`,et=z(()=>{let e=B(`color`),t=B(`font`),n=B(`text`),r=B(`font-weight`),i=B(`tracking`),a=B(`leading`),o=B(`breakpoint`),s=B(`container`),c=B(`spacing`),l=B(`radius`),u=B(`shadow`),d=B(`inset-shadow`),f=B(`text-shadow`),p=B(`drop-shadow`),m=B(`blur`),h=B(`perspective`),g=B(`aspect`),_=B(`ease`),v=B(`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(),U,H],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[U,H,c],T=()=>[ye,`full`,`auto`,...w()],E=()=>[be,`none`,`subgrid`,U,H],ee=()=>[`auto`,{span:[`full`,be,U,H]},be,U,H],D=()=>[be,`auto`,U,H],O=()=>[`auto`,`min`,`max`,`fr`,U,H],k=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],A=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],j=()=>[`auto`,...w()],M=()=>[ye,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],N=()=>[ye,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],P=()=>[ye,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],F=()=>[e,U,H],te=()=>[...b(),ze,Pe,{position:[U,H]}],ne=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,Be,ke,{size:[U,H]}],ie=()=>[xe,Le,Ae],I=()=>[``,`none`,`full`,l,U,H],L=()=>[``,V,Le,Ae],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=()=>[V,xe,ze,Pe],se=()=>[``,`none`,m,U,H],ce=()=>[`none`,V,U,H],le=()=>[`none`,V,U,H],z=()=>[V,U,H],ue=()=>[ye,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[Se],breakpoint:[Se],color:[Ce],container:[Se],"drop-shadow":[Se],ease:[`in`,`out`,`in-out`],font:[Oe],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[Se],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[Se],shadow:[Se],spacing:[`px`,V],text:[Se],"text-shadow":[Se],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,ye,H,U,g]}],container:[`container`],columns:[{columns:[V,H,U,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:[be,`auto`,U,H]}],basis:[{basis:[ye,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[V,ye,`auto`,`initial`,`none`,H]}],grow:[{grow:[``,V,U,H]}],shrink:[{shrink:[``,V,U,H]}],order:[{order:[be,`first`,`last`,`none`,U,H]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:ee()}],"col-start":[{"col-start":D()}],"col-end":[{"col-end":D()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:ee()}],"row-start":[{"row-start":D()}],"row-end":[{"row-end":D()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":O()}],"auto-rows":[{"auto-rows":O()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...k(),`normal`]}],"justify-items":[{"justify-items":[...A(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...A()]}],"align-content":[{content:[`normal`,...k()]}],"align-items":[{items:[...A(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...A(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":k()}],"place-items":[{"place-items":[...A(),`baseline`]}],"place-self":[{"place-self":[`auto`,...A()]}],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:j()}],mx:[{mx:j()}],my:[{my:j()}],ms:[{ms:j()}],me:[{me:j()}],mbs:[{mbs:j()}],mbe:[{mbe:j()}],mt:[{mt:j()}],mr:[{mr:j()}],mb:[{mb:j()}],ml:[{ml:j()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:M()}],"inline-size":[{inline:[`auto`,...N()]}],"min-inline-size":[{"min-inline":[`auto`,...N()]}],"max-inline-size":[{"max-inline":[`none`,...N()]}],"block-size":[{block:[`auto`,...P()]}],"min-block-size":[{"min-block":[`auto`,...P()]}],"max-block-size":[{"max-block":[`none`,...P()]}],w:[{w:[s,`screen`,...M()]}],"min-w":[{"min-w":[s,`screen`,`none`,...M()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...M()]}],h:[{h:[`screen`,`lh`,...M()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...M()]}],"max-h":[{"max-h":[`screen`,`lh`,...M()]}],"font-size":[{text:[`base`,n,Le,Ae]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Ue,Me]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,xe,H]}],"font-family":[{font:[Re,Ne,t]}],"font-features":[{"font-features":[H]}],"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,U,H]}],"line-clamp":[{"line-clamp":[V,`none`,U,je]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,U,H]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,U,H]}],"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:[V,`from-font`,`auto`,U,Ae]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[V,`auto`,U,H]}],"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`,U,H]}],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`,U,H]}],"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`]},be,U,H],radial:[``,U,H],conic:[be,U,H]},Ve,Fe]}],"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":[V,U,H]}],"outline-w":[{outline:[``,V,Le,Ae]}],"outline-color":[{outline:F()}],shadow:[{shadow:[``,`none`,u,He,Ie]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":[`none`,d,He,Ie]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:L()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[V,Ae]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":L()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":[`none`,f,He,Ie]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[V,U,H]}],"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":[V]}],"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":[U,H]}],"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":[V]}],"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`,U,H]}],filter:[{filter:[``,`none`,U,H]}],blur:[{blur:se()}],brightness:[{brightness:[V,U,H]}],contrast:[{contrast:[V,U,H]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,He,Ie]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:[``,V,U,H]}],"hue-rotate":[{"hue-rotate":[V,U,H]}],invert:[{invert:[``,V,U,H]}],saturate:[{saturate:[V,U,H]}],sepia:[{sepia:[``,V,U,H]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,U,H]}],"backdrop-blur":[{"backdrop-blur":se()}],"backdrop-brightness":[{"backdrop-brightness":[V,U,H]}],"backdrop-contrast":[{"backdrop-contrast":[V,U,H]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,V,U,H]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[V,U,H]}],"backdrop-invert":[{"backdrop-invert":[``,V,U,H]}],"backdrop-opacity":[{"backdrop-opacity":[V,U,H]}],"backdrop-saturate":[{"backdrop-saturate":[V,U,H]}],"backdrop-sepia":[{"backdrop-sepia":[``,V,U,H]}],"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`,U,H]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[V,`initial`,U,H]}],ease:[{ease:[`linear`,`initial`,_,U,H]}],delay:[{delay:[V,U,H]}],animate:[{animate:[`none`,v,U,H]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,U,H]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:ce()}],"rotate-x":[{"rotate-x":ce()}],"rotate-y":[{"rotate-y":ce()}],"rotate-z":[{"rotate-z":ce()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":[`scale-3d`],skew:[{skew:z()}],"skew-x":[{"skew-x":z()}],"skew-y":[{"skew-y":z()}],transform:[{transform:[U,H,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:ue()}],"translate-x":[{"translate-x":ue()}],"translate-y":[{"translate-y":ue()}],"translate-z":[{"translate-z":ue()}],"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`,U,H]}],"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`,U,H]}],fill:[{fill:[`none`,...F()]}],"stroke-w":[{stroke:[V,Le,Ae,je]}],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 tt(...e){return et(v(e))}function nt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function rt(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function it(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 at=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,ot=v,st=(e,t)=>n=>{if(t?.variants==null)return ot(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=at(t)||at(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 ot(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)},W=c(u(),1),ct=c(m(),1);function lt(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 ut=e=>{switch(e){case`success`:return pt;case`info`:return ht;case`warning`:return mt;case`error`:return gt;default:return null}},dt=Array(12).fill(0),ft=({visible:e,className:t})=>W.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},W.createElement(`div`,{className:`sonner-spinner`},dt.map((e,t)=>W.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),pt=W.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},W.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`})),mt=W.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},W.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`})),ht=W.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},W.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`})),gt=W.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},W.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`})),_t=W.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`},W.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),W.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),vt=()=>{let[e,t]=W.useState(document.hidden);return W.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},yt=1,bt=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:yt++,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],W.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(St(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`&&!W.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`&&!W.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`&&!W.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`&&!W.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||yt++;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}},xt=(e,t)=>{let n=t?.id||yt++;return bt.addToast({title:e,...t,id:n}),n},St=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,Ct=Object.assign(xt,{success:bt.success,info:bt.info,warning:bt.warning,error:bt.error,custom:bt.custom,message:bt.message,promise:bt.promise,dismiss:bt.dismiss,loading:bt.loading},{getHistory:()=>bt.toasts,getToasts:()=>bt.getActiveToasts()});lt(`[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 wt(e){return e.label!==void 0}var Tt=3,Et=`24px`,Dt=`16px`,Ot=4e3,kt=356,At=14,jt=45,Mt=200;function Nt(...e){return e.filter(Boolean).join(` `)}function Pt(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var Ft=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:v=``,duration:y,position:b,gap:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:T=`Close toast`}=e,[E,ee]=W.useState(null),[D,O]=W.useState(null),[k,A]=W.useState(!1),[j,M]=W.useState(!1),[N,P]=W.useState(!1),[F,te]=W.useState(!1),[ne,re]=W.useState(!1),[ie,I]=W.useState(0),[L,ae]=W.useState(0),oe=W.useRef(n.duration||y||Ot),R=W.useRef(null),se=W.useRef(null),ce=c===0,le=c+1<=o,z=n.type,ue=n.dismissible!==!1,B=n.className||``,de=n.descriptionClassName||``,fe=W.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),pe=W.useMemo(()=>n.closeButton??p,[n.closeButton,p]),me=W.useMemo(()=>n.duration||y||Ot,[n.duration,y]),he=W.useRef(0),ge=W.useRef(0),_e=W.useRef(0),ve=W.useRef(null),[ye,V]=b.split(`-`),be=W.useMemo(()=>s.reduce((e,t,n)=>n>=fe?e:e+t.height,0),[s,fe]),xe=vt(),Se=n.invert||t,Ce=z===`loading`;ge.current=W.useMemo(()=>fe*x+be,[fe,be]),W.useEffect(()=>{oe.current=me},[me]),W.useEffect(()=>{A(!0)},[]),W.useEffect(()=>{let e=se.current;if(e){let t=e.getBoundingClientRect().height;return ae(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),W.useLayoutEffect(()=>{if(!k)return;let e=se.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,ae(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])},[k,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let we=W.useCallback(()=>{M(!0),I(ge.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},Mt)},[n,d,a,ge]);W.useEffect(()=>{if(n.promise&&z===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||xe?(()=>{if(_e.current<he.current){let e=new Date().getTime()-he.current;oe.current-=e}_e.current=new Date().getTime()})():oe.current!==1/0&&(he.current=new Date().getTime(),e=setTimeout(()=>{n.onAutoClose==null||n.onAutoClose.call(n,n),we()},oe.current)),()=>clearTimeout(e)},[u,i,n,z,xe,we]),W.useEffect(()=>{n.delete&&(we(),n.onDismiss==null||n.onDismiss.call(n,n))},[we,n.delete]);function Te(){return w?.loading?W.createElement(`div`,{className:Nt(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":z===`loading`},w.loading):W.createElement(ft,{className:Nt(C?.loader,n?.classNames?.loader),visible:z===`loading`})}let Ee=n.icon||w?.[z]||ut(z);return W.createElement(`li`,{tabIndex:0,ref:se,className:Nt(_,B,C?.toast,n?.classNames?.toast,C?.default,C?.[z],n?.classNames?.[z]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":k,"data-promise":!!n.promise,"data-swiped":ne,"data-removed":j,"data-visible":le,"data-y-position":ye,"data-x-position":V,"data-index":c,"data-front":ce,"data-swiping":N,"data-dismissible":ue,"data-type":z,"data-invert":Se,"data-swipe-out":F,"data-swipe-direction":D,"data-expanded":!!(u||S&&k),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${j?ie:ge.current}px`,"--initial-height":S?`auto`:`${L}px`,...m,...n.style},onDragEnd:()=>{P(!1),ee(null),ve.current=null},onPointerDown:e=>{e.button!==2&&(Ce||!ue||(R.current=new Date,I(ge.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(P(!0),ve.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(F||!ue)return;ve.current=null;let e=Number(se.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(se.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-R.current?.getTime(),i=E===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=jt||a>.11){I(ge.current),n.onDismiss==null||n.onDismiss.call(n,n),O(E===`x`?e>0?`right`:`left`:t>0?`down`:`up`),we(),te(!0);return}else{var o,s;(o=se.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=se.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`)}re(!1),P(!1),ee(null)},onPointerMove:t=>{var n,r;if(!ve.current||!ue||window.getSelection()?.toString().length>0)return;let i=t.clientY-ve.current.y,a=t.clientX-ve.current.x,o=e.swipeDirections??Pt(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&ee(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(E===`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(E===`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)&&re(!0),(n=se.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=se.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},pe&&!n.jsx&&z!==`loading`?W.createElement(`button`,{"aria-label":T,"data-disabled":Ce,"data-close-button":!0,onClick:Ce||!ue?()=>{}:()=>{we(),n.onDismiss==null||n.onDismiss.call(n,n)},className:Nt(C?.closeButton,n?.classNames?.closeButton)},w?.close??_t):null,(z||n.icon||n.promise)&&n.icon!==null&&(w?.[z]!==null||n.icon)?W.createElement(`div`,{"data-icon":``,className:Nt(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Te():null,n.type===`loading`?null:Ee):null,W.createElement(`div`,{"data-content":``,className:Nt(C?.content,n?.classNames?.content)},W.createElement(`div`,{"data-title":``,className:Nt(C?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?W.createElement(`div`,{"data-description":``,className:Nt(v,de,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),W.isValidElement(n.cancel)?n.cancel:n.cancel&&wt(n.cancel)?W.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{wt(n.cancel)&&ue&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),we())},className:Nt(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,W.isValidElement(n.action)?n.action:n.action&&wt(n.action)?W.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{wt(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&we())},className:Nt(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function It(){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 Lt(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?Dt:Et;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 Rt=W.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=Tt,toastOptions:g,dir:_=It(),gap:v=At,icons:y,containerAriaLabel:b=`Notifications`}=e,[x,S]=W.useState([]),C=W.useMemo(()=>n?x.filter(e=>e.toasterId===n):x.filter(e=>!e.toasterId),[x,n]),w=W.useMemo(()=>Array.from(new Set([i].concat(C.filter(e=>e.position).map(e=>e.position)))),[C,i]),[T,E]=W.useState([]),[ee,D]=W.useState(!1),[O,k]=W.useState(!1),[A,j]=W.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),M=W.useRef(null),N=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),P=W.useRef(null),F=W.useRef(!1),te=W.useCallback(e=>{S(t=>(t.find(t=>t.id===e.id)?.delete||bt.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return W.useEffect(()=>bt.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{ct.flushSync(()=>{S(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)]})})})}),[x]),W.useEffect(()=>{if(d!==`system`){j(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?j(`dark`):j(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{j(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{j(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),W.useEffect(()=>{x.length<=1&&D(!1)},[x]),W.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;D(!0),(t=M.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===M.current||M.current?.contains(document.activeElement))&&D(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),W.useEffect(()=>{if(M.current)return()=>{P.current&&(P.current.focus({preventScroll:!0}),P.current=null,F.current=!1)}},[M.current]),W.createElement(`section`,{ref:t,"aria-label":`${b} ${N}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},w.map((t,n)=>{let[i,a]=t.split(`-`);return C.length?W.createElement(`ol`,{key:t,dir:_===`auto`?It():_,tabIndex:-1,ref:M,className:c,"data-sonner-toaster":!0,"data-sonner-theme":A,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${T[0]?.height||0}px`,"--width":`${kt}px`,"--gap":`${v}px`,...m,...Lt(l,u)},onBlur:e=>{F.current&&!e.currentTarget.contains(e.relatedTarget)&&(F.current=!1,P.current&&=(P.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||F.current||(F.current=!0,P.current=e.relatedTarget)},onMouseEnter:()=>D(!0),onMouseMove:()=>D(!0),onMouseLeave:()=>{O||D(!1)},onDragEnd:()=>D(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||k(!0)},onPointerUp:()=>k(!1)},C.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>W.createElement(Ft,{key:n.id,icons:y,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:O,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:te,toasts:C.filter(e=>e.position==n.position),heights:T.filter(e=>e.position==n.position),setHeights:E,expandByDefault:o,gap:v,expanded:ee,swipeDirections:e.swipeDirections}))):null}))}),zt=`__includes_scalar__`,Bt=class{},Vt=class extends Bt{constructor(e,t){super(),this.collection=e,this.alias=t,this.type=`collectionRef`}},Ht=class extends Bt{constructor(e,t){super(),this.query=e,this.alias=t,this.type=`queryRef`}},G=class extends Bt{constructor(e){super(),this.path=e,this.type=`ref`}},K=class extends Bt{constructor(e){super(),this.value=e,this.type=`val`}},Ut=class extends Bt{constructor(e,t){super(),this.name=e,this.args=t,this.type=`func`}},Wt=class extends Bt{constructor(e,t){super(),this.name=e,this.args=t,this.type=`agg`}},Gt=class extends Bt{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 Kt(e){return e instanceof Wt||e instanceof Ut||e instanceof G||e instanceof K||e instanceof Gt}function qt(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Jt(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Yt(e){return typeof e==`object`&&`expression`in e&&e.residual===!0}function Xt(e){return{expression:e,residual:!0}}function Zt(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 Qt(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 Qt(e,t,n)}return{collection:n,path:[r]}}if(t.path.length>1){let[r,...i]=t.path,a=Zt(e,r);return a?a.type===`queryRef`?Qt(a.query,new G(i),n):{collection:a.collection,path:i}:void 0}}}var $t=class extends Error{constructor(e){super(e),this.name=`TanStackDBError`}},en=class extends $t{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}},tn=class extends $t{constructor(e){super(e),this.name=`CollectionConfigurationError`}},nn=class extends tn{constructor(){super(`Collection requires a config`)}},rn=class extends tn{constructor(){super(`Collection requires a sync config`)}},an=class extends tn{constructor(){super(`Schema must implement the standard-schema interface`)}},on=class extends tn{constructor(){super(`Schema validation must be synchronous`)}},sn=class extends $t{constructor(e){super(e),this.name=`CollectionStateError`}},cn=class extends sn{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}},ln=class extends sn{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}},un=class extends sn{constructor(){super(`Collection is in error state`)}},dn=class extends sn{constructor(){super(`Active subscribers count is negative - this should never happen`)}},fn=class extends $t{constructor(e){super(e),this.name=`CollectionOperationError`}},pn=class extends fn{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}},mn=class extends fn{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)}`)}},hn=class extends fn{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}},gn=class extends fn{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)}},_n=class extends fn{constructor(){super(`The first argument to update is missing`)}},vn=class extends fn{constructor(){super(`No keys were passed to update`)}},yn=class extends fn{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}},bn=class extends fn{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.`)}},xn=class extends fn{constructor(){super(`No keys were passed to delete`)}},Sn=class extends fn{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}},Cn=class extends $t{constructor(e){super(e),this.name=`MissingHandlerError`}},wn=class extends Cn{constructor(){super(`Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.`)}},Tn=class extends Cn{constructor(){super(`Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.`)}},En=class extends Cn{constructor(){super(`Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.`)}},Dn=class extends $t{constructor(e){super(e),this.name=`TransactionError`}},On=class extends Dn{constructor(){super(`mutationFn is required when creating a transaction`)}},kn=class extends Dn{constructor(){super(`You can no longer call .mutate() as the transaction is no longer pending`)}},An=class extends Dn{constructor(){super(`You can no longer call .rollback() as the transaction is already completed`)}},jn=class extends Dn{constructor(){super(`You can no longer call .commit() as the transaction is no longer pending`)}},Mn=class extends Dn{constructor(){super(`No pending sync transaction to write to`)}},Nn=class extends Dn{constructor(){super(`The pending sync transaction is already committed, you can't still write to it.`)}},Pn=class extends Dn{constructor(){super(`No pending sync transaction to commit`)}},Fn=class extends Dn{constructor(){super(`The pending sync transaction is already committed, you can't commit it again.`)}},In=class extends $t{constructor(e){super(e),this.name=`QueryBuilderError`}},Ln=class extends In{constructor(e){super(`Only one source is allowed in the ${e}`)}},Rn=class extends In{constructor(e){super(`A sub query passed to a ${e} must have a from clause itself`)}},zn=class extends In{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.`)}},Bn=class extends In{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}`)}},Vn=class extends In{constructor(){super(`Join condition must be an equality expression`)}},Hn=class extends In{constructor(){super(`Query must have a from clause`)}},Un=class extends In{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`)}},Wn=class extends $t{constructor(e){super(e),this.name=`QueryCompilationError`}},Gn=class extends Wn{constructor(){super(`DISTINCT requires a SELECT clause.`)}},Kn=class extends Wn{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().`)}},qn=class extends Wn{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(...)).`)}},Jn=class extends Wn{constructor(){super(`HAVING clause requires GROUP BY clause`)}},Yn=class extends Wn{constructor(){super(`LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results`)}},Xn=class extends Wn{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}`)}},Zn=class extends Wn{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.`)}},Qn=class extends Wn{constructor(e){super(`Unsupported FROM type: ${e}`)}},$n=class extends Wn{constructor(e){super(`Unknown expression type: ${e}`)}},er=class extends Wn{constructor(){super(`Reference path cannot be empty`)}},tr=class extends Wn{constructor(e){super(`Unknown function: ${e}`)}},nr=class extends Wn{constructor(e){super(`Collection "${e}" not found during compilation of join`)}},rr=class extends $t{constructor(e){super(e),this.name=`JoinError`}},ir=class extends rr{constructor(e){super(`Unsupported join type: ${e}`)}},ar=class extends rr{constructor(e){super(`Invalid join condition: both expressions refer to the same source "${e}"`)}},or=class extends rr{constructor(){super(`Invalid join condition: expressions must reference source aliases`)}},sr=class extends rr{constructor(e){super(`Invalid join condition: left expression refers to an unavailable source "${e}"`)}},cr=class extends rr{constructor(e){super(`Invalid join condition: right expression does not refer to the joined source "${e}"`)}},lr=class extends rr{constructor(){super(`Invalid join condition`)}},ur=class extends rr{constructor(e){super(`Unsupported join source type: ${e}`)}},dr=class extends $t{constructor(e){super(e),this.name=`GroupByError`}},fr=class extends dr{constructor(e){super(`Non-aggregate expression '${e}' in SELECT must also appear in GROUP BY clause`)}},pr=class extends dr{constructor(e){super(`Unsupported aggregate function: ${e}`)}},mr=class extends dr{constructor(e){super(`Aggregate function in HAVING clause must also be in SELECT clause: ${e}`)}},hr=class extends dr{constructor(e){super(`Unknown expression type in HAVING clause: ${e}`)}},gr=class extends $t{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`}},_r=class extends $t{constructor(e){super(e),this.name=`QueryOptimizerError`}},vr=class extends _r{constructor(){super(`Cannot combine empty expression list`)}},yr=class extends Wn{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.`)}},br=class extends Wn{constructor(e){super(`Internal error: compiler returned aliases without inputs: ${e.join(`, `)}. This indicates a bug in query compilation. Please report this issue.`)}},xr=class extends Wn{constructor(){super(`setWindow() can only be called on collections with an ORDER BY clause. Add .orderBy() to your query to enable window movement.`)}};function Sr(e,t){return Cr(e,t,new Map)}function Cr(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)&&Cr(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(Tr(e)&&Tr(t))return e[Symbol.toStringTag]===t[Symbol.toStringTag]?typeof e.equals==`function`?e.equals(t):e.toString()===t.toString():!1;if(Tr(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)=>Cr(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&&Cr(e[r],t[r],n));return n.delete(e),a}return!1}var wr=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function Tr(e){if(typeof e!=`object`||!e)return!1;let t=e[Symbol.toStringTag];return typeof t==`string`&&wr.has(t)}var Er={direction:`asc`,nulls:`first`,stringSort:`locale`},Dr=new WeakMap,Or=1;function kr(e){if(Dr.has(e))return Dr.get(e);let t=Or++;return Dr.set(e,t),t}var Ar=(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=Ar(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(Tr(e)&&Tr(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 kr(e)-kr(t);if(i)return 1;if(a)return-1}return e<t?-1:+(e>t)},jr=(e,t,n)=>Ar(t,e,{...n,nulls:n.nulls===`first`?`last`:`first`});function Mr(e){return(t,n)=>e.direction===`asc`?Ar(t,n,e):jr(t,n,e)}var Nr=Mr({direction:`asc`,nulls:`first`,stringSort:`locale`});function Pr(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 Fr=128;function Ir(e){return e instanceof Date?e.getTime():Tr(e)?`__temporal__${e[Symbol.toStringTag]}__${e.toString()}`:(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)&&e.byteLength<=Fr?`__u8__${Array.from(e).join(`,`)}`:e}function Lr(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?Pr(e,t):!1}function q(e){return e==null}function Rr(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 zr(e,t){return e===`%Y-%m-%d`?t.toISOString().slice(0,10):t.toISOString()}function Br(e){return e===!0}function J(e,t=!1){return Hr(e,t)}function Vr(e){return Hr(e,!0)}function Hr(e,t){switch(e.type){case`val`:{let t=e.value;return()=>t}case`ref`:return t?Wr(e):Ur(e);case`func`:return Gr(e,t);default:throw new $n(e.type)}}function Ur(e){let[t,...n]=e.path;if(!t)throw new er;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 Wr(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 Gr(e,t){let n=e.args.map(e=>Hr(e,t));switch(e.name){case`eq`:{let e=n[0],t=n[1];return n=>{let r=Ir(e(n)),i=Ir(t(n));return q(r)||q(i)?null:Lr(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=Ir(e(n)),i=t(n);return q(r)?null:Array.isArray(i)?i.some(e=>Ir(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:Kr(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:Kr(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=Rr(e(t));return n?n.toISOString().slice(0,10):null}}case`datetime`:{let e=n[0];return t=>{let n=Rr(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=Rr(t(n));return i?zr(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 tr(e.name)}}function Kr(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 qr=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 Jr(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 Yr=[`$synced`,`$origin`,`$key`,`$collectionId`];function Xr(e){return Yr.includes(e)}function Zr(e){return e.some(e=>Xr(e))}function Qr(e,t,n){if(Zr(t))return;let r=n??{...Er,...e.compareOptions};for(let n of e.indexes.values())if(n.matchesField(t)&&n.matchesCompareOptions(r))return n.matchesDirection(r.direction)?n:new qr(n)}function $r(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 ei(e){let t=new Set;for(let n of e)for(let e of n)t.add(e);return t}function ti(e,t){return ni(e,t)}function ni(e,t){if(e.type===`func`)switch(e.name){case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:return ii(e,t);case`and`:return ai(e,t);case`or`:return oi(e,t);case`in`:return si(e,t)}return{canOptimize:!1,matchingKeys:new Set}}function ri(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=Qr(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 ii(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=Qr(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 ai(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set};let n=ri(e,t);if(n.canOptimize)return n;let r=[];for(let n of e.args){let e=ni(n,t);e.canOptimize&&r.push(e)}return r.length>0?{canOptimize:!0,matchingKeys:$r(r.map(e=>e.matchingKeys))}:{canOptimize:!1,matchingKeys:new Set}}function oi(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=ni(r,t);e.canOptimize&&n.push(e)}return n.length>0?{canOptimize:!0,matchingKeys:ei(n.map(e=>e.matchingKeys))}:{canOptimize:!1,matchingKeys:new Set}}function si(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=Qr(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 ci={enabled:!0,collectionSizeThreshold:1e3,slowQueryThresholdMs:10,onSuggestion:null};function li(){return ci.enabled&&!1}function ui(e){if(li())if(ci.onSuggestion)try{ci.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 di(e,t,n){li()&&t>ci.collectionSizeThreshold&&ui({type:`collection-size`,collectionId:e,fieldPath:n,message:`Collection has ${t} items. Queries on "${n.join(`.`)}" may benefit from an index.`,collectionSize:t})}function fi(e){return e.config.autoIndex===`eager`}function pi(e,t,n,r,i){if(Zr(t)||!fi(n))return;let a=r??{...Er,...n.compareOptions};if(!Array.from(n.indexes.values()).find(e=>e.matchesField(t)&&e.matchesCompareOptions(a))){li()&&di(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 mi(e,t){if(!fi(t))return;let n=hi(e);for(let{fieldName:e,fieldPath:r}of n)pi(e,r,t)}function hi(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 gi=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}},_i=3e4;function vi(e,t){if(t.length<=_i)e.push(...t);else for(let n=0;n<t.length;n+=_i){let r=t.slice(n,n+_i);e.push(...r)}}function yi(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 bi=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 xi(e,t){let[n,r]=e,[i,a]=t;return{onlyInA:[...Si(n,Math.min(r,i)),...Si(Math.max(n,a),r)],onlyInB:[...Si(i,Math.min(a,n)),...Si(Math.max(i,r),a)]}}function Si(e,t){let n=[];for(let r=e;r<t;r++)n.push(r);return n}function Ci(e,t){return typeof e==typeof t?e<t?-1:+(e>t):typeof e==`string`?-1:1}function wi(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t instanceof Date?t.toISOString():t)}var Ti=Y(),Ei=Y(),Di=Y(),Oi=Y(),ki=Y();function Y(){return Math.random()*(2**31-1)>>>0}var Ai=new ArrayBuffer(8),ji=new DataView(Ai),Mi=new Uint8Array(Ai),Ni=class{constructor(){this.hash=Ti,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(ki);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(Ei);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`:ji.setFloat64(0,e,!0),this.writeByte(Mi[0]),this.writeByte(Mi[1]),this.writeByte(Mi[2]),this.writeByte(Mi[3]),this.writeByte(Mi[4]),this.writeByte(Mi[5]),this.writeByte(Mi[6]),this.writeByte(Mi[7]);return;case`bigint`:{let t=e;for(t<0n?(t=-t,this.update(Oi)):this.update(Di);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}},Pi=Y(),Fi=Y(),Ii=Y(),Li=Y(),Ri=Y(),zi=Y(),Bi=Y(),Vi=Y(),Hi=Y(),Ui=Y(),Wi=Y(),Gi=Y(),Ki=Y(),qi=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function Ji(e){let t=e[Symbol.toStringTag];return typeof t==`string`&&qi.has(t)}var Yi=128,Xi=new WeakMap;function Zi(e){let t=new Ni;return ra(t,e),t.digest()}function Qi(e){let t=Xi.get(e);if(t!==void 0)return t;let n;if(e instanceof Date)n=$i(e);else if(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)if(e.byteLength<=Yi)n=ea(e);else return oa(e);else if(e instanceof File)return oa(e);else if(Ji(e))n=ta(e);else{let t=e,r=Vi;e instanceof Array&&(r=Hi),e instanceof Map&&(r=Ui,t=[...e.entries()]),e instanceof Set&&(r=Wi,t=[...e.entries()]),n=na(t,r)}return Xi.set(e,n),n}function $i(e){let t=new Ni;return t.update(Bi),t.update(e.getTime()),t.digest()}function ea(e){let t=new Ni;t.update(Gi),t.update(e.byteLength);for(let n=0;n<e.byteLength;n++)t.writeByte(e[n]);return t.digest()}function ta(e){let t=new Ni;return t.update(Ki),t.update(e[Symbol.toStringTag]),t.update(e.toString()),t.digest()}function na(e,t){let n=new Ni;n.update(t);let r=Object.keys(e);r.sort(sa);for(let t of r)n.update(Ri),n.update(t),ra(n,e[t]);return n.digest()}function ra(e,t){if(t===null){e.update(Ii);return}switch(typeof t){case`undefined`:e.update(Li);return;case`boolean`:e.update(t?Pi:Fi);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(ia(t));return;case`function`:e.update(oa(t));return;default:console.warn(`Ignored input during hashing because it is of type ${typeof t} which is not supported`)}}function ia(e){let t=Xi.get(e);return t===void 0&&(t=Qi(e)),t}var aa=1;function oa(e){let t=Xi.get(e);return t===void 0&&(t=aa^zi,aa++,Xi.set(e,t)),t}function sa(e,t){return e.localeCompare(t)}var ca=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 vi(n,this.#e),vi(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`${bi.getStringId(t)}|${bi.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):bi.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 gi(()=>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?Zi(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;vi(this.#e,n)}add(e,t){t!==0&&this.#e.push([e,t])}getInner(){return this.#e}},la=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}},ua=class{#e=[];sendData(e){e instanceof ca||(e=new ca(e));for(let t of this.#e)t.unshift(e)}newReader(){let e=[];return this.#e.push(e),new la(e)}},da=class{constructor(e,t,n){this.id=e,this.inputs=t,this.output=n}hasPendingWork(){return this.inputs.some(e=>!e.isEmpty())}},fa=class extends da{constructor(e,t,n){super(e,[t],n),this.id=e}inputMessages(){return this.inputs[0].drain()}},pa=class extends da{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()}},ma=class extends fa{run(){for(let e of this.inputMessages())this.output.sendData(this.inner(e))}},ha=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 ua;return new _a(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()}},ga=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)}},_a=class extends ga{sendData(e){this.writer.sendData(e)}},va=class extends fa{run(){let e=this.inputMessages();if(e.length===0)return;let t=new ca;for(let n of e)t.extend(n);let n=t.consolidate();n.getInner().length>0&&this.output.sendData(n)}};function ya(){return e=>{let t=new ga(e.graph,new ua),n=new va(e.graph.getNextOperatorId(),e.connectReader(),t.writer);return e.graph.addOperator(n),t}}var ba=Symbol(`NO_PREFIX`),xa=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=wa(e),r=this.get(n);if(Ta(r)){let[i,a]=r;if(wa(i)!==n)throw Error(`Mismatching prefixes, this should never happen`);if(i===e||Zi(i)===Zi(e)){let r=a+t;r===0?this.delete(n):this.set(n,[e,r])}else{let a=new Sa;a.set(Zi(i),r),a.set(Zi(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}},Sa=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=Zi(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}},Ca=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(Ta(t))yield t;else if(t===void 0)return;else if(t instanceof Sa)for(let e of t.values())yield e;else for(let e of t.values())if(Ta(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(Ta(a)){this.#n(e,a,n,r);return}if(a instanceof Sa){let i=wa(n);if(i!==ba){let n=new xa;n.set(ba,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=wa(n),s=wa(i);if(s===o&&(i===n||Zi(i)===Zi(n))){let t=a+r;t===0?this.#e.delete(e):this.#e.set(e,[n,t]);return}if(s===ba&&o===ba){let a=new Sa;a.set(Zi(i),t),a.set(Zi(n),[n,r]),this.#e.set(e,a)}else{let a=new xa;if(s===o){let e=new Sa;e.set(Zi(i),t),e.set(Zi(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 ca(t)}};function wa(e){return Array.isArray(e)&&(typeof e[0]==`string`||typeof e[0]==`number`||typeof e[0]==`bigint`)?e[0]:ba}function Ta(e){return Array.isArray(e)}var Ea=class extends fa{#e=new Ca;#t=new Ca;#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 ca(t))}};function Da(e){return t=>{let n=new ga(t.graph,new ua),r=new Ea(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Oa=class extends fa{#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=Zi(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([[Zi(this.#e(i)),i[1]],1]):e>0&&r<=0&&t.push([[Zi(this.#e(i)),i[1]],-1])}t.length>0&&this.output.sendData(new ca(t))}};function ka(e=e=>e){return t=>{let n=new ga(t.graph,new ua),r=new Oa(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Aa=class extends ma{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.filter(this.#e)}};function ja(e){return t=>{let n=new ga(t.graph,new ua),r=new Aa(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Ma=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`;function Na(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)+Na(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]+Na(e.slice(1),null,n)}function Pa(e){if(e.length!==Fa(e[0]))throw Error(`invalid integer part of order key: `+e)}function Fa(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 Ia(e){let t=Fa(e[0]);if(t>e.length)throw Error(`invalid order key: `+e);return e.slice(0,t)}function La(e,t){if(e===`A`+t[0].repeat(26))throw Error(`invalid order key: `+e);let n=Ia(e);if(e.slice(n.length).slice(-1)===t[0])throw Error(`invalid order key: `+e)}function Ra(e,t){Pa(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 za(e,t){Pa(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 Ba(e,t,n=Ma){if(e!=null&&La(e,n),t!=null&&La(t,n),e!=null&&t!=null&&e>=t)throw Error(e+` >= `+t);if(e==null){if(t==null)return`a`+n[0];let e=Ia(t),r=t.slice(e.length);if(e===`A`+n[0].repeat(26))return e+Na(``,r,n);if(e<t)return e;let i=za(e,n);if(i==null)throw Error(`cannot decrement any more`);return i}if(t==null){let t=Ia(e),r=e.slice(t.length);return Ra(t,n)??t+Na(r,null,n)}let r=Ia(e),i=e.slice(r.length),a=Ia(t),o=t.slice(a.length);if(r===a)return r+Na(i,o,n);let s=Ra(r,n);if(s==null)throw Error(`cannot increment any more`);return s<t?s:r+Na(i,null,n)}function Va(e,t){return[e,t]}function Ha(e){return e[0]}function Ua(e){return e[1]}function Wa(e){return([t,n],[r,i])=>{let a=e(n,i);return a===0?Ci(t,r):a}}var Ga=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}=xi(i,[this.#n,this.#r===1/0?Math.max(this.#n+this.size,i[1]):this.#r]),s=[];o.forEach(e=>{let t=this.#e[e];t&&s.push(t)});let c=[];return a.forEach(e=>{let t=this.#e[e];t&&c.push(t)}),{moveIns:s,moveOuts:c,changes:a.length+o.length>0}}insert(e){let t={moveIn:null,moveOut:null},n=this.#i(e),r=Va(e,Ba(n===0?null:Ua(this.#e[n-1]),n===this.#e.length?null:Ua(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 yi(this.#e,Va(e,``),(e,t)=>this.#t(Ha(e),Ha(t)))}},Ka=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 Ga))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 qa(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],1])}}function Ja(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],-1])}}var Ya=class extends fa{#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=Wa(r),i.setSizeCallback?.(()=>this.#a()),i.setWindowFn?.(this.#c.bind(this))}createTopK(e,t,n){return new Ga(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 Ka(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=>qa(e,n)),t.moveOuts.forEach(e=>Ja(e,n)),t.changes&&(r=!0)}r&&this.output.sendData(new ca(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 ca(e))}#l(e,t,n,r){let i=this.#t(e,t),a=this.#o(i),o=a.processElement(e,t,n);qa(o.moveIn,r),Ja(o.moveOut,r),this.#s(i,a)}};function Xa(e,t){return n=>{let r=new ga(n.graph,new ua),i=new Ya(n.graph.getNextOperatorId(),n.connectReader(),r.writer,e,t);return n.graph.addOperator(i),r}}var Za=class extends pa{#e=new Ca;#t=new Ca;#n;constructor(e,t,n,r,i=`inner`){super(e,t,n,r),this.#n=i}run(){let e=Ca.fromMultiSets(this.inputAMessages()),t=Ca.fromMultiSets(this.inputBMessages());if(e.size===0&&t.size===0)return;let n=new ca;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 Qa(e,t=`inner`){return n=>{if(n.graph!==e.graph)throw Error(`Cannot join streams from different graphs`);let r=new ga(n.graph,new ua),i=new Za(n.graph.getNextOperatorId(),n.connectReader(),e.connectReader(),r.writer,t);return n.graph.addOperator(i),r}}var $a=class extends ma{#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 ga(t.graph,new ua),r=new $a(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var eo=class extends fa{#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 to(e){return t=>{let n=new ga(t.graph,new ua),r=new eo(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var no=class extends ma{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return this.#e(e),e}};function ro(e){return t=>{let n=new ga(t.graph,new ua),r=new no(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var io=class extends fa{#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,Wa(r));this.#e=new Ka(s),i.setSizeCallback?.(()=>this.#e.size),i.setWindowFn?.(this.moveTopK.bind(this))}createTopK(e,t,n){return new Ga(e,t,n)}moveTopK({offset:e,limit:t}){let n=[],r=this.#e.move({offset:e,limit:t});r.moveIns.forEach(e=>qa(e,n)),r.moveOuts.forEach(e=>Ja(e,n)),r.changes&&this.output.sendData(new ca(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 ca(e))}processElement(e,t,n,r){let i=this.#e.processElement(e,t,n);qa(i.moveIn,r),Ja(i.moveOut,r)}};function ao(e,t){let n=t||{};return t=>{let r=new ga(t.graph,new ua),i=new io(t.graph.getNextOperatorId(),t.connectReader(),r.writer,e,n);return t.graph.addOperator(i),r}}function oo(e){return`pipe`in e}function so(e,t={}){let n=Object.fromEntries(Object.entries(t).filter(([e,t])=>!oo(t)));return Object.fromEntries(Object.entries(t).filter(([e,t])=>oo(t))),t=>{let r=`__original_key__`;return t.pipe(X(t=>{let i=e(t),a=wi(i),o={};o[r]=i;for(let[e,r]of Object.entries(n))o[e]=r.preMap(t);return[a,o]})).pipe(Da(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 co(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 lo(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 uo(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 fo(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 po(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 mo(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 ho(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 go={sum:co,count:lo,avg:uo,min:fo,max:po,median:mo,mode:ho};function _o(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(Xa((t,n)=>s(e(t),e(n)),{limit:n,offset:r,setSizeCallback:i,setWindowFn:a,groupKeyFn:o}),ya())}function vo(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}),ya())}function yo(e,t){return vo(ao,e,t)}var bo=`__virtual_synced__`,xo=`__virtual_has_local__`;function So(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:Co,count:wo,avg:To,min:Eo,max:Do}=go;function Oo(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`||Po(i))continue;let t=r.findIndex(e=>Ao(i,e));if(t===-1)throw new fr(e);n.set(e,t)}return{selectToGroupByIndex:n,groupByExpressions:r}}function ko(e,t,n,r,i,a,o){let s={[bo]:{preMap:([,e])=>So(e).synced,reduce:e=>{for(let[t,n]of e)if(!t&&n>0)return!1;return!0}},[xo]:{preMap:([,e])=>So(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]=jo(n);else if(Po(n)){let{transformed:r,extracted:i}=Fo(n,l);for(let[e,n]of Object.entries(i))t[e]=jo(n);c[e]=J(r)}}let u=o?([,e])=>({__singleGroup:!0,__correlationKey:e?.[o]?.__correlationKey}):()=>({__singleGroup:!0});if(e=e.pipe(so(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]);No(t,e,c)}let n=o?e.__correlationKey:void 0,i=n===void 0?`single_group`:`single_group_${wi(n)}`,s={...e,$selected:t},l=e[bo],u=e[xo];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(Mo(Jt(t),r||{},`$selected`));e=e.pipe(ja(([,e])=>Br(n({$selected:e.$selected}))))}if(i&&i.length>0)for(let t of i)e=e.pipe(ja(([,e])=>Br(t({$selected:e.$selected}))));return e}let c=Oo(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]=jo(t);else if(Po(t)){let{transformed:n,extracted:r}=Fo(t,p);for(let[e,t]of Object.entries(r))d[e]=jo(t);f[e]=J(n)}}if(e=e.pipe(so(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}`]}No(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]:wi(l),d={...e,$selected:i},p=e[bo],m=e[xo];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(Mo(Jt(t),r||{}));e=e.pipe(ja(([,e])=>n({$selected:e.$selected})))}if(i&&i.length>0)for(let t of i)e=e.pipe(ja(([,e])=>Br(t({$selected:e.$selected}))));return e}function Ao(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)=>Ao(e,t.args[n]));case`agg`:return e.name===t.name&&e.args?.length===t.args?.length&&(e.args||[]).every((e,n)=>Ao(e,t.args[n]));default:return!1}}function jo(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 Co(n);case`count`:return wo(i);case`avg`:return To(n);case`min`:return Eo(r);case`max`:return Do(r);default:throw new pr(e.name)}}function Mo(e,t,n=`$selected`){switch(e.type){case`agg`:{let r=e;for(let[e,i]of Object.entries(t))if(i.type===`agg`&&Io(r,i))return new G([n,e]);throw new mr(r.name)}case`func`:{let n=e,r=n.args.map(e=>Mo(e,t));return new Ut(n.name,r)}case`ref`:return e;case`val`:return e;default:throw new hr(e.type)}}function No(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 Po(e){return Kt(e)?e.type===`agg`?!0:e.type===`func`&&`args`in e?e.args.some(e=>Po(e)):!1:!1}function Fo(e,t){if(e.type===`agg`){let n=`__agg_${t.value++}`;return{transformed:new G([`$selected`,n]),extracted:{[n]:e}}}if(e.type===`func`){let n={},r=e.args.map(e=>{let r=Fo(e,t);return Object.assign(n,r.extracted),r.transformed});return{transformed:new Ut(e.name,r),extracted:n}}return{transformed:e,extracted:{}}}function Io(e,t){return e.name===t.name&&e.args.length===t.args.length&&e.args.every((e,n)=>Ao(e,t.args[n]))}function Lo(e,t,n,r,i,a,o,s,c,l){let u=n.map(e=>({compiledExpression:J(Mo(e.expression,r,`$selected`)),compareOptions:Ro(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=Mr(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 Mr(n.compareOptions)(e,t)}return Nr(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=Qt(e,d,i);if(n){r=n.collection;let i=n.path[0],a=Ro(u,r);if(i){let e=Mr(a);pi(i,n.path,r,a,e)}if(o=J(new G(n.path),!0),t=Qr(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=Qt(e,n,i);return J(r?new G(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(_o(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(yo(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 Ro(e,t){return e.compareOptions.stringSort===void 0?{...t.compareOptions,direction:e.compareOptions.direction,nulls:e.compareOptions.nulls}:e.compareOptions}function zo(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?Bo(t.where):void 0,r=Ho(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=ti(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(Bo(r))}catch(r){console.warn(`${e.id?`[${e.id}] `:``}Error processing where clause, falling back to full scan:`,r);let i=Bo(t.where);return t.optimizedOnly?void 0:n(i)}}function Bo(e){let t=Vr(e);return e=>{try{return Br(t(e))}catch{return!1}}}function Vo(e,t){let n=Bo(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 Ho(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=Ro(i,e);pi(t[0],t,e,o);let s=Qr(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=Mr(r.compareOptions)(Uo(e.value,r.expression),Uo(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 Uo(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 Vr(t)(e)}var Wo=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=Ci(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=Ci(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)}},Go=`__tanstack_db_direct`,Ko=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:Jr(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&&Sr(f.value,n)||r!==void 0&&Sr(f.value,r))&&(m=!0);let h=c&&n!==void 0&&r!==void 0&&Sr(n,r);if(!(m&&!h))if(n===void 0&&r!==void 0){let e=p.get(t);if(e){let n=e.value,i=Jr(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&&(!Sr(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 Wo((e,t)=>e.compareCreatedAt(t)),this.syncedData=new Wo(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[Go]===!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 qo(){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 Jo(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 Yo(e){let t=Jo(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(Xo(e))return new G(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 K(e)}function Xo(e){return e&&typeof e==`object`&&e.__refProxy===!0}function Zo(e,t){return new Ut(`eq`,[Z(e),Z(t)])}function Qo(e,t){return new Ut(`gt`,[Z(e),Z(t)])}function $o(e,t){return new Ut(`gte`,[Z(e),Z(t)])}function es(e,t){return new Ut(`lt`,[Z(e),Z(t)])}function ts(e,t,...n){return new Ut(`and`,[e,t,...n].map(e=>Z(e)))}function ns(e,t,...n){return new Ut(`or`,[e,t,...n].map(e=>Z(e)))}function rs(e,t){return new Ut(`in`,[Z(e),Z(t)])}var is=class{constructor(e){this.query=e,this.__brand=`ToArrayWrapper`}},as=class{constructor(e){this.query=e,this.__brand=`ConcatToArrayWrapper`}},os=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 ss(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`?Qo:es)(n,new K(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(Zo(r.expression,new K(i)))}let s=(i.compareOptions.direction===`asc`?Qo:es)(i.expression,new K(a));if(o.length===0)n.push(s);else{let e=[...o,s];n.push(e.reduce((e,t)=>ts(e,t)))}}return n.length===1?n[0]:n.reduce((e,t)=>ns(e,t))}var cs=class extends os{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&&mi(n.whereExpression,this.collection);let r=e=>{t(e),this.trackSentKeys(e)};this.callback=r,this.filteredCallback=n.whereExpression?Vo(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=ts(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?Bo(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:Zo(n,new K(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 G(_.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=ss(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=ts($o(r,new K(i)),es(r,new K(e)))}else a=Zo(r,new K(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()}},ls=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(qo())));let a=new cs(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 dn;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}},us=e=>setTimeout(()=>{e({didTimeout:!0,timeRemaining:()=>50})},0),ds=e=>{clearTimeout(e)},fs=typeof window<`u`&&`requestIdleCallback`in window?(e,t)=>window.requestIdleCallback(e,t):(e,t)=>us(e),ps=typeof window<`u`&&`cancelIdleCallback`in window?e=>window.cancelIdleCallback(e):ds,ms=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)}};ms.instance=null;var hs=ms,gs=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 ln(e,t,this.id)}setStatus(e,t=!1){if(e===`ready`&&!t)throw new sn(`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 cn(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)||hs.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){hs.getInstance().cancel(this),this.idleCallbackId!==null&&(ps(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&ps(this.idleCallbackId),this.idleCallbackId=fs(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(),hs.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&&(ps(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}},_s=Symbol(`liveQueryInternal`),vs=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=ys(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 Mn;if(t.committed)throw new Nn;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&&Sr(t,e.value))r=`update`;else{let e=this.config.utils[_s];throw new gn(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 Pn;if(e.committed)throw new Fn;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 Mn;if(e.committed)throw new Nn;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 tn(`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 Mn;if(e.committed)throw new Nn;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 un);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 gr(this.id,e);throw t.cause=e,t.stack=e.stack,t}else throw new gr(this.id,e)})}this.preloadPromise=null}};function ys(e){if(typeof e==`function`)return{cleanup:e};if(typeof e==`object`)return e}var bs=1;function xs(e,t){return e===t?0:e<t?-1:1}function Ss(e){return{kind:`constructor`,...e.name?{name:e.name}:{}}}function Cs(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=>Cs(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=>Cs(e)??null).sort((e,t)=>xs(ws(e),ws(t)))};if(e instanceof Map)return{__type:`map`,entries:Array.from(e.entries()).map(([e,t])=>({key:Cs(e)??null,value:Cs(t)??null})).sort((e,t)=>xs(ws(e.key),ws(t.key)))};if(e instanceof RegExp)return{__type:`regexp`,value:e.toString()};let t={},n=Object.entries(e).sort(([e],[t])=>xs(e,t));for(let[e,r]of n){let n=Cs(r);n!==void 0&&(t[e]=n)}return t}function ws(e){return e===null?`null`:Array.isArray(e)?`[${e.map(ws).join(`,`)}]`:typeof e==`object`?`{${Object.keys(e).sort((e,t)=>xs(e,t)).map(t=>`${JSON.stringify(t)}:${ws(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function Ts(e,t,n,r,i){let a=Ss(r),o=Cs(t)??null,s=Cs(i);return{signatureVersion:bs,signature:ws(Cs({signatureVersion:bs,expression:o,options:s??null})??null),indexId:e,name:n,expression:t,resolver:a,...s===void 0?{}:{options:s}}}function Es(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>Es(e));let t={};for(let[n,r]of Object.entries(e))t[n]=Es(r);return t}function Ds(e){return JSON.parse(JSON.stringify(e))}var Os=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(qo())),i=t.indexType??this.defaultIndexType;if(!i)throw new tn(`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=Ts(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:Ds(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:Es(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()}},ks=new Set([`find`,`findLast`,`findIndex`,`findLastIndex`,`filter`,`map`,`flatMap`,`forEach`,`some`,`every`,`reduce`,`reduceRight`]),As=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]),js=new Set([`set`,`delete`,`clear`,`add`]),Ms=new Set([`entries`,`keys`,`values`,`forEach`]);function Ns(e){return typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof RegExp)&&!Tr(e)}function Ps(e,t,n,r){if(ks.has(e))return function(...i){let a=i[0];if(typeof a!=`function`)return t.apply(n.copy_,i);let o=(e,t)=>{if(Ns(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 Fs(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(Ns(i)){let{proxy:n}=t(i,{tracker:e,prop:String(r)});a=n}return r++,{done:!1,value:a}},[Symbol.iterator](){return this}}}}function Is(e,t,n){return function(...r){let i=e.apply(t.copy_,r);return n(t),i}}function Ls(e,t,n,r,i,a,o){if(Ms.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 Rs(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]=Rs(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,Rs(e,t))}),n}if(e instanceof Set){let n=new Set;return t.set(e,n),e.forEach(e=>{n.add(Rs(e,t))}),n}if(Tr(e))return e;let n={};t.set(e,n);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=Rs(e[r],t));let r=Object.getOwnPropertySymbols(e);for(let i of r)n[i]=Rs(e[i],t);return n}var zs=0;function Bs(){return zs+=1,zs}function Vs(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=Vs(e,t);return n.set(e,r),r}}let i=new Map,a={copy_:Rs(e),originalObject:Rs(e),proxyCount:Bs(),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),!Sr(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(!Sr(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(As.has(e))return Is(n,a,o);let i=Ps(e,n,a,r);if(i)return i;if(t===Symbol.iterator)return Fs(a,r)}if(e instanceof Map||e instanceof Set){let i=t.toString();if(js.has(i))return Is(n,a,o);let s=Ls(i,t,n,e,a,r,o);if(s)return s}return n.bind(e)}if(Ns(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),Sr(i,r))Q(`Value unchanged, not tracking`);else{let e=a.originalObject[n],i=Sr(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]=Rs(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]=Rs(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 Hs(e){let t=e.map(e=>Vs(e));return{proxies:t.map(e=>e.proxy),getChanges:()=>t.map(e=>e.getChanges())}}function Us(e,t){let{proxy:n,getChanges:r}=Vs(e);return t(n),r()}function Ws(e,t){let{proxies:n,getChanges:r}=Hs(e);return t(n),r()}function Gs(){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 Ks(e){return typeof e==`object`&&!!e&&typeof e.hasPendingGraphRun==`function`}var qs=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=Ks(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))}},Js=[],Ys=[],Xs=0;function Zs(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 Qs(e){let t=new rc(e);return Js.push(t),t}function $s(){if(Ys.length>0)return Ys.slice(-1)[0]}function ec(e){qs.clear(e.id),Ys.push(e)}function tc(e){try{qs.flush(e.id)}finally{Ys=Ys.filter(t=>t.id!==e.id)}}function nc(e){let t=Js.findIndex(t=>t.id===e.id);t!==-1&&Js.splice(t,1)}var rc=class{constructor(e){if(e.mutationFn===void 0)throw new On;this.id=e.id??crypto.randomUUID(),this.mutationFn=e.mutationFn,this.state=`pending`,this.mutations=[],this.isPersisted=Gs(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=Xs++,this.metadata=e.metadata??{}}setState(e){this.state=e,(e===`completed`||e===`failed`)&&nc(this)}mutate(e){if(this.state!==`pending`)throw new kn;ec(this);try{e()}finally{tc(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=Zs(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 An;if(this.setState(`failed`),!t){let e=new Set;this.mutations.forEach(t=>e.add(t.globalKey));for(let t of Js)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 jn;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}},ic=class{constructor(e,t){this.insert=(e,t)=>{this.lifecycle.validateCollectionUsable(`insert`);let n=this.state,r=$s();if(!r&&!this.config.onInsert)throw new wn;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 hn(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=Qs({metadata:{[Go]:!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=$s();if(!r&&!this.config.onDelete)throw new En;if(Array.isArray(e)&&e.length===0)throw new xn;let i=Array.isArray(e)?e:[e],a=[];for(let e of i){if(!this.state.has(e))throw new Sn(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=Qs({autoCommit:!0,metadata:{[Go]:!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 an}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 on;if(`issues`in a&&a.issues)throw new en(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 on;if(`issues`in i&&i.issues)throw new en(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 pn(t):new mn(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 _n;let r=this.state;this.lifecycle.validateCollectionUsable(`update`);let i=$s();if(!i&&!this.config.onUpdate)throw new Tn;let a=Array.isArray(e),o=a?e:[e];if(a&&o.length===0)throw new vn;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 yn(e);return t}),u;u=a?Ws(l,s):[Us(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 bn(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=Qs({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=Qs({metadata:{[Go]:!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}},ac=class extends os{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 oc(e){let t=new sc(e);return e.utils?t.utils=e.utils:t.utils={},t}var sc=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 nn;if(!e.sync)throw new rn;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 tn(`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 ls,this._events=new ac,this._indexes=new Os,this._lifecycle=new gs(e,this.id),this._mutations=new ic(e,this.id),this._state=new Ko(e),this._sync=new vs(e,this.id),this.comparisonOpts=cc(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 zo(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 cc(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 lc(e){let t=uc(e),n=e,r,i=0;for(;i<10&&!Sr(n,r);)r=n,n=pc(n),i++;return{optimizedQuery:hc(n),sourceWhereClauses:t}}function uc(e){let t=new Map;if(!e.where||e.where.length===0)return t;let n=xc(vc(e.where).map(e=>bc(e))),r=fc(e);for(let[i,a]of n.singleSource)dc(e,i)&&!r.has(i)&&t.set(i,a);return t}function dc(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 fc(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 pc(e){return mc({...e,from:e.from.type===`queryRef`?new Ht(pc(e.from.query),e.from.alias):e.from,join:e.join?.map(e=>({...e,from:e.from.type===`queryRef`?new Ht(pc(e.from.query),e.from.alias):e.from}))})}function mc(e){if(!e.where||e.where.length===0)return e;if(!e.join||e.join.length===0){if(e.where.length>1){let t=Fc(vc(e.where));return{...e,where:[t]}}return e}let t=Sc(e,xc(vc(e.where.filter(e=>!Yt(e))).map(e=>bc(e)))),n=e.where.filter(e=>Yt(e));return n.length>0&&(t.where=[...t.where||[],...n]),t}function hc(e){return{...e,from:gc(e.from),join:e.join?.map(e=>({...e,from:gc(e.from)}))}}function gc(e){if(e.type===`collectionRef`)return e;let t=hc(e.query);if(_c(t)){let n=gc(t.from);return n.type===`collectionRef`?new Vt(n.collection,e.alias):new Ht(n.query,e.alias)}return new Ht(t,e.alias)}function _c(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 vc(e){let t=[];for(let n of e){let e=qt(n);t.push(...yc(e))}return t}function yc(e){if(e.type===`func`&&e.name===`and`){let t=[];for(let n of e.args)t.push(...yc(n));return t}else return[e]}function bc(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 xc(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,Fc(n));return{singleSource:r,multiSource:n.length>0?Fc(n):void 0}}function Sc(e,t){let n=new Set,r=fc(e),i=new Map;for(let[e,n]of t.singleSource)r.has(e)||i.set(e,n);let a=wc(e.from,i,n),o=e.join?e.join.map(e=>({...e,from:wc(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(Xt(r)):s.push(r);let l=s.length>1?[Fc(s.flatMap(e=>yc(qt(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 Cc(e){return{from:e.from.type===`collectionRef`?new Vt(e.from.collection,e.from.alias):new Ht(Cc(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 Vt(e.from.collection,e.from.alias):new Ht(Cc(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 wc(e,t,n){let r=t.get(e.alias);if(!r)return e.type===`collectionRef`?new Vt(e.collection,e.alias):new Ht(Cc(e.query),e.alias);if(e.type===`collectionRef`){let t={from:new Vt(e.collection,e.alias),where:[r]};return n.add(e.alias),new Ht(t,e.alias)}if(!Ac(e.query,r,e.alias)||Pc(e.query,r,e.alias))return new Ht(Cc(e.query),e.alias);let i=e.query.where||[],a={...Cc(e.query),where:[...i,r]};return n.add(e.alias),new Ht(a,e.alias)}function Tc(e,t,n){return e.select?jc(e.select)||Nc(e.select,t,n):!1}function Ec(e){return e.groupBy&&e.groupBy.length>0}function Dc(e){return e.having&&e.having.length>0}function Oc(e){return e.orderBy&&e.orderBy.length>0&&(e.limit!==void 0||e.offset!==void 0)}function kc(e){return e.fnSelect||e.fnWhere&&e.fnWhere.length>0||e.fnHaving&&e.fnHaving.length>0}function Ac(e,t,n){return!(Tc(e,t,n)||Ec(e)||Dc(e)||Oc(e)||kc(e))}function jc(e){for(let t of Object.values(e))if(typeof t==`object`){let e=t;if(e.type===`agg`||!(`type`in e)&&jc(e))return!0}return!1}function Mc(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(...Mc(n));break}return t}function Nc(e,t,n){let r=new Set;for(let[t,n]of Object.entries(e))t.startsWith(`__SPREAD_SENTINEL__`)||n instanceof G||r.add(t);let i=Mc(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 Pc(e,t,n){let r=Mc(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 G)||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 Fc(e){if(e.length===0)throw new vr;return e.length===1?e[0]:new Ut(`and`,e)}function Ic(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=Lc(y,e,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v);return y}function Lc(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}=Bc(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 nr(r);if(!w)throw new nr(S);let{activeSource:T,lazySource:E}=Hc(t.type,C,w),ee=Object.keys(n),{mainExpr:D,joinedExpr:O}=Rc(t.left,t.right,ee,b),k=J(D),A=J(O),j=e.pipe(X(([e,t])=>[Ir(k(t)),[e,t]])),M=x.pipe(X(([e,t])=>{let n={[b]:t};return[Ir(A(n)),[e,n]]}));if(![`inner`,`left`,`right`,`full`].includes(t.type))throw new ir(t.type);if(T){let e=T===`main`?t.from:m.from,n=e.type===`queryRef`&&(e.query.limit||e.query.offset),r=D.type===`func`||O.type===`func`;if(!n&&!r){let e=T===`main`?b:i;d.add(e);let t=T===`main`?j:M,n=Qt(m,T===`main`?O:D,E),r=n.collection,a=n.path[0];a&&pi(a,n.path,r);let o=t.pipe(ro(t=>{let i=_[e]||e,a=l[i];if(!a)throw new yr(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 G(n.path);if(!a.requestSnapshot({where:rs(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`?j=o:M=o}}return j.pipe(Qa(M,t.type),Vc(t.type))}function Rc(e,t,n,r){let i=n.filter(e=>e!==r),a=zc(e),o=zc(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 or:a===o?new ar(a):i.includes(a)?o===r?new lr:new cr(r):new sr(a)}function zc(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=zc(n);e&&t.add(e)}return t.size===1?Array.from(t)[0]:null}default:return null}}function Bc(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 Xn(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 ur(e.type)}}function Vc(e){return function(t){return t.pipe(ja(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 Hc(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 Uc(e){return e instanceof K?e.value:e}function Wc(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]=Uc(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]=Uc(n)}else{let e=t[n];(typeof e!=`object`||!e)&&(t[n]={}),t=t[n]}}}}function Gc(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]]=Uc(e.compiled(t))}}function Kc([e,t],n){let r={};for(let e of n)e.kind===`merge`?Wc(e,t,r):Gc(e,t,r);return[e,{...t,$selected:r}]}function qc(e,t,n){let r=[];return Xc([],t,r),e.pipe(X(e=>Kc(e,r)))}function Jc(e){return e.type===`agg`}function Yc(e){return e&&typeof e==`object`&&!Kt(e)}function Xc(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 G(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(Yc(t)){Xc([...e,r],t,n);continue}if(Jc(t)||Po(t))n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});else{if(t===void 0||!Kt(t)){n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>t});continue}if(t instanceof K){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 Zc=Symbol(`includesRouting`);function Qc(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;el(e);let{optimizedQuery:p,sourceWhereClauses:m}=lc(e),h=p;l.set(h,e),al(h,e,l);let g={...t},_={},v={},y={},{alias:b,input:x,collectionId:S}=tl(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])=>[fl(n,e),[t,n]])).pipe(Qa(u,`inner`)).pipe(ja(([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=Ic(w,h.join,y,S,b,g,c,l,n,r,i,a,o,s,e,Qc,_,v,m)),h.where&&h.where.length>0)for(let e of h.where){let t=J(qt(e));w=w.pipe(ja(([e,n])=>Br(t(n))))}if(h.fnWhere&&h.fnWhere.length>0)for(let e of h.fnWhere)w=w.pipe(ja(([t,n])=>Br(e(n))));let T=[],E=[];if(h.select){let e=cl(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(Da(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=sl(u.query,u.childCorrelationField,p);if(y){let e=y.collection,t=y.path,n=t[0];a.add(f),n&&pi(n,t,e),d=d.pipe(ro(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 G(t);n.requestSnapshot({where:rs(a,i)})}))}let b=Qc(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})});dl(h.select,t)}}if(h.distinct&&!h.fnSelect&&!h.select)throw new Gn;if(h.fnSelect&&h.groupBy&&h.groupBy.length>0)throw new Kn;w=h.fnSelect?w.pipe(X(([e,t])=>{let n=h.fnSelect(t);return[e,{...t,$selected:n}]})):h.select?qc(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[Zc]=n,[e,t]})));let ee=u?b:void 0;if(h.groupBy&&h.groupBy.length>0?w=ko(w,h.groupBy,h.having,h.select,h.fnHaving,S,ee):h.select&&Object.values(h.select).some(e=>e.type===`agg`||Po(e))&&(w=ko(w,[],h.having,h.select,h.fnHaving,S,ee)),h.having&&(!h.groupBy||h.groupBy.length===0)&&!(h.select&&Object.values(h.select).some(e=>e.type===`agg`)))throw new Jn;if(h.fnHaving&&h.fnHaving.length>0&&(!h.groupBy||h.groupBy.length===0))for(let e of h.fnHaving)w=w.pipe(ja(([t,n])=>e(n)));if(h.distinct&&(w=w.pipe(ka(([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:Lo(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=il(rl(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 Yn;let D={collectionId:S,pipeline:w.pipe(X(([e,t])=>{let n=t.$selected,r=il(rl(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,D),D}function $c(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 el(e,t=new Set){let n=$c(e);for(let e of n)if(t.has(e))throw new Zn(e,Array.from(t));let r=new Set([...t,...n]);if(e.from.type===`queryRef`&&el(e.from.query,r),e.join)for(let t of e.join)t.from.type===`queryRef`&&el(t.from.query,r)}function tl(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 Xn(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=Qc(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,rl(n)]}));return{alias:e.alias,input:_,collectionId:p.collectionId}}default:throw new Qn(e.type)}}function nl(e){return e instanceof K||e&&typeof e==`object`&&`type`in e&&e.type===`val`}function rl(e){return nl(e)?e.value:e}function il(e,t){if(!e||typeof e!=`object`)return e;let n=!1;for(let r of Yr)if(e[r]==null&&r in t){n=!0;break}if(!n)return e;for(let n of Yr)e[n]==null&&n in t&&(e[n]=t[n]);return e}function al(e,t,n){if(e.from.type===`queryRef`&&t.from.type===`queryRef`&&(n.set(e.from.query,t.from.query),al(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),al(i.from.query,a.from.query,n))}}function ol(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 sl(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 sl(e,t,n)}return{collection:n,path:[r]}}if(t.path.length>1){let[r,...i]=t.path,a=ol(e,r);return a?a.type===`queryRef`?sl(a.query,new G(i),n):{collection:a.collection,path:i}:void 0}}}function cl(e){let t=[];for(let[n,r]of Object.entries(e))n.startsWith(`__SPREAD_SENTINEL__`)||(r instanceof Gt?t.push({key:n,subquery:r}):ll(r)&&ul(r,n));return t}function ll(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.type!=`string`}function ul(e,t){for(let[n,r]of Object.entries(e))if(!n.startsWith(`__SPREAD_SENTINEL__`)){if(r instanceof Gt)throw Error(`Includes subqueries must be at the top level of select(). Found nested includes at "${t}.${n}".`);ll(r)&&ul(r,`${t}.${n}`)}}function dl(e,t){e[t]=new K(null)}function fl(e,t){let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}function pl(e,t){let n=e.type;if(n===`val`)return new K(e.value);if(n===`ref`){let n=e.path;if(Array.isArray(n)){if(n[0]===t&&n.length>1)return new G(n.slice(1));if(n.length===1&&n[0]!==void 0)return new G([n[0]])}return new G(Array.isArray(n)?n:[String(n)])}else{let n=[];for(let r of e.args){let e=pl(r,t);n.push(e)}return new Ut(e.name,n)}}function ml(e,t){return e.map(e=>{let n=pl(e.expression,t);return{...e,expression:n}})}var hl=new WeakMap;function gl(e){return e.utils?.[_s]?.getBuilder?.()}function _l(e,t){hl.set(e,t)}function vl(e){return hl.get(e)}var yl=class e{constructor(e={}){this.query={},this.query={...e}}_createRefForSource(t,n){let r;try{r=Object.keys(t)}catch{throw new Bn(n,t===null?`null`:`undefined`)}if(Array.isArray(t))throw new Bn(n,`array`);if(r.length!==1)throw r.length===0?new Bn(n,`empty object`):r.every(e=>!isNaN(Number(e)))?new Bn(n,`string`):new Ln(n);let i=r[0],a=t[i],o;if(a instanceof sc)o=new Vt(a,i);else if(a instanceof e){let e=a._getQuery();if(!e.from)throw new Rn(n);o=new Ht(e,i)}else throw new zn(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(Jo([...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 Vn;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(Jo(this._getCurrentAliases())),r=Xo(n)?Z(n):n;if(!Kt(r))throw new Un(bl(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?Yo(n):Jo(n)),i=Xo(r)?Z(r):r;if(!Kt(i))throw new Un(bl(i));let a=this.query.having||[];return new e({...this.query,having:[...a,i]})}select(t){let n=this._getCurrentAliases(),r=t(Jo(n));Xo(r)&&r.__path.length===1&&(r={[`__SPREAD_SENTINEL__${r.__path[0]}__0`]:!0});let i=Cl(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?Yo(r):Jo(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(Jo(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 Hn;return this.query}};function bl(e){return e===null?`null`:e===void 0?`undefined`:typeof e==`object`?`object`:typeof e}function xl(e){return e===void 0?Z(null):e instanceof Wt||e instanceof Ut||e instanceof G||e instanceof K?e:Z(e)}function Sl(e){return typeof e==`object`&&!!e&&!Kt(e)&&!e.__refProxy}function Cl(e,t=[]){if(!Sl(e))return xl(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 yl){n[r]=El(i,r,t,`collection`);continue}if(i instanceof is){if(!(i.query instanceof yl))throw Error(`toArray() must wrap a subquery builder`);n[r]=El(i.query,r,t,`array`);continue}if(i instanceof as){if(!(i.query instanceof yl))throw Error(`concat(toArray(...)) must wrap a subquery builder`);n[r]=El(i.query,r,t,`concat`);continue}n[r]=Cl(i,t)}return n}function wl(e){let t=[];switch(e.type){case`ref`:t.push(e);break;case`func`:for(let n of e.args??[])t.push(...wl(n));break}return t}function Tl(e,t){return wl(typeof e==`object`&&`expression`in e?e.expression:e).some(e=>e.path[0]!=null&&t.includes(e.path[0]))}function El(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=Dl(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=Dl(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 Ut(`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)Tl(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 wl(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||Sl(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=zt,_={...m,select:{[v]:h}}}return new Gt(_,o,s,t,f.length>0?f:void 0,p,r,v)}function Dl(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 Ol(e){return kl(e(new yl))}function kl(e){return e._getQuery()}function Al(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 Gt?r(n.query):Nl(n)&&i(n))}return r(e),t}function jl(e){let t=e.from;if(t.type===`collectionRef`)return t.collection;if(t.type===`queryRef`)return jl(t.query);throw Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(e)}`)}function Ml(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 Gt?i(n.query):Nl(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 Nl(e){return!(typeof e!=`object`||!e||e instanceof Gt||`type`in e&&typeof e.type==`string`||e.__refProxy)}function Pl(e){let t=typeof e.query==`function`?Ol(e.query):kl(e.query);if(e.requireObjectResult&&t.select&&!Nl(t.select))throw new qn;return t}function Fl(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 ca(r)),r.length}function*Il(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 Ll(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 Rl(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 zl(e,t){let{orderBy:n,limit:r,offset:i}=e,a=r!==void 0&&i!==void 0?r+i:r,o=n?ml(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 Bl(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=wi({minValues:l??null,offset:s,limit:i});if(n===u)return;let d=ml(a,r);return{minValues:l,normalizedOrderBy:d,loadRequestKey:u}}var Vl=Symbol.for(`@tanstack/db.collection-config-builder`),Hl=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=pl(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=Ll(Array.isArray(e)?e:[...e],this.sentToD2Keys),r=this.collectionConfigBuilder.currentSyncState.inputs[this.alias],i=Fl(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=zl(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=Il(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=ml(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[Vl]??=this.loadMoreIfNeeded.bind(this,t),this.sendChangesToPipeline(e,n[Vl])}loadNextItems(e,t){let n=this.getOrderByInfo();if(!n)return;let r=Bl(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=Rl(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)}},Ul=0,Wl=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-${++Ul}`,this.query=Pl({query:e.query,requireObjectResult:!0}),this.collections=Al(this.query);let t=Ml(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=Gl(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??jl(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),[_s]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(e){if(!this.windowFn)throw new xr;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??$s()?.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;qs.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=qs.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 ha,this.inputsCache=Object.fromEntries(Object.keys(this.collectionByAlias).map(e=>[e,this.graphCache.newInput()]));let e=Qc(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 br(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(to(e=>{let n=e.getInner();t.messagesCount+=n.length,n.reduce(au,s)}));let c=this.setupIncludesOutput(this.includesCache,t);return t.flushPendingChanges=()=>{let t=s.size>0,i=ru(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,nu(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(to(e=>{let r=e.getInner();t.messagesCount+=r.length;for(let[[e,t],i]of r){let[r,a,o,s]=t,c=eu(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=Jl(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=vl(i);a&&a!==this?(this.aliasDependencies[n]=[a],this.builderDependencies.add(a)):this.aliasDependencies[n]=[];let o=new Hl(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 Gl(e){return(t,n)=>{let r=e.get(t),i=e.get(n);return r&&i?r<i?-1:+(r>i):0}}function Kl(e){return e.materialization!==`collection`}function ql(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 Jl(e,t){return e.map(e=>{let n=new Map;e.pipeline.pipe(to(e=>{let r=e.getInner();t.messagesCount+=r.length;for(let[[e,t],i]of r){let[r,a,o,s]=t,c=eu(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=Jl(e.childCompilationResult.includes,t)),r})}function Yl(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 Xl(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 Zl(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[Zc]?.[r.compilationResult.fieldName],a=n?.correlationKey,o=eu(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[Zc]?.[r.compilationResult.fieldName],a=n?.correlationKey,o=eu(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 Ql(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 $l(e){for(let t of e)if(t.buffer.size>0||t.nestedSetups&&$l(t.nestedSetups))return!0;return!1}function eu(e,t){return t==null?e:JSON.stringify([e,t])}function tu(e,t,n,r,i){let a=new WeakMap,o=r?new WeakMap:null,s=null,c=o?Gl(o):void 0,l={collection:oc({id:`__child-collection:${e}-${t}-${wi(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=Yl(i)),l}function nu(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[Zc]?.[a.fieldName],s=o?.correlationKey,c=eu(s,o?.parentContext??null);if(s!=null){if(!a.childRegistry.has(c)){let e=tu(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=ql(a,a.childRegistry.get(c));r[a.fieldName]=o;let s=t.get(e);s&&s!==r&&(s[a.fieldName]=o)}}}let e=Kl(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=tu(n,a.fieldName,e,a.hasOrderBy,a.nestedSetups),a.childRegistry.set(e,i)),a.materialization===`collection`&&iu(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()}Zl(a,e,r),o.set(e,{entry:i,childChanges:r})}a.pendingChildChanges.clear()}let s=Xl(a);for(let[,{entry:e,childChanges:t}]of o)e.includesStates&&nu(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&&nu(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&&ru(t.includesStates)&&(nu(t.includesStates,t.collection,t.collection.id,null,t.syncMethods),c.add(e));let l=Kl(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]=ql(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[Zc]?.[a.fieldName],r=n?.correlationKey,i=eu(r,n?.parentContext??null);if(r!=null){let t=a.correlationToParentKeys.get(i);t&&(t.delete(e),t.size===0&&(Ql(a,i),a.childRegistry.delete(i),a.correlationToParentKeys.delete(i)))}}}}if(r)for(let[,e]of r)delete e.value[Zc]}function ru(e){for(let t of e)if(t.pendingChildChanges.size>0||t.nestedSetups&&$l(t.nestedSetups))return!0;return!1}function iu(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 au(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 ou(e){return new Wl(e).getConfig()}function su(e){if(typeof e==`function`)return cu(ou({query:e}));{let t=e,n=ou(t);return t.utils&&(n.utils={...n.utils,...t.utils}),cu(n)}}function cu(e){let t=oc(e),n=gl(e);return n&&_l(t,n),t}var lu=1;function uu(e,t=[]){let n=e&&typeof e==`object`&&typeof e.subscribeChanges==`function`&&typeof e.startSyncImmediate==`function`&&typeof e.id==`string`,r=(0,W.useRef)(null),i=(0,W.useRef)(null),a=(0,W.useRef)(null),o=(0,W.useRef)(0),s=(0,W.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 yl);if(n==null)r.current=null;else if(n instanceof sc)n.startSyncImmediate(),r.current=n;else if(n instanceof yl)r.current=su({query:e,startSync:!0,gcTime:lu});else if(n&&typeof n==`object`)r.current=su({startSync:!0,gcTime:lu,...n});else throw Error(`useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof n}`);i.current=[...t]}else r.current=su({startSync:!0,gcTime:lu,...e}),i.current=[...t];c&&(o.current=0,s.current=null);let l=(0,W.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,W.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,W.useSyncExternalStore)(l.current,u.current),f=(0,W.useRef)(null),p=(0,W.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 du=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(){}},fu=new class extends du{#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`}},pu={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},mu=new class{#e=pu;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 hu(e){setTimeout(e,0)}var gu=typeof window>`u`||`Deno`in globalThis;function _u(){}function vu(e,t){return typeof e==`function`?e(t):e}function yu(e){return typeof e==`number`&&e>=0&&e!==1/0}function bu(e,t){return Math.max(e+(t||0)-Date.now(),0)}function xu(e,t){return typeof e==`function`?e(t):e}function Su(e,t){return typeof e==`function`?e(t):e}function Cu(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Tu(o,t.options))return!1}else if(!Du(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 wu(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Eu(t.options.mutationKey)!==Eu(a))return!1}else if(!Du(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Tu(e,t){return(t?.queryKeyHashFn||Eu)(e)}function Eu(e){return JSON.stringify(e,(e,t)=>Mu(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Du(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>Du(e[n],t[n])):!1}var Ou=Object.prototype.hasOwnProperty;function ku(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ju(e)&&ju(t);if(!r&&!(Mu(e)&&Mu(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:Ou.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=ku(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Au(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 ju(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Mu(e){if(!Nu(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Nu(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Nu(e){return Object.prototype.toString.call(e)===`[object Object]`}function Pu(e){return new Promise(t=>{mu.setTimeout(t,e)})}function Fu(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:ku(e,t)}function Iu(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Lu(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ru=Symbol();function zu(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ru?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Bu(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 Vu=(()=>{let e=()=>gu;return{isServer(){return e()},setIsServer(t){e=t}}})();function Hu(){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 Uu=hu;function Wu(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Uu,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 $=Wu(),Gu=new class extends du{#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 Ku(e){return Math.min(1e3*2**e,3e4)}function qu(e){return(e??`online`)===`online`?Gu.isOnline():!0}var Ju=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Yu(e){let t=!1,n=0,r,i=Hu(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new Ju(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>fu.isFocused()&&(e.networkMode===`always`||Gu.isOnline())&&e.canRun(),u=()=>qu(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??(Vu.isServer()?0:3),o=e.retryDelay??Ku,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),Pu(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 Xu=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),yu(this.gcTime)&&(this.#e=mu.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Vu.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(mu.clearTimeout(this.#e),this.#e=void 0)}};function Zu(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=>{Bu(e,()=>t.signal,()=>n=!0)},u=zu(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?Lu:Iu;return{pages:s(e.pages,a,o),pageParams:s(e.pageParams,r,o)}};if(i&&a.length){let e=i===`backward`,t=e?$u:Qu,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:Qu(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 Qu(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 $u(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var ed=class extends Xu{#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=rd(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=rd(this.options);e.data!==void 0&&(this.setState(nd(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Fu(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(_u).catch(_u):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=>Su(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ru||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>xu(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:!bu(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=zu(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`?Zu(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=Yu({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Ju&&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 Ju){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,...td(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...nd(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 td(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:qu(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function nd(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function rd(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 id=class extends du{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=Hu(),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),od(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return sd(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return sd(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 Su(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&&!Au(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&cd(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||Su(this.options.enabled,this.#t)!==Su(t.enabled,this.#t)||xu(this.options.staleTime,this.#t)!==xu(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Su(this.options.enabled,this.#t)!==Su(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 ud(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(_u)),t}#g(){this.#b();let e=xu(this.options.staleTime,this.#t);if(Vu.isServer()||this.#r.isStale||!yu(e))return;let t=bu(this.#r.dataUpdatedAt,e)+1;this.#d=mu.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,!(Vu.isServer()||Su(this.options.enabled,this.#t)===!1||!yu(this.#p)||this.#p===0)&&(this.#f=mu.setInterval(()=>{(this.options.refetchIntervalInBackground||fu.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(mu.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(mu.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&&od(e,t),o=i&&cd(e,n,t,r);(a||o)&&(l={...l,...td(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=Fu(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=Fu(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:ld(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Su(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=Hu())},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),!Au(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 ad(e,t){return Su(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&Su(t.retryOnMount,e)===!1)}function od(e,t){return ad(e,t)||e.state.data!==void 0&&sd(e,t,t.refetchOnMount)}function sd(e,t,n){if(Su(t.enabled,e)!==!1&&xu(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&ld(e,t)}return!1}function cd(e,t,n,r){return(e!==t||Su(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&ld(e,n)}function ld(e,t){return Su(t.enabled,e)!==!1&&e.isStaleByTime(xu(t.staleTime,e))}function ud(e,t){return!Au(e.getCurrentResult(),t)}var dd=class extends Xu{#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||fd(),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=Yu({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 fd(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var pd=class extends du{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 dd({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=md(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=md(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=md(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=md(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=>wu(t,e))}findAll(e={}){return this.getAll().filter(t=>wu(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(_u))))}};function md(e){return e.options.scope?.id}var hd=class extends du{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??Tu(r,t),a=this.get(i);return a||(a=new ed({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=>Cu(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>Cu(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()})})}},gd=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new hd,this.#t=e.mutationCache||new pd,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=fu.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=Gu.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(xu(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=vu(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(_u).catch(_u)}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(_u)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(_u)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(xu(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(_u).catch(_u)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(_u).catch(_u)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return Gu.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(Eu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{Du(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(Eu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{Du(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||=Tu(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===Ru&&(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()}},_d=class extends $t{constructor(e){super(e),this.name=`QueryCollectionError`}},vd=class extends _d{constructor(){super(`[QueryCollection] queryKey must be provided.`),this.name=`QueryKeyRequiredError`}},yd=class extends _d{constructor(){super(`[QueryCollection] queryFn must be provided.`),this.name=`QueryFnRequiredError`}},bd=class extends _d{constructor(){super(`[QueryCollection] queryClient must be provided.`),this.name=`QueryClientRequiredError`}},xd=class extends _d{constructor(){super(`[QueryCollection] getKey must be provided.`),this.name=`GetKeyRequiredError`}},Sd=class extends _d{constructor(){super(`Collection must be in 'ready' state for manual sync operations. Sync not initialized yet.`),this.name=`SyncNotInitializedError`}},Cd=class extends _d{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name=`DuplicateKeyInBatchError`}},wd=class extends _d{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name=`UpdateOperationItemNotFoundError`}},Td=class extends _d{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name=`DeleteOperationItemNotFoundError`}},Ed=new WeakMap;function Dd(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 Od(e,t){let n=new Set;for(let r of e){if(n.has(r.key))throw new Cd(r.key);if(n.add(r.key),r.type===`update`){if(!t.collection._state.syncedData.has(r.key))throw new wd(r.key)}else if(r.type===`delete`&&!t.collection._state.syncedData.has(r.key))throw new Td(r.key)}}function kd(e,t){let n=Dd(e,t);Od(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 Ad(e){function t(){let t=e();if(!t)throw new Sd;return t}return{writeInsert(e){let n={type:`insert`,data:e},r=t(),i=Ed.get(r);if(i?.isActive){i.operations.push(n);return}kd(n,r)},writeUpdate(e){let n={type:`update`,data:e},r=t(),i=Ed.get(r);if(i?.isActive){i.operations.push(n);return}kd(n,r)},writeDelete(e){let n={type:`delete`,key:e},r=t(),i=Ed.get(r);if(i?.isActive){i.operations.push(n);return}kd(n,r)},writeUpsert(e){let n={type:`upsert`,data:e},r=t(),i=Ed.get(r);if(i?.isActive){i.operations.push(n);return}kd(n,r)},writeBatch(e){let n=t();if(Ed.get(n)?.isActive)throw Error(`Cannot nest writeBatch calls. Complete the current batch before starting a new one.`);let r={operations:[],isActive:!0};Ed.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&&kd(r.operations,n)}finally{r.isActive=!1,Ed.delete(n)}}}}function jd(e){if(!e)return;let t={};return e.where&&(t.where=Md(e.where)),e.orderBy?.length&&(t.orderBy=e.orderBy.map(e=>{let t={expression:Md(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 Md(e){if(!e)return null;switch(e.type){case`val`:return{type:`val`,value:Nd(e.value)};case`ref`:return{type:`ref`,path:[...e.path]};case`func`:return{type:`func`,name:e.name,args:e.args.map(e=>Md(e))};default:return null}}function Nd(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=>Nd(e)):typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Nd(t)])):e}var Pd=`queryCollection:gc:`,Fd=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 Id(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)=>Sr(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 vd;if(!n)throw new yd;if(!i)throw new bd;if(!d)throw new xd;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)},ee=(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},D=e=>{let{begin:f,write:p,commit:m,markReady:g,collection:v,metadata:D}=e,O=D,k=!1,A=!1,j=new Set,M=new Map,N=new Map,P=Promise.resolve(),F=e=>D?.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(!D)return;let n={...F(e)??{}};if(t.size===0){delete n.queryCollection,Object.keys(n).length===0?D.row.delete(e):D.row.set(e,n);return}D.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=>(P=P.then(e,e),P),I=e=>{let t=N.get(e);t&&(clearTimeout(t),N.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=O?.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(!D)return;let t=await ae(e),n=[];f(),t.forEach(({value:t,owners:r},i)=>{r.delete(e),ne(i,r),ee(i,e)&&n.push(t)}),n.forEach(e=>{p({type:`delete`,value:e})}),D.collection.delete(`${Pd}${e}`),m()},R=e=>{if(e.mode!==`ttl`)return;I(e.queryHash);let t=Math.max(0,e.expiresAt-Date.now()),n=setTimeout(()=>{N.delete(e.queryHash),ie(async()=>{let t=D?.collection.get(`${Pd}${e.queryHash}`),n=re(t,e.queryHash);!n||n.mode!==`ttl`||n.expiresAt>Date.now()||await oe(e.queryHash)})},t);N.set(e.queryHash,n)},se=async()=>{if(!D)return;let e=D.collection.list(Pd),t=Date.now();for(let{key:n,value:r}of e){let e=re(r,n.slice(Pd.length));e&&(e.mode===`ttl`&&e.expiresAt<=t?await oe(e.queryHash):e.mode===`ttl`&&R(e))}},ce=e=>{if(typeof t==`function`)return t(e);if(_===`on-demand`){let n=jd(e);return n===void 0?t:[...t,n]}else return t},le=D?.collection.list(Pd),z=!le||le.length===0?(A=!0,Promise.resolve()):ie(async()=>{try{await se()}finally{A=!0}}),ue=(e={},t=n)=>{if(!A)return z.then(()=>{let n=ue(e,t);return n===!0?void 0:n});let r=ce(e),d=Eu(r),f={...h,loadSubsetOptions:e},p=D?.collection.get(`${Pd}${d}`);if(re(p,d)!==void 0&&j.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 id(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?M.delete(d):M.set(d,_),T.set(d,(T.get(d)||0)+1),i.getQueryData(r)!==void 0)return(k||v.subscriberCount>0)&&me(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(k||v.subscriberCount>0)&&me(m,d),S},B=(e,t,n)=>{let i=Eu(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(),D&&D.collection.delete(`${Pd}${i}`),l.forEach(e=>{let t=c?n.get(e)?.value:s.get(e);if(!t)return;let r=u.get(e);if(r)Sr(t,r)||p({type:`update`,value:r});else{let n=te(e);n.delete(i),ne(e,n),ee(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(),j.delete(i),I(i),g()},de=async(e,t)=>{let n=await ae(Eu(e));v.status!==`cleaned-up`&&B(e,t,n)},fe=e=>{let t=Eu(e);return n=>{if(n.isSuccess){if(v.deferDataRefresh){v.deferDataRefresh.then(()=>{let e=b.observers.get(t);e&&e.refetch().catch(()=>{})});return}j.has(t)?de(e,n).catch(t=>{console.error(`[QueryCollection] Error reconciling query ${String(e)}:`,t)}):B(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())}},pe=e=>w.has(e),me=(e,t)=>{if(!pe(t)){let n=fe(x.get(t)),r=e.subscribe(n);w.set(t,r);let i=e.getCurrentResult();(i.isSuccess||i.isError)&&n(i)}},he=()=>{b.observers.forEach(me)},ge=()=>{w.forEach(e=>{e()}),w.clear()};k=!0;let _e=v.on(`subscribers:change`,({subscriberCount:e})=>{e>0?he():e===0&&ge()});if(_===`eager`){let e=ue({});e instanceof Promise&&e.catch(()=>{})}else A?g():z.then(()=>{g()});he(),b.observers.forEach((e,t)=>{fe(x.get(t))(e.getCurrentResult())});let ve=e=>{w.get(e)?.(),w.delete(e),I(e),j.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=D!==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),M.delete(e)},ye=e=>{let t=T.get(e)||0,n=b.observers.get(e),r=M.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&&D&&O?.row.scanPersisted){f(),D.collection.set(`${Pd}${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}ve(e)},V=e=>{ve(e)},be=i.getQueryCache().subscribe(e=>{let t=e.query.queryHash;e.type===`removed`&&x.has(t)&&ye(t)});return{loadSubset:_===`eager`?void 0:ue,unloadSubset:_===`eager`?void 0:e=>{let t=Eu(ce(e)),n=(T.get(t)||0)-1;n<=0?(T.set(t,0),ye(t)):T.set(t,n)},cleanup:async()=>{_e(),ge(),N.forEach(e=>{clearTimeout(e)}),N.clear();let e=[...x.values()],t=[...b.observers.keys()];for(let e of t)V(e);be(),await Promise.all(e.map(async e=>{await i.cancelQueries({queryKey:e,exact:!0}),i.removeQueries({queryKey:e,exact:!0})}))}}},O=async e=>{let t=[...x.values()].map(t=>b.observers.get(Eu(t)).refetch({throwOnError:e?.throwOnError}));return Promise.all(t)},k=(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)},A=e=>{let t=i.getQueryCache().findAll({queryKey:v});if(t.length>0)for(let n of t)k(n.queryKey,e);else k(v,e)},j=null,M=e=>{let{begin:n,write:r,commit:a,collection:o}=e;return j={collection:o,queryClient:i,queryKey:typeof t==`function`?t({}):t,getKey:d,begin:n,write:r,commit:a,updateCacheData:A},D(e)},N=Ad(()=>j),P=f?async e=>{let t=await f(e)??{};return t.refetch!==!1&&await O(),t}:void 0,F=p?async e=>{let t=await p(e)??{};return t.refetch!==!1&&await O(),t}:void 0,te=m?async e=>{let t=await m(e)??{};return t.refetch!==!1&&await O(),t}:void 0,ne=new Fd(b,O,N);return{...g,getKey:d,syncMode:_,sync:{sync:M},onInsert:P,onUpdate:F,onDelete:te,utils:ne}}var Ld=`/api`;async function Rd(e,t){let n=await fetch(`${Ld}${e}`,t);if(!n.ok)throw Error(`${n.status} ${n.statusText}`);return n.json()}function zd(e,t){return Rd(`/memories/${e}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})}function Bd(e){return Rd(`/memories/${e}`,{method:`DELETE`})}function Vd(){return Rd(`/projects`)}function Hd(e,t){return Rd(`/projects/${e}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:t})})}function Ud(e,t){return Rd(`/memories/${e}/projects`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({projectId:t})})}function Wd(e,t){return Rd(`/memories/${e}/projects/${t}`,{method:`DELETE`})}function Gd(){return Rd(`/syntheses`)}function Kd(e){return Rd(`/projects/${e}/synthesis`,{method:`POST`})}function qd(e){return Rd(`/projects/${e}/synthesis/in-flight`,{method:`DELETE`})}function Jd(e){return Rd(`/projects/${e}/stats`)}function Yd(e,t){return Rd(`/projects/${e}/activity${t===void 0?``:`?days=${t}`}`)}function Xd(e){return Rd(`/activity${e===void 0?``:`?days=${e}`}`)}var Zd=new gd,Qd=oc(Id({queryKey:[`memories`],queryFn:async()=>{let e=await fetch(`/api/memories`);if(!e.ok)throw Error(`${e.status}`);return e.json()},queryClient:Zd,getKey:e=>e.id,onUpdate:async({transaction:e})=>{try{await Promise.all(e.mutations.map(e=>{let t=e.changes;return zd(e.original.id,{content:t.content,tags:t.tags,type:t.type,pinned:t.pinned})}))}catch{Ct.error(`Failed to save — changes may not have been stored`)}},onDelete:async({transaction:e})=>{try{await Promise.all(e.mutations.map(e=>Bd(e.original.id)))}catch{Ct.error(`Failed to delete — try again`)}}})),$d=oc(Id({queryKey:[`syntheses`],queryFn:Gd,queryClient:Zd,getKey:e=>e.id})),ef=oc(Id({queryKey:[`projects`],queryFn:Vd,queryClient:Zd,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():Hd(e.original.id,t.name)}))}}));export{m as C,c as D,o as E,g as S,u as T,st as _,Ud as a,it as b,Jd as c,qd as d,Kd as f,Ct as g,Rt as h,$d as i,zd as l,Zo as m,ef as n,Xd as o,uu as p,Zd as r,Yd as s,Qd as t,Wd as u,nt as v,f as w,rt as x,tt as y};
|