@fuma-content/studio 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/build/client/assets/{QueryClientProvider-Cys2v_1v.js → QueryClientProvider-BFSUF51X.js} +1 -1
  2. package/build/client/assets/actions-ByenKsIt.js +1 -0
  3. package/build/client/assets/actions-ClHPL1CP.js +1 -0
  4. package/build/client/assets/badge-BnhEE6iu.js +1 -0
  5. package/build/client/assets/{client-Cfd36Zz-.js → client-BEKU4RIg.js} +146 -146
  6. package/build/client/assets/client-DBU2dkUR.js +1 -0
  7. package/build/client/assets/client-DvwvjHta.js +1 -0
  8. package/build/client/assets/client-wd2sce2I.js +8 -0
  9. package/build/client/assets/dropdown-menu-By_XeFX4.js +1 -0
  10. package/build/client/assets/entry.rsc-J_U0YQEr.js +1 -0
  11. package/build/client/assets/{index-DL539Bhx.js → index-B5GacMxj.js} +1 -1
  12. package/build/client/assets/index-BTaHNKf7.js +1 -0
  13. package/build/client/assets/index-BgFxGtat.js +1 -0
  14. package/build/client/assets/index-CG_0cSZQ.js +1 -0
  15. package/build/client/assets/index-CfCSvolS.js +1 -0
  16. package/build/client/assets/{index-C37mbJ0i.js → index-D8KuzOxG.js} +1 -1
  17. package/build/client/assets/index-DrT4Adhh.js +41 -0
  18. package/build/client/assets/{index-DXHuzvfN.js → index-El_a1Yhs.js} +1 -1
  19. package/build/client/assets/index-QYLIz8qa.js +1 -0
  20. package/build/client/assets/layout-BPVd8vtW.js +1 -0
  21. package/build/client/assets/{mdx-CehodSrM.js → mdx-DBJIR6uw.js} +1 -1
  22. package/build/client/assets/page-BJL5nvn-.js +1 -0
  23. package/build/client/assets/page-eyuUZvVn.js +1 -0
  24. package/build/client/assets/popover-BowiFsDm.js +1 -0
  25. package/build/client/assets/{react-D58ornpH.js → react-CzFdRS7Y.js} +7 -7
  26. package/build/client/assets/root-7fvd-0uP.js +1 -0
  27. package/build/client/assets/root-B0B6-NU5.css +1 -0
  28. package/build/client/assets/{root-CNcQf1GA.js → root-jg-0qm8s.js} +1 -1
  29. package/build/client/assets/route-BLLsZ_zO.js +1 -0
  30. package/build/client/assets/{router-XCTsiXqQ.js → router-QEl8O8lm.js} +1 -1
  31. package/build/client/assets/select-BI356bZ1.js +1 -0
  32. package/build/client/assets/separator-0kwG7IIM.js +1 -0
  33. package/build/client/assets/sidebar-ByyQE2QS.js +12 -0
  34. package/build/client/assets/{site-header-1Aor7-g4.js → site-header-iBpA4Sim.js} +1 -1
  35. package/build/client/assets/spinner-D35u7i0p.js +1 -0
  36. package/build/client/assets/tooltip-v-_I4rCw.js +16 -0
  37. package/build/client/assets/use-sync-yCWvjE_m.js +2 -0
  38. package/build/client/assets/{yaml-DUnUkeX8.js → yaml-BnQf_2Zt.js} +1 -1
  39. package/build/server/__ssr_build/__vite_rsc_assets_manifest.js +213 -133
  40. package/build/server/__ssr_build/assets/{actions-DLZnfFzU.js → actions-C5Kv8XYU.js} +2 -2
  41. package/build/server/__ssr_build/assets/{actions-D6dLhck1.js → actions-DQIBBM15.js} +4 -4
  42. package/build/server/__ssr_build/assets/{badge-CH6ntch2.js → badge-B48L9yYO.js} +1 -1
  43. package/build/server/__ssr_build/assets/{client-C-WcMcGh.js → client-AuWNsacU.js} +3 -3
  44. package/build/server/__ssr_build/assets/client-BHaLyky8.js +1162 -0
  45. package/build/server/__ssr_build/assets/{client-DX-wDNer.js → client-BogEWrwz.js} +9 -5
  46. package/build/server/__ssr_build/assets/{client-JNaR8Jey.js → client-DXOHI3cC.js} +2808 -4397
  47. package/build/server/__ssr_build/assets/{dropdown-menu-gcIcDMHP.js → dropdown-menu-CnDgV_JY.js} +7 -9
  48. package/build/server/__ssr_build/assets/{entry.rsc-Cg_DxYkh.js → entry.rsc-aOU-YPkj.js} +1 -1
  49. package/build/server/__ssr_build/assets/{index-PpqpVA51.js → index-B6ajh-UP.js} +1 -1
  50. package/build/server/__ssr_build/assets/index-BPd5y8T-.js +76 -0
  51. package/build/server/__ssr_build/assets/{button-U-KvP9zg.js → index-By9m5mBe.js} +3272 -3175
  52. package/build/server/__ssr_build/assets/index-Ch7b9Ofo.js +37 -0
  53. package/build/server/__ssr_build/assets/{index-BJ-AF-IL.js → index-Cw6b1mnl.js} +8 -7
  54. package/build/server/__ssr_build/assets/{index-BloUStie.js → index-kCa2P0Xn.js} +4 -75
  55. package/build/server/__ssr_build/assets/{index-CWwW5yWZ.js → index-tFzyztyE.js} +2 -2
  56. package/build/server/__ssr_build/assets/{layout-B79fq6F-.js → layout-CC-HJHWR.js} +13 -11
  57. package/build/server/__ssr_build/assets/{mdx-bmeV1kyx.js → mdx-D9VFmsYC.js} +1 -1
  58. package/build/server/__ssr_build/assets/{page-CxhOzrct.js → page-BVUd9aDy.js} +10 -8
  59. package/build/server/__ssr_build/assets/{page-DxtKhA1K.js → page-C_wQzy3_.js} +13 -11
  60. package/build/server/__ssr_build/assets/popover-CzQgoguQ.js +321 -0
  61. package/build/server/__ssr_build/assets/{root-TWeSpY2W.js → root-BmMc6_zA.js} +1 -1
  62. package/build/server/__ssr_build/assets/route-CNYc37pV.js +860 -0
  63. package/build/server/__ssr_build/assets/{spinner-w3Q_wkh3.js → select-B8QQSB6X.js} +10 -25
  64. package/build/server/__ssr_build/assets/{separator-CKrKBtv4.js → separator-C601eKPH.js} +2 -2
  65. package/build/server/__ssr_build/assets/{sidebar-DoXmiwf0.js → sidebar-C6fHDjcx.js} +237 -65
  66. package/build/server/__ssr_build/assets/{site-header-pFjDV73T.js → site-header-Bmsr3a30.js} +2 -2
  67. package/build/server/__ssr_build/assets/spinner-D5zAJQcS.js +19 -0
  68. package/build/server/__ssr_build/assets/{tooltip-B2NV0tpS.js → tooltip-B3A57zPO.js} +1211 -1211
  69. package/build/server/__ssr_build/assets/{use-sync-p_-o0jkt.js → use-sync-DTZgOM1O.js} +29 -1185
  70. package/build/server/__ssr_build/assets/{yaml-BEdFfhvc.js → yaml-xJU1Ur4O.js} +1 -1
  71. package/build/server/__ssr_build/index.js +31 -15
  72. package/build/server/__vite_rsc_assets_manifest.js +213 -133
  73. package/build/server/assets/{actions-C92yn6jE.js → actions-BbMzIy5J.js} +2 -2
  74. package/build/server/assets/{actions-CWWFIcb1.js → actions-CjWBMAed.js} +2 -2
  75. package/build/server/assets/{actions-DZdN0IBq.js → actions-cRzXiMyR.js} +2 -2
  76. package/build/server/assets/{config-Cb909uq6.js → config-Dka4Bvz4.js} +10 -10
  77. package/build/server/assets/{layout-CRw_6FCt.js → layout-CIIfFN0v.js} +2 -2
  78. package/build/server/assets/{page-BfKoQQmw.js → page-pyqagPXb.js} +2 -2
  79. package/build/server/assets/root-B0B6-NU5.css +1 -0
  80. package/build/server/assets/{root-BqMNAwvK.js → root-D1ebFoST.js} +1 -1
  81. package/build/server/assets/{route-DiqCR5uw.js → route-C7QEArEP.js} +13911 -5699
  82. package/build/server/index.js +40 -15
  83. package/dist/bin.mjs +4 -4
  84. package/dist/package.mjs +1 -1
  85. package/package.json +32 -15
  86. package/build/client/assets/actions-BIaFztcg.js +0 -1
  87. package/build/client/assets/actions-Bws1O3FH.js +0 -1
  88. package/build/client/assets/badge-C70RdDmr.js +0 -1
  89. package/build/client/assets/button-B0G-joJA.js +0 -41
  90. package/build/client/assets/client-C814jsdE.js +0 -1
  91. package/build/client/assets/client-wwp8K9Xz.js +0 -1
  92. package/build/client/assets/dropdown-menu-Re3QusA0.js +0 -1
  93. package/build/client/assets/entry.rsc-CdTwhQ3_.js +0 -1
  94. package/build/client/assets/index-DZ8LIlZu.js +0 -1
  95. package/build/client/assets/index-DprkZK2S.js +0 -1
  96. package/build/client/assets/index-UnlOgAz7.js +0 -1
  97. package/build/client/assets/layout-C5TjiFIx.js +0 -1
  98. package/build/client/assets/page-CiRIEJz9.js +0 -1
  99. package/build/client/assets/page-DBIuN_hk.js +0 -1
  100. package/build/client/assets/root-CbriXo_i.css +0 -1
  101. package/build/client/assets/root-DJ8qMHCd.js +0 -1
  102. package/build/client/assets/separator-BDe8wWVP.js +0 -1
  103. package/build/client/assets/sidebar-DNKkYLTA.js +0 -12
  104. package/build/client/assets/spinner-O3ZbB6fn.js +0 -1
  105. package/build/client/assets/tooltip-B4fI3WTO.js +0 -16
  106. package/build/client/assets/use-sync-CfDyibsS.js +0 -9
  107. package/build/server/assets/root-CbriXo_i.css +0 -1
  108. /package/build/server/__ssr_build/assets/{root-BYlluTc0.js → root-S8l7oX7x.js} +0 -0
  109. /package/build/server/assets/{root-ByROcfN4.js → root-DRYtk85G.js} +0 -0
@@ -0,0 +1,12 @@
1
+ import{r as z,f as us,g as hs,j as R}from"./react-CzFdRS7Y.js";import{S as er,p as Fs,r as ce,s as Ut,a as Je,n as tr,i as js,b as Bs,c as sr,d as dt,f as nr,e as rr,g as Ls,h as ir,j as ft,q as En}from"./query-z9oLNeTD.js";import{c as or,B as Rn,X as ar,d as N,S as cr,e as lr}from"./index-DrT4Adhh.js";import{R as ur,C as hr,ao as dr,am as fr,an as pr,P as yr,O as gr,T as mr,i as wr,m as vr}from"./tooltip-v-_I4rCw.js";const br=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],Sr=or("panel-left",br);var xr=class extends er{constructor(s,e){super(),this.options=e,this.#e=s,this.#o=null,this.#i=Fs(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#n=void 0;#r;#h;#i;#o;#y;#d;#f;#c;#l;#a;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),zs(this.#t,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Vt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Vt(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#S(),this.#t.removeObserver(this)}setOptions(s){const e=this.options,t=this.#t;if(this.options=this.#e.defaultQueryOptions(s),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ce(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#x(),this.#t.setOptions(this.options),e._defaulted&&!Ut(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const n=this.hasListeners();n&&Ns(this.#t,t,this.options,e)&&this.#u(),this.updateResult(),n&&(this.#t!==t||ce(this.options.enabled,this.#t)!==ce(e.enabled,this.#t)||Je(this.options.staleTime,this.#t)!==Je(e.staleTime,this.#t))&&this.#g();const r=this.#m();n&&(this.#t!==t||ce(this.options.enabled,this.#t)!==ce(e.enabled,this.#t)||r!==this.#a)&&this.#w(r)}getOptimisticResult(s){const e=this.#e.getQueryCache().build(this.#e,s),t=this.createResult(e,s);return Ir(this,t)&&(this.#n=t,this.#h=this.options,this.#r=this.#t.state),t}getCurrentResult(){return this.#n}trackResult(s,e){return new Proxy(s,{get:(t,n)=>(this.trackProp(n),e?.(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#i.status==="pending"&&this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(t,n))})}trackProp(s){this.#p.add(s)}getCurrentQuery(){return this.#t}refetch({...s}={}){return this.fetch({...s})}fetchOptimistic(s){const e=this.#e.defaultQueryOptions(s),t=this.#e.getQueryCache().build(this.#e,e);return t.fetch().then(()=>this.createResult(t,e))}fetch(s){return this.#u({...s,cancelRefetch:s.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#u(s){this.#x();let e=this.#t.fetch(this.options,s);return s?.throwOnError||(e=e.catch(tr)),e}#g(){this.#b();const s=Je(this.options.staleTime,this.#t);if(js||this.#n.isStale||!Bs(s))return;const t=sr(this.#n.dataUpdatedAt,s)+1;this.#c=dt.setTimeout(()=>{this.#n.isStale||this.updateResult()},t)}#m(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#w(s){this.#S(),this.#a=s,!(js||ce(this.options.enabled,this.#t)===!1||!Bs(this.#a)||this.#a===0)&&(this.#l=dt.setInterval(()=>{(this.options.refetchIntervalInBackground||nr.isFocused())&&this.#u()},this.#a))}#v(){this.#g(),this.#w(this.#m())}#b(){this.#c&&(dt.clearTimeout(this.#c),this.#c=void 0)}#S(){this.#l&&(dt.clearInterval(this.#l),this.#l=void 0)}createResult(s,e){const t=this.#t,n=this.options,r=this.#n,i=this.#r,o=this.#h,c=s!==t?s.state:this.#s,{state:l}=s;let u={...l},h=!1,y;if(e._optimisticResults){const I=this.hasListeners(),v=!I&&zs(s,e),x=I&&Ns(s,t,e,n);(v||x)&&(u={...u,...rr(l.data,s.options)}),e._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:f,errorUpdatedAt:d,status:p}=u;y=u.data;let g=!1;if(e.placeholderData!==void 0&&y===void 0&&p==="pending"){let I;r?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(I=r.data,g=!0):I=typeof e.placeholderData=="function"?e.placeholderData(this.#f?.state.data,this.#f):e.placeholderData,I!==void 0&&(p="success",y=Ls(r?.data,I,e),h=!0)}if(e.select&&y!==void 0&&!g)if(r&&y===i?.data&&e.select===this.#y)y=this.#d;else try{this.#y=e.select,y=e.select(y),y=Ls(r?.data,y,e),this.#d=y,this.#o=null}catch(I){this.#o=I}this.#o&&(f=this.#o,y=this.#d,d=Date.now(),p="error");const m=u.fetchStatus==="fetching",w=p==="pending",S=p==="error",b=w&&m,k=y!==void 0,D={status:p,fetchStatus:u.fetchStatus,isPending:w,isSuccess:p==="success",isError:S,isInitialLoading:b,isLoading:b,data:y,dataUpdatedAt:u.dataUpdatedAt,error:f,errorUpdatedAt:d,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:m,isRefetching:m&&!w,isLoadingError:S&&!k,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:S&&k,isStale:ds(s,e),refetch:this.refetch,promise:this.#i,isEnabled:ce(e.enabled,s)!==!1};if(this.options.experimental_prefetchInRender){const I=D.data!==void 0,v=D.status==="error"&&!I,x=B=>{v?B.reject(D.error):I&&B.resolve(D.data)},M=()=>{const B=this.#i=D.promise=Fs();x(B)},K=this.#i;switch(K.status){case"pending":s.queryHash===t.queryHash&&x(K);break;case"fulfilled":(v||D.data!==K.value)&&M();break;case"rejected":(!v||D.error!==K.reason)&&M();break}}return D}updateResult(){const s=this.#n,e=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#h=this.options,this.#r.data!==void 0&&(this.#f=this.#t),Ut(e,s))return;this.#n=e;const t=()=>{if(!s)return!0;const{notifyOnChangeProps:n}=this.options,r=typeof n=="function"?n():n;if(r==="all"||!r&&!this.#p.size)return!0;const i=new Set(r??this.#p);return this.options.throwOnError&&i.add("error"),Object.keys(this.#n).some(o=>{const a=o;return this.#n[a]!==s[a]&&i.has(a)})};this.#C({listeners:t()})}#x(){const s=this.#e.getQueryCache().build(this.#e,this.options);if(s===this.#t)return;const e=this.#t;this.#t=s,this.#s=s.state,this.hasListeners()&&(e?.removeObserver(this),s.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#C(s){ir.batch(()=>{s.listeners&&this.listeners.forEach(e=>{e(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Cr(s,e){return ce(e.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&e.retryOnMount===!1)}function zs(s,e){return Cr(s,e)||s.state.data!==void 0&&Vt(s,e,e.refetchOnMount)}function Vt(s,e,t){if(ce(e.enabled,s)!==!1&&Je(e.staleTime,s)!=="static"){const n=typeof t=="function"?t(s):t;return n==="always"||n!==!1&&ds(s,e)}return!1}function Ns(s,e,t,n){return(s!==e||ce(n.enabled,s)===!1)&&(!t.suspense||s.state.status!=="error")&&ds(s,t)}function ds(s,e){return ce(e.enabled,s)!==!1&&s.isStaleByTime(Je(e.staleTime,s))}function Ir(s,e){return!Ut(s.getCurrentResult(),e)}class Fe{}class Ke extends Fe{constructor(e,t){super(),this.collection=e,this.alias=t,this.type="collectionRef"}}class oe extends Fe{constructor(e,t){super(),this.query=e,this.alias=t,this.type="queryRef"}}class Y extends Fe{constructor(e){super(),this.path=e,this.type="ref"}}class X extends Fe{constructor(e){super(),this.value=e,this.type="val"}}class se extends Fe{constructor(e,t){super(),this.name=e,this.args=t,this.type="func"}}class kn extends Fe{constructor(e,t){super(),this.name=e,this.args=t,this.type="agg"}}function et(s){return s instanceof kn||s instanceof se||s instanceof Y||s instanceof X}function fs(s){return typeof s=="object"&&"expression"in s?s.expression:s}function $s(s){return typeof s=="object"&&"expression"in s?s.expression:s}function Us(s){return typeof s=="object"&&"expression"in s&&s.residual===!0}function Er(s){return{expression:s,residual:!0}}function Rr(s,e){if(s.from.alias===e)return s.from;for(const t of s.join||[])if(t.from.alias===e)return t.from}function tt(s,e,t){if(e.path.length!==0){if(e.path.length===1){const n=e.path[0];if(s.select){const r=s.select[n];if(r&&r.type==="ref")return tt(s,r,t)}return{collection:t,path:[n]}}if(e.path.length>1){const[n,...r]=e.path,i=Rr(s,n);return i?i.type==="queryRef"?tt(i.query,new Y(r),t):{collection:i.collection,path:r}:void 0}}}class ne extends Error{constructor(e){super(e),this.name="TanStackDBError"}}class Vs extends ne{constructor(e,t,n){const r=`${e==="insert"?"Insert":"Update"} validation failed: ${t.map(i=>`
2
+ - ${i.message} - path: ${i.path}`).join("")}`;super(n||r),this.name="SchemaValidationError",this.type=e,this.issues=t}}class it extends ne{constructor(e){super(e),this.name="CollectionConfigurationError"}}class kr extends it{constructor(){super("Collection requires a config")}}class Or extends it{constructor(){super("Collection requires a sync config")}}class _r extends it{constructor(){super("Schema must implement the standard-schema interface")}}class qs extends it{constructor(){super("Schema validation must be synchronous")}}class ot extends ne{constructor(e){super(e),this.name="CollectionStateError"}}class Ar extends ot{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}}class Mr extends ot{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}}class Tr extends ot{constructor(){super("Collection is in error state")}}class Pr extends ot{constructor(){super("Active subscribers count is negative - this should never happen")}}class he extends ne{constructor(e){super(e),this.name="CollectionOperationError"}}class Dr extends he{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}}class Kr extends he{constructor(e,t){const n=e===null?"null":typeof e;super(`getKey returned an invalid key type. Expected string or number, but got ${n}: ${JSON.stringify(e)}. Item: ${JSON.stringify(t)}`)}}class Fr extends he{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}}class jr extends he{constructor(e,t,n){const 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)}}class Br extends he{constructor(){super("The first argument to update is missing")}}class Lr extends he{constructor(){super("No keys were passed to update")}}class zr extends he{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}}class Nr extends he{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.`)}}class $r extends he{constructor(){super("No keys were passed to delete")}}class Ur extends he{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}}class ps extends ne{constructor(e){super(e),this.name="MissingHandlerError"}}class Vr extends ps{constructor(){super("Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.")}}class qr extends ps{constructor(){super("Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.")}}class Wr extends ps{constructor(){super("Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.")}}class xe extends ne{constructor(e){super(e),this.name="TransactionError"}}class Gr extends xe{constructor(){super("mutationFn is required when creating a transaction")}}class Hr extends xe{constructor(){super("You can no longer call .mutate() as the transaction is no longer pending")}}class Qr extends xe{constructor(){super("You can no longer call .rollback() as the transaction is already completed")}}class Jr extends xe{constructor(){super("You can no longer call .commit() as the transaction is no longer pending")}}class Ws extends xe{constructor(){super("No pending sync transaction to write to")}}class Gs extends xe{constructor(){super("The pending sync transaction is already committed, you can't still write to it.")}}class Yr extends xe{constructor(){super("No pending sync transaction to commit")}}class Zr extends xe{constructor(){super("The pending sync transaction is already committed, you can't commit it again.")}}class Oe extends ne{constructor(e){super(e),this.name="QueryBuilderError"}}class Xr extends Oe{constructor(e){super(`Only one source is allowed in the ${e}`)}}class ei extends Oe{constructor(e){super(`A sub query passed to a ${e} must have a from clause itself`)}}class ti extends Oe{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.`)}}class pt extends Oe{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}`)}}class si extends Oe{constructor(){super("Join condition must be an equality expression")}}class ni extends Oe{constructor(){super("Query must have a from clause")}}class Hs extends Oe{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`)}}class re extends ne{constructor(e){super(e),this.name="QueryCompilationError"}}class ri extends re{constructor(){super("DISTINCT requires a SELECT clause.")}}class ii extends re{constructor(){super("HAVING clause requires GROUP BY clause")}}class oi extends re{constructor(){super("LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results")}}class On extends re{constructor(e,t,n){const 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}`)}}class ai extends re{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.`)}}class ci extends re{constructor(e){super(`Unsupported FROM type: ${e}`)}}class li extends re{constructor(e){super(`Unknown expression type: ${e}`)}}class ui extends re{constructor(){super("Reference path cannot be empty")}}class hi extends re{constructor(e){super(`Unknown function: ${e}`)}}class Qs extends re{constructor(e){super(`Collection "${e}" not found during compilation of join`)}}class _e extends ne{constructor(e){super(e),this.name="JoinError"}}class di extends _e{constructor(e){super(`Unsupported join type: ${e}`)}}class fi extends _e{constructor(e){super(`Invalid join condition: both expressions refer to the same source "${e}"`)}}class pi extends _e{constructor(){super("Invalid join condition: expressions must reference source aliases")}}class yi extends _e{constructor(e){super(`Invalid join condition: left expression refers to an unavailable source "${e}"`)}}class gi extends _e{constructor(e){super(`Invalid join condition: right expression does not refer to the joined source "${e}"`)}}class mi extends _e{constructor(){super("Invalid join condition")}}class wi extends _e{constructor(e){super(`Unsupported join source type: ${e}`)}}class kt extends ne{constructor(e){super(e),this.name="GroupByError"}}class vi extends kt{constructor(e){super(`Non-aggregate expression '${e}' in SELECT must also appear in GROUP BY clause`)}}class bi extends kt{constructor(e){super(`Unsupported aggregate function: ${e}`)}}class Si extends kt{constructor(e){super(`Aggregate function in HAVING clause must also be in SELECT clause: ${e}`)}}class xi extends kt{constructor(e){super(`Unknown expression type in HAVING clause: ${e}`)}}class Js extends ne{constructor(e,t){const n=t instanceof Error?t.message:String(t);super(`Collection "${e}" sync cleanup function threw an error: ${n}`),this.name="SyncCleanupError"}}class Ci extends ne{constructor(e){super(e),this.name="QueryOptimizerError"}}class Ii extends Ci{constructor(){super("Cannot combine empty expression list")}}class Ei extends re{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.`)}}class Ri extends re{constructor(e){super(`Internal error: compiler returned aliases without inputs: ${e.join(", ")}. This indicates a bug in query compilation. Please report this issue.`)}}class ki extends re{constructor(){super("setWindow() can only be called on collections with an ORDER BY clause. Add .orderBy() to your query to enable window movement.")}}const Pt=new WeakMap;let Oi=1;function Ys(s){if(Pt.has(s))return Pt.get(s);const e=Oi++;return Pt.set(s,e),e}const ys=(s,e,t)=>{const{nulls:n}=t;if(s==null&&e==null)return 0;if(s==null)return n==="first"?-1:1;if(e==null)return n==="first"?1:-1;if(typeof s=="string"&&typeof e=="string"&&t.stringSort==="locale")return s.localeCompare(e,t.locale,t.localeOptions);if(Array.isArray(s)&&Array.isArray(e)){for(let o=0;o<Math.min(s.length,e.length);o++){const a=ys(s[o],e[o],t);if(a!==0)return a}return s.length-e.length}if(s instanceof Date&&e instanceof Date)return s.getTime()-e.getTime();const r=typeof s=="object",i=typeof e=="object";if(r||i){if(r&&i){const o=Ys(s),a=Ys(e);return o-a}if(r)return 1;if(i)return-1}return s<e?-1:s>e?1:0},_i=(s,e,t)=>ys(e,s,{...t,nulls:t.nulls==="first"?"last":"first"});function bt(s){return(e,t)=>s.direction==="asc"?ys(e,t,s):_i(e,t,s)}const qt=bt({direction:"asc",nulls:"first",stringSort:"locale"});function Ai(s,e){if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}const Mi=128,_n="__TS_DB_BTREE_UNDEFINED_VALUE__";function Wt(s){return s instanceof Date?s.getTime():(typeof Buffer<"u"&&s instanceof Buffer||s instanceof Uint8Array)&&s.byteLength<=Mi?`__u8__${Array.from(s).join(",")}`:s}function we(s){return s===void 0?_n:Wt(s)}function qe(s){if(s!==_n)return s}function Ti(s,e){if(s===e)return!0;const t=typeof Buffer<"u"&&s instanceof Buffer||s instanceof Uint8Array,n=typeof Buffer<"u"&&e instanceof Buffer||e instanceof Uint8Array;return t&&n?Ai(s,e):!1}function V(s){return s==null}function De(s){return s===!0}function ee(s,e=!1){return ms(s,e)}function gs(s){return ms(s,!0)}function ms(s,e){switch(s.type){case"val":{const t=s.value;return()=>t}case"ref":return e?Di(s):Pi(s);case"func":return Ki(s,e);default:throw new li(s.type)}}function Pi(s){const[e,...t]=s.path;if(!e)throw new ui;if(e==="$selected"){if(t.length===0)return r=>r.$selected;if(t.length===1){const r=t[0];return i=>i.$selected?.[r]}else return r=>{const i=r.$selected;if(i===void 0)return;let o=i;for(const a of t){if(o==null)return o;o=o[a]}return o}}const n=e;if(t.length===0)return r=>r[n];if(t.length===1){const r=t[0];return i=>i[n]?.[r]}else return r=>{const i=r[n];if(i===void 0)return;let o=i;for(const a of t){if(o==null)return o;o=o[a]}return o}}function Di(s){const e=s.path;return t=>{let n=t;for(const r of e){if(n==null)return n;n=n[r]}return n}}function Ki(s,e){const t=s.args.map(n=>ms(n,e));switch(s.name){case"eq":{const n=t[0],r=t[1];return i=>{const o=Wt(n(i)),a=Wt(r(i));return V(o)||V(a)?null:Ti(o,a)}}case"gt":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return V(o)||V(a)?null:o>a}}case"gte":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return V(o)||V(a)?null:o>=a}}case"lt":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return V(o)||V(a)?null:o<a}}case"lte":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return V(o)||V(a)?null:o<=a}}case"and":return n=>{let r=!1;for(const i of t){const o=i(n);if(o===!1)return!1;V(o)&&(r=!0)}return r?null:!0};case"or":return n=>{let r=!1;for(const i of t){const o=i(n);if(o===!0)return!0;V(o)&&(r=!0)}return r?null:!1};case"not":{const n=t[0];return r=>{const i=n(r);return V(i)?null:!i}}case"in":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return V(o)?null:Array.isArray(a)?a.includes(o):!1}}case"like":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return V(o)||V(a)?null:Zs(o,a,!1)}}case"ilike":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return V(o)||V(a)?null:Zs(o,a,!0)}}case"upper":{const n=t[0];return r=>{const i=n(r);return typeof i=="string"?i.toUpperCase():i}}case"lower":{const n=t[0];return r=>{const i=n(r);return typeof i=="string"?i.toLowerCase():i}}case"length":{const n=t[0];return r=>{const i=n(r);return typeof i=="string"||Array.isArray(i)?i.length:0}}case"concat":return n=>t.map(r=>{const i=r(n);try{return String(i??"")}catch{try{return JSON.stringify(i)||""}catch{return"[object]"}}}).join("");case"coalesce":return n=>{for(const r of t){const i=r(n);if(i!=null)return i}return null};case"add":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return(o??0)+(a??0)}}case"subtract":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return(o??0)-(a??0)}}case"multiply":{const n=t[0],r=t[1];return i=>{const o=n(i),a=r(i);return(o??0)*(a??0)}}case"divide":{const n=t[0],r=t[1];return i=>{const o=n(i),c=r(i)??0;return c!==0?(o??0)/c:null}}case"isUndefined":{const n=t[0];return r=>n(r)===void 0}case"isNull":{const n=t[0];return r=>n(r)===null}default:throw new hi(s.name)}}function Zs(s,e,t){if(typeof s!="string"||typeof e!="string")return!1;const n=t?s.toLowerCase():s;let i=(t?e.toLowerCase():e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return i=i.replace(/%/g,".*"),i=i.replace(/_/g,"."),new RegExp(`^${i}$`).test(n)}function le(s,e){return mt(s,e,new Map)}function mt(s,e,t){if(s===e)return!0;if(s==null||e==null||typeof s!=typeof e)return!1;if(s instanceof Date)return e instanceof Date?s.getTime()===e.getTime():!1;if(e instanceof Date)return!1;if(s instanceof RegExp)return e instanceof RegExp?s.source===e.source&&s.flags===e.flags:!1;if(e instanceof RegExp)return!1;if(s instanceof Map){if(!(e instanceof Map)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const r=Array.from(s.entries()).every(([i,o])=>e.has(i)&&mt(o,e.get(i),t));return t.delete(s),r}if(e instanceof Map)return!1;if(s instanceof Set){if(!(e instanceof Set)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=Array.from(s),r=Array.from(e);if(n.every(o=>typeof o!="object"))return t.delete(s),n.every(o=>e.has(o));const i=n.length===r.length;return t.delete(s),i}if(e instanceof Set)return!1;if(ArrayBuffer.isView(s)&&ArrayBuffer.isView(e)&&!(s instanceof DataView)&&!(e instanceof DataView)){const n=s,r=e;if(n.length!==r.length)return!1;for(let i=0;i<n.length;i++)if(n[i]!==r[i])return!1;return!0}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)&&!ArrayBuffer.isView(s))return!1;if(Ye(s)&&Ye(e)){const n=Gt(s),r=Gt(e);return n!==r?!1:typeof s.equals=="function"?s.equals(e):s.toString()===e.toString()}if(Ye(e))return!1;if(Array.isArray(s)){if(!Array.isArray(e)||s.length!==e.length)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=s.every((r,i)=>mt(r,e[i],t));return t.delete(s),n}if(Array.isArray(e))return!1;if(typeof s=="object"){if(t.has(s))return t.get(s)===e;t.set(s,e);const n=Object.keys(s),r=Object.keys(e);if(n.length!==r.length)return t.delete(s),!1;const i=n.every(o=>o in e&&mt(s[o],e[o],t));return t.delete(s),i}return!1}const Fi=["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"];function Gt(s){return s[Symbol.toStringTag]}function Ye(s){const e=Gt(s);return typeof e=="string"&&Fi.includes(e)}const ws={direction:"asc",nulls:"first",stringSort:"locale"};class ji{constructor(e){this.originalIndex=e}lookup(e,t){const 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 at(s,e,t){const n=t??{...ws,...s.compareOptions};for(const r of s.indexes.values())if(r.matchesField(e)&&r.matchesCompareOptions(n))return r.matchesDirection(n.direction)?r:new ji(r)}function Bi(s){if(s.length===0)return new Set;if(s.length===1)return new Set(s[0]);let e=new Set(s[0]);for(let t=1;t<s.length;t++){const n=new Set;for(const r of e)s[t].has(r)&&n.add(r);e=n}return e}function Li(s){const e=new Set;for(const t of s)for(const n of t)e.add(n);return e}function zi(s,e){return vs(s,e)}function vs(s,e){if(s.type==="func")switch(s.name){case"eq":case"gt":case"gte":case"lt":case"lte":return $i(s,e);case"and":return Ui(s,e);case"or":return Vi(s,e);case"in":return qi(s,e)}return{canOptimize:!1,matchingKeys:new Set}}function Ni(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const t=new Map;for(const n of s.args)if(n.type==="func"&&["gt","gte","lt","lte"].includes(n.name)){const r=n;if(r.args.length===2){const i=r.args[0],o=r.args[1];let a=null,c=null,l=r.name;if(i.type==="ref"&&o.type==="val")a=i,c=o;else if(i.type==="val"&&o.type==="ref")switch(a=o,c=i,l){case"gt":l="lt";break;case"gte":l="lte";break;case"lt":l="gt";break;case"lte":l="gte";break}if(a&&c){const h=a.path.join("."),y=c.value;t.has(h)||t.set(h,[]),t.get(h).push({operation:l,value:y})}}}for(const[n,r]of t)if(r.length>=2){const i=n.split("."),o=at(e,i);if(o&&o.supports("gt")&&o.supports("lt")){let a,c,l=!0,u=!0;for(const{operation:y,value:f}of r)switch(y){case"gt":(a===void 0||f>a)&&(a=f,l=!1);break;case"gte":(a===void 0||f>a)&&(a=f,l=!0);break;case"lt":(c===void 0||f<c)&&(c=f,u=!1);break;case"lte":(c===void 0||f<c)&&(c=f,u=!0);break}return{canOptimize:!0,matchingKeys:o.rangeQuery({from:a,to:c,fromInclusive:l,toInclusive:u})}}}return{canOptimize:!1,matchingKeys:new Set}}function $i(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};const t=s.args[0],n=s.args[1];let r=null,i=null,o=s.name;if(t.type==="ref"&&n.type==="val")r=t,i=n;else if(t.type==="val"&&n.type==="ref")switch(r=n,i=t,o){case"gt":o="lt";break;case"gte":o="lte";break;case"lt":o="gt";break;case"lte":o="gte";break}if(r&&i){const a=r.path,c=at(e,a);if(c){const l=i.value,u=o;return c.supports(u)?{canOptimize:!0,matchingKeys:c.lookup(u,l)}:{canOptimize:!1,matchingKeys:new Set}}}return{canOptimize:!1,matchingKeys:new Set}}function Ui(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const t=Ni(s,e);if(t.canOptimize)return t;const n=[];for(const r of s.args){const i=vs(r,e);i.canOptimize&&n.push(i)}if(n.length>0){const r=n.map(o=>o.matchingKeys);return{canOptimize:!0,matchingKeys:Bi(r)}}return{canOptimize:!1,matchingKeys:new Set}}function Vi(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const t=[];for(const n of s.args){const r=vs(n,e);r.canOptimize&&t.push(r)}if(t.length>0){const n=t.map(i=>i.matchingKeys);return{canOptimize:!0,matchingKeys:Li(n)}}return{canOptimize:!1,matchingKeys:new Set}}function qi(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};const t=s.args[0],n=s.args[1];if(t.type==="ref"&&n.type==="val"&&Array.isArray(n.value)){const r=t.path,i=n.value,o=at(e,r);if(o){if(o.supports("in"))return{canOptimize:!0,matchingKeys:o.lookup("in",i)};if(o.supports("eq")){const a=new Set;for(const c of i){const l=o.lookup("eq",c);for(const u of l)a.add(u)}return{canOptimize:!0,matchingKeys:a}}}}return{canOptimize:!1,matchingKeys:new Set}}class Wi extends Map{constructor(e,t){super(t),this.defaultValue=e}get(e){return this.has(e)?super.get(e):this.defaultValue()}update(e,t){const n=this.get(e),r=t(n);return this.set(e,r),r}}const Dt=3e4;function Kt(s,e){if(e.length<=Dt)s.push(...e);else for(let t=0;t<e.length;t+=Dt){const n=e.slice(t,t+Dt);s.push(...n)}}function Gi(s,e,t){let n=0,r=s.length;for(;n<r;){const i=Math.floor((n+r)/2),o=t(s[i],e);if(o<0)n=i+1;else if(o>0)r=i;else return i}return n}class Hi{constructor(){this.objectIds=new WeakMap,this.nextId=0}getId(e){if(typeof e!="object"||e===null){const t=String(e);let n=0;for(let r=0;r<t.length;r++){const i=t.charCodeAt(r);n=(n<<5)-n+i,n=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"?`str_${String(e)}`:`obj_${this.getId(e)}`}}const Ft=new Hi;function Qi(s,e){const[t,n]=s,[r,i]=e,o=[...yt(t,Math.min(n,r)),...yt(Math.max(t,i),n)],a=[...yt(r,Math.min(i,t)),...yt(Math.max(r,n),i)];return{onlyInA:o,onlyInB:a}}function yt(s,e){const t=[];for(let n=s;n<e;n++)t.push(n);return t}function St(s,e){return typeof s==typeof e?s<e?-1:s>e?1:0:typeof s=="string"?-1:1}function bs(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?t.toString():t instanceof Date?t.toISOString():t)}const Ji=W(),Yi=W(),Zi=W(),Xi=W(),eo=W();function W(){return Math.random()*(2**31-1)>>>0}const An=new ArrayBuffer(8),to=new DataView(An),ve=new Uint8Array(An);class Ot{constructor(){this.hash=Ji,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(eo);const t=e.description;if(!t)return;for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);this.writeByte(r&255),this.writeByte(r>>>8&255)}return}case"string":this.update(Yi);for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);this.writeByte(n&255),this.writeByte(n>>>8&255)}return;case"number":to.setFloat64(0,e,!0),this.writeByte(ve[0]),this.writeByte(ve[1]),this.writeByte(ve[2]),this.writeByte(ve[3]),this.writeByte(ve[4]),this.writeByte(ve[5]),this.writeByte(ve[6]),this.writeByte(ve[7]);return;case"bigint":{let t=e;for(t<0n?(t=-t,this.update(Xi)):this.update(Zi);t>0n;)this.writeByte(Number(t&0xffn)),t>>=8n;e===0n&&this.writeByte(0);return}default:throw new 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}}const so=W(),no=W(),ro=W(),io=W(),oo=W(),ao=W(),co=W(),lo=W(),uo=W(),ho=W(),fo=W(),po=W(),yo=128,st=new WeakMap;function Q(s){const e=new Ot;return Mn(e,s),e.digest()}function go(s){const e=st.get(s);if(e!==void 0)return e;let t;if(s instanceof Date)t=mo(s);else if(typeof Buffer<"u"&&s instanceof Buffer||s instanceof Uint8Array)if(s.byteLength<=yo)t=wo(s);else return Ht(s);else{if(s instanceof File)return Ht(s);{let n=s,r=lo;s instanceof Array&&(r=uo),s instanceof Map&&(r=ho,n=[...s.entries()]),s instanceof Set&&(r=fo,n=[...s.entries()]),t=vo(n,r)}}return st.set(s,t),t}function mo(s){const e=new Ot;return e.update(co),e.update(s.getTime()),e.digest()}function wo(s){const e=new Ot;e.update(po),e.update(s.byteLength);for(let t=0;t<s.byteLength;t++)e.writeByte(s[t]);return e.digest()}function vo(s,e){const t=new Ot;t.update(e);const n=Object.keys(s);n.sort(So);for(const r of n)t.update(oo),t.update(r),Mn(t,s[r]);return t.digest()}function Mn(s,e){if(e===null){s.update(ro);return}switch(typeof e){case"undefined":s.update(io);return;case"boolean":s.update(e?so:no);return;case"number":s.update(isNaN(e)?NaN:e===0?0:e);return;case"bigint":case"string":case"symbol":s.update(e);return;case"object":s.update(bo(e));return;case"function":s.update(Ht(e));return;default:console.warn(`Ignored input during hashing because it is of type ${typeof e} which is not supported`)}}function bo(s){let e=st.get(s);return e===void 0&&(e=go(s)),e}let Xs=1;function Ht(s){let e=st.get(s);return e===void 0&&(e=Xs^ao,Xs++,st.set(s,e)),e}function So(s,e){return s.localeCompare(e)}class U{#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(e){return new U(JSON.parse(e))}map(e){return new U(this.#e.map(([t,n])=>[e(t),n]))}filter(e){return new U(this.#e.filter(([t,n])=>e(t)))}negate(){return new U(this.#e.map(([e,t])=>[e,-t]))}concat(e){const t=[];return Kt(t,this.#e),Kt(t,e.getInner()),new U(t)}consolidate(){if(this.#e.length>0){const e=this.#e[0]?.[0];if(Array.isArray(e)&&e.length===2)return this.#t()}return this.#s()}#t(){const e=new Map,t=new Map,n=i=>{if(i.length!==2)throw new Error("Expected tuple of length 2");const[o,a]=i;return`${Ft.getStringId(o)}|${Ft.getStringId(a)}`};for(const[i,o]of this.#e){if(!Array.isArray(i)||i.length!==2)return this.#s();const[a,c]=i;if(typeof a!="string"&&typeof a!="number")return this.#s();let l;Array.isArray(c)&&c.length===2?l=n(c):l=Ft.getStringId(c);const u=a+"|"+l;e.set(u,(e.get(u)||0)+o),t.has(u)||t.set(u,i)}const r=[];for(const[i,o]of e)o!==0&&r.push([t.get(i),o]);return new U(r)}#s(){const e=new Wi(()=>0),t=new Map;let n=!1,r=!1,i=!1;for(const[c,l]of this.#e)if(typeof c=="string")n=!0;else if(typeof c=="number")r=!0;else{i=!0;break}const o=i||n&&r;for(const[c,l]of this.#e){const u=o?Q(c):c;o&&!t.has(u)&&t.set(u,c),e.update(u,h=>h+l)}const a=[];for(const[c,l]of e.entries())if(l!==0){const u=o?t.get(c):c;a.push([u,l])}return new U(a)}extend(e){const t=e instanceof U?e.getInner():e;Kt(this.#e,t)}add(e,t){t!==0&&this.#e.push([e,t])}getInner(){return this.#e}}class xo{#e;constructor(e){this.#e=e}drain(){const e=[...this.#e].reverse();return this.#e.length=0,e}isEmpty(){return this.#e.length===0}}class de{#e=[];sendData(e){e instanceof U||(e=new U(e));for(const t of this.#e)t.unshift(e)}newReader(){const e=[];return this.#e.push(e),new xo(e)}}class Tn{constructor(e,t,n){this.id=e,this.inputs=t,this.output=n}hasPendingWork(){return this.inputs.some(e=>!e.isEmpty())}}class je extends Tn{constructor(e,t,n){super(e,[t],n),this.id=e}inputMessages(){return this.inputs[0].drain()}}class Co extends Tn{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()}}class Ss extends je{run(){for(const e of this.inputMessages())this.output.sendData(this.inner(e))}}class Io{#e=[];#t=0;#s=!1;constructor(){}#n(){if(this.#s)throw new Error("Graph already finalized")}getNextOperatorId(){return this.#n(),this.#t++}newInput(){this.#n();const e=new de;return new Eo(this,e)}addOperator(e){this.#n(),this.#e.push(e)}finalize(){this.#n(),this.#s=!0}step(){if(!this.#s)throw new Error("Graph not finalized");for(const e of this.#e)e.run()}pendingWork(){return this.#e.some(e=>e.hasPendingWork())}run(){for(;this.pendingWork();)this.step()}}class fe{#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((t,n)=>n(t),this)}}class Eo extends fe{sendData(e){this.writer.sendData(e)}}class Ro extends Ss{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.map(this.#e)}}function J(s){return e=>{const t=new fe(e.graph,new de),n=new Ro(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}const Ge=Symbol("NO_PREFIX");class en extends Map{addValue(e,t){if(t===0)return this.size===0;const n=Ze(e),r=this.get(n);if(wt(r)){const[i,o]=r;if(Ze(i)!==n)throw new Error("Mismatching prefixes, this should never happen");if(i===e||Q(i)===Q(e)){const c=o+t;c===0?this.delete(n):this.set(n,[e,c])}else{const c=new He;c.set(Q(i),r),c.set(Q(e),[e,t]),this.set(n,c)}}else r===void 0?this.set(n,[e,t]):r.addValue(e,t)&&this.delete(n);return this.size===0}}class He extends Map{addValue(e,t){if(t===0)return this.size===0;const n=Q(e),r=this.get(n);if(r){const[,i]=r,o=i+t;o===0?this.delete(n):this.set(n,[e,o])}else this.set(n,[e,t]);return this.size===0}}class be{#e;#t=new Map;constructor(){this.#e=new Map}static fromMultiSets(e){const t=new be;for(const n of e)for(const[r,i]of n.getInner()){const[o,a]=r;t.addValue(o,[a,i])}return t}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){const t=this.#e.get(e);if(wt(t))yield t;else{if(t===void 0)return;if(t instanceof He)for(const n of t.values())yield n;else for(const n of t.values())if(wt(n))yield n;else for(const r of n.values())yield r}}*entries(){for(const e of this.#e.keys())for(const t of this.getIterator(e))yield[e,t]}*entriesIterators(){for(const e of this.#e.keys())yield[e,this.getIterator(e)]}addValue(e,t){const[n,r]=t;if(r===0)return;const i=(this.#t.get(e)||0)+r;i===0?this.#t.delete(e):this.#t.set(e,i);const o=this.#e.get(e);if(o===void 0){this.#e.set(e,t);return}if(wt(o)){this.#s(e,o,n,r);return}if(o instanceof He){const a=Ze(n);if(a!==Ge){const c=new en;c.set(Ge,o),c.set(a,t),this.#e.set(e,c)}else o.addValue(n,r)&&this.#e.delete(e)}else o.addValue(n,r)&&this.#e.delete(e)}#s(e,t,n,r){const[i,o]=t;if(i===n){const l=o+r;l===0?this.#e.delete(e):this.#e.set(e,[n,l]);return}const a=Ze(n),c=Ze(i);if(c===a&&(i===n||Q(i)===Q(n))){const l=o+r;l===0?this.#e.delete(e):this.#e.set(e,[n,l]);return}if(c===Ge&&a===Ge){const l=new He;l.set(Q(i),t),l.set(Q(n),[n,r]),this.#e.set(e,l)}else{const l=new en;if(c===a){const u=new He;u.set(Q(i),t),u.set(Q(n),[n,r]),l.set(c,u)}else l.set(c,t),l.set(a,[n,r]);this.#e.set(e,l)}}append(e){for(const[t,n]of e.entries())this.addValue(t,n)}join(e){const t=[];if(this.size<=e.size)for(const[n,r]of this.entriesIterators()){if(!e.has(n))continue;const i=e.get(n);for(const[o,a]of r)for(const[c,l]of i)a!==0&&l!==0&&t.push([[n,[o,c]],a*l])}else for(const[n,r]of e.entriesIterators()){if(!this.has(n))continue;const i=this.get(n);for(const[o,a]of r)for(const[c,l]of i)l!==0&&a!==0&&t.push([[n,[c,o]],l*a])}return new U(t)}}function Ze(s){return Array.isArray(s)&&(typeof s[0]=="string"||typeof s[0]=="number"||typeof s[0]=="bigint")?s[0]:Ge}function wt(s){return Array.isArray(s)}class ko extends je{#e=new be;#t=new be;#s;constructor(e,t,n,r){super(e,t,n),this.#s=r}run(){const e=new Set;for(const n of this.inputMessages())for(const[r,i]of n.getInner()){const[o,a]=r;this.#e.addValue(o,[a,i]),e.add(o)}const t=[];for(const n of e){const r=this.#e.get(n),i=this.#t.get(n),o=this.#s(r),a=new Map,c=new Map;for(const[l,u]of o){const h=a.get(l)??0;a.set(l,h+u)}for(const[l,u]of i){const h=c.get(l)??0;c.set(l,h+u)}for(const[l,u]of c)a.has(l)||(t.push([[n,l],-u]),this.#t.addValue(n,[l,-u]));for(const[l,u]of a)c.has(l)||u!==0&&(t.push([[n,l],u]),this.#t.addValue(n,[l,u]));for(const[l,u]of a){const h=c.get(l);if(h!==void 0){const y=u-h;y!==0&&(t.push([[n,l],y]),this.#t.addValue(n,[l,y]))}}}t.length>0&&this.output.sendData(new U(t))}}function Oo(s){return e=>{const t=new fe(e.graph,new de),n=new ko(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}function tn(s){return"pipe"in s}function sn(s,e={}){const t=Object.fromEntries(Object.entries(e).filter(([n,r])=>!tn(r)));return Object.fromEntries(Object.entries(e).filter(([n,r])=>tn(r))),n=>{const r="__original_key__";return n.pipe(J(a=>{const c=s(a),l=bs(c),u={};u[r]=c;for(const[h,y]of Object.entries(t))u[h]=y.preMap(a);return[l,u]})).pipe(Oo(a=>{let c=0;for(const[h,y]of a)c+=y;if(c<=0)return[];const l={},u=a[0]?.[0]?.[r];l[r]=u;for(const[h,y]of Object.entries(t)){const f=a.map(([d,p])=>[d[h],p]);l[h]=y.reduce(f)}return[[l,1]]})).pipe(J(([a,c])=>{const l=c[r],u={};Object.assign(u,l);for(const[h,y]of Object.entries(t))y.postMap?u[h]=y.postMap(c[h]):u[h]=c[h];return[a,u]}))}}function _o(s=e=>e){return{preMap:e=>s(e),reduce:e=>{let t=0;for(const[n,r]of e)t+=n*r;return t}}}function Ao(s=e=>e){return{preMap:e=>s(e)==null?0:1,reduce:e=>{let t=0;for(const[n,r]of e)t+=n*r;return t}}}function Mo(s=e=>e){return{preMap:e=>({sum:s(e),count:0}),reduce:e=>{let t=0,n=0;for(const[r,i]of e)t+=r.sum*i,n+=i;return{sum:t,count:n}},postMap:e=>e.sum/e.count}}function To(s){const e=s??(t=>t);return{preMap:t=>e(t),reduce:t=>{let n;for(const[r,i]of t)(!n||r&&r<n)&&(n=r);return n}}}function Po(s){const e=s??(t=>t);return{preMap:t=>e(t),reduce:t=>{let n;for(const[r,i]of t)(!n||r&&r>n)&&(n=r);return n}}}const Do={sum:_o,count:Ao,avg:Mo,min:To,max:Po};class Ko extends Ss{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return this.#e(e),e}}function Fo(s){return e=>{const t=new fe(e.graph,new de),n=new Ko(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}class jo extends Ss{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.filter(this.#e)}}function Se(s){return e=>{const t=new fe(e.graph,new de),n=new jo(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}class Bo extends je{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}run(){for(const e of this.inputMessages())this.#e(e),this.output.sendData(e)}}function Lo(s){return e=>{const t=new fe(e.graph,new de),n=new Bo(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}class zo extends je{run(){const e=this.inputMessages();if(e.length===0)return;const t=new U;for(const r of e)t.extend(r);const n=t.consolidate();n.getInner().length>0&&this.output.sendData(n)}}function No(){return s=>{const e=new fe(s.graph,new de),t=new zo(s.graph.getNextOperatorId(),s.connectReader(),e.writer);return s.graph.addOperator(t),e}}class $o extends Co{#e=new be;#t=new be;#s;constructor(e,t,n,r,i="inner"){super(e,t,n,r),this.#s=i}run(){const e=be.fromMultiSets(this.inputAMessages()),t=be.fromMultiSets(this.inputBMessages());if(e.size===0&&t.size===0)return;const n=new U;this.#s!=="anti"&&this.emitInnerResults(e,t,n),(this.#s==="left"||this.#s==="full"||this.#s==="anti")&&this.emitLeftOuterResults(e,t,n),(this.#s==="right"||this.#s==="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(const[r,i]of e.entriesIterators()){const o=this.#t.getConsolidatedMultiplicity(r),a=t.getConsolidatedMultiplicity(r);if(o+a===0)for(const[l,u]of i)u!==0&&n.add([r,[l,null]],u)}if(t.size>0)for(const r of t.getPresenceKeys()){const i=this.#t.getConsolidatedMultiplicity(r),o=t.getConsolidatedMultiplicity(r);if(o===0)continue;const a=i+o;if(i===0==(a===0))continue;const c=i===0;for(const[l,u]of this.#e.getIterator(r))u!==0&&n.add([r,[l,null]],c?-u:+u)}}emitRightOuterResults(e,t,n){if(t.size>0)for(const[r,i]of t.entriesIterators()){const o=this.#e.getConsolidatedMultiplicity(r),a=e.getConsolidatedMultiplicity(r);if(o+a===0)for(const[l,u]of i)u!==0&&n.add([r,[null,l]],u)}if(e.size>0)for(const r of e.getPresenceKeys()){const i=this.#e.getConsolidatedMultiplicity(r),o=e.getConsolidatedMultiplicity(r);if(o===0)continue;const a=i+o;if(i===0==(a===0))continue;const c=i===0;for(const[l,u]of this.#t.getIterator(r))u!==0&&n.add([r,[null,l]],c?-u:+u)}}}function Uo(s,e="inner"){return t=>{if(t.graph!==s.graph)throw new Error("Cannot join streams from different graphs");const n=new fe(t.graph,new de),r=new $o(t.graph.getNextOperatorId(),t.connectReader(),s.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}class Vo extends je{#e;#t;constructor(e,t,n,r=i=>i){super(e,t,n),this.#e=r,this.#t=new Map}run(){const e=new Map;for(const n of this.inputMessages())for(const[r,i]of n.getInner()){const o=Q(this.#e(r)),c=(e.get(o)?.[0]??this.#t.get(o)??0)+i;e.set(o,[c,r])}const t=[];for(const[n,[r,i]]of e.entries()){const o=this.#t.get(n)??0;r===0?this.#t.delete(n):this.#t.set(n,r),o<=0&&r>0?t.push([[Q(this.#e(i)),i[1]],1]):o>0&&r<=0&&t.push([[Q(this.#e(i)),i[1]],-1])}t.length>0&&this.output.sendData(new U(t))}}function qo(s=e=>e){return e=>{const t=new fe(e.graph,new de),n=new Vo(e.graph.getNextOperatorId(),e.connectReader(),t.writer,s);return e.graph.addOperator(n),t}}const Wo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Te(s,e,t){const n=t[0];if(e!=null&&s>=e)throw new Error(s+" >= "+e);if(s.slice(-1)===n||e&&e.slice(-1)===n)throw new Error("trailing zero");if(e){let o=0;for(;(s[o]||n)===e[o];)o++;if(o>0)return e.slice(0,o)+Te(s.slice(o),e.slice(o),t)}const r=s?t.indexOf(s[0]):0,i=e!=null?t.indexOf(e[0]):t.length;if(i-r>1){const o=Math.round(.5*(r+i));return t[o]}else return e&&e.length>1?e.slice(0,1):t[r]+Te(s.slice(1),null,t)}function Pn(s){if(s.length!==Dn(s[0]))throw new Error("invalid integer part of order key: "+s)}function Dn(s){if(s>="a"&&s<="z")return s.charCodeAt(0)-97+2;if(s>="A"&&s<="Z")return 90-s.charCodeAt(0)+2;throw new Error("invalid order key head: "+s)}function Qe(s){const e=Dn(s[0]);if(e>s.length)throw new Error("invalid order key: "+s);return s.slice(0,e)}function nn(s,e){if(s==="A"+e[0].repeat(26))throw new Error("invalid order key: "+s);const t=Qe(s);if(s.slice(t.length).slice(-1)===e[0])throw new Error("invalid order key: "+s)}function rn(s,e){Pn(s);const[t,...n]=s.split("");let r=!0;for(let i=n.length-1;r&&i>=0;i--){const o=e.indexOf(n[i])+1;o===e.length?n[i]=e[0]:(n[i]=e[o],r=!1)}if(r){if(t==="Z")return"a"+e[0];if(t==="z")return null;const i=String.fromCharCode(t.charCodeAt(0)+1);return i>"a"?n.push(e[0]):n.pop(),i+n.join("")}else return t+n.join("")}function Go(s,e){Pn(s);const[t,...n]=s.split("");let r=!0;for(let i=n.length-1;r&&i>=0;i--){const o=e.indexOf(n[i])-1;o===-1?n[i]=e.slice(-1):(n[i]=e[o],r=!1)}if(r){if(t==="a")return"Z"+e.slice(-1);if(t==="A")return null;const i=String.fromCharCode(t.charCodeAt(0)-1);return i<"Z"?n.push(e.slice(-1)):n.pop(),i+n.join("")}else return t+n.join("")}function Ho(s,e,t=Wo){if(s!=null&&nn(s,t),e!=null&&nn(e,t),s!=null&&e!=null&&s>=e)throw new Error(s+" >= "+e);if(s==null){if(e==null)return"a"+t[0];const c=Qe(e),l=e.slice(c.length);if(c==="A"+t[0].repeat(26))return c+Te("",l,t);if(c<e)return c;const u=Go(c,t);if(u==null)throw new Error("cannot decrement any more");return u}if(e==null){const c=Qe(s),l=s.slice(c.length),u=rn(c,t);return u??c+Te(l,null,t)}const n=Qe(s),r=s.slice(n.length),i=Qe(e),o=e.slice(i.length);if(n===i)return n+Te(r,o,t);const a=rn(n,t);if(a==null)throw new Error("cannot increment any more");return a<e?a:n+Te(r,null,t)}function on(s,e){return[s,e]}function an(s){return s[0]}function cn(s){return s[1]}function Qo(s){return([e,t],[n,r])=>{const i=s(t,r);return i!==0?i:St(e,n)}}class Kn{#e=[];#t;#s;#n;constructor(e,t,n){this.#s=e,this.#n=e+t,this.#t=n}get size(){const e=this.#s,t=this.#n-this.#s,n=this.#e.length-e;return Math.max(0,Math.min(t,n))}move({offset:e,limit:t}){const n=this.#s,r=this.#n-this.#s,i=[this.#s,this.#n===1/0?this.#s+this.size:this.#n];this.#s=e??n,this.#n=this.#s+(t??r);const o=[this.#s,this.#n===1/0?Math.max(this.#s+this.size,i[1]):this.#n],{onlyInA:a,onlyInB:c}=Qi(i,o),l=[];c.forEach(h=>{const y=this.#e[h];y&&l.push(y)});const u=[];return a.forEach(h=>{const y=this.#e[h];y&&u.push(y)}),{moveIns:l,moveOuts:u,changes:a.length+c.length>0}}insert(e){const t={moveIn:null,moveOut:null},n=this.#r(e),r=n===0?null:cn(this.#e[n-1]),i=n===this.#e.length?null:cn(this.#e[n]),o=Ho(r,i),a=on(e,o);if(this.#e.splice(n,0,a),n<this.#n){const c=Math.max(n,this.#s);c<this.#e.length&&(t.moveIn=this.#e[c],this.#n<this.#e.length&&(t.moveOut=this.#e[this.#n]))}return t}delete(e){const t={moveIn:null,moveOut:null},n=this.#r(e),[r]=this.#e.splice(n,1);if(n<this.#n){if(t.moveOut=r,n<this.#s){const o=this.#s-1;o<this.#e.length?t.moveOut=this.#e[o]:t.moveOut=null}const i=this.#n-1;i<this.#e.length&&(t.moveIn=this.#e[i])}return t}#r(e){return Gi(this.#e,on(e,""),(t,n)=>this.#t(an(t),an(n)))}}class Jo{#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){const{oldMultiplicity:r,newMultiplicity:i}=this.#s(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 Kn))throw new Error("Cannot move B+-tree implementation of TopK with fractional index");return this.#t.move(e)}#s(e,t){if(t===0){const i=this.#e.get(e)??0;return{oldMultiplicity:i,newMultiplicity:i}}const 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 ln(s,e){if(s){const[[t,n],r]=s;e.push([[t,[n,r]],1])}}function un(s,e){if(s){const[[t,n],r]=s;e.push([[t,[n,r]],-1])}}class Yo extends je{#e;constructor(e,t,n,r,i){super(e,t,n);const o=i.limit??1/0,a=i.offset??0,c=this.createTopK(a,o,Qo(r));this.#e=new Jo(c),i.setSizeCallback?.(()=>this.#e.size),i.setWindowFn?.(this.moveTopK.bind(this))}createTopK(e,t,n){return new Kn(e,t,n)}moveTopK({offset:e,limit:t}){const n=[],r=this.#e.move({offset:e,limit:t});r.moveIns.forEach(i=>ln(i,n)),r.moveOuts.forEach(i=>un(i,n)),r.changes&&this.output.sendData(new U(n))}run(){const e=[];for(const t of this.inputMessages())for(const[n,r]of t.getInner()){const[i,o]=n;this.processElement(i,o,r,e)}e.length>0&&this.output.sendData(new U(e))}processElement(e,t,n,r){const i=this.#e.processElement(e,t,n);ln(i.moveIn,r),un(i.moveOut,r)}}function Zo(s,e){const t=e||{};return n=>{const r=new fe(n.graph,new de),i=new Yo(n.graph.getNextOperatorId(),n.connectReader(),r.writer,s,t);return n.graph.addOperator(i),r}}function Xo(s,e,t){const n=t?.limit??1/0,r=t?.offset??0,i=t?.setSizeCallback,o=t?.setWindowFn,a=t?.comparator??((c,l)=>c===l?0:c<l?-1:1);return c=>c.pipe(s((l,u)=>a(e(l),e(u)),{limit:n,offset:r,setSizeCallback:i,setWindowFn:o}),No())}function ea(s,e){return Xo(Zo,s,e)}class ta{constructor(e,t,n){this._root=jt,this._size=0,this._maxNodeSize=n>=4?Math.min(n,256):32,this._compare=e,t&&this.setPairs(t)}get size(){return this._size}get length(){return this._size}get isEmpty(){return this._size===0}clear(){this._root=jt,this._size=0}get(e,t){return this._root.get(e,t,this)}set(e,t,n){this._root.isShared&&(this._root=this._root.clone());const r=this._root.set(e,t,n,this);return r===!0||r===!1?r:(this._root=new xs([this._root,r]),!0)}has(e){return this.forRange(e,e,!0,void 0)!==0}delete(e){return this.editRange(e,e,!0,na)!==0}get maxNodeSize(){return this._maxNodeSize}minKey(){return this._root.minKey()}maxKey(){return this._root.maxKey()}keysArray(){const e=[];return this._root.forRange(this.minKey(),this.maxKey(),!0,!1,this,0,(t,n)=>{e.push(t)}),e}nextHigherPair(e,t){return t=t||[],e===void 0?this._root.minPair(t):this._root.getPairOrNextHigher(e,this._compare,!1,t)}nextHigherKey(e){const t=this.nextHigherPair(e,hn);return t&&t[0]}nextLowerPair(e,t){return t=t||[],e===void 0?this._root.maxPair(t):this._root.getPairOrNextLower(e,this._compare,!1,t)}nextLowerKey(e){const t=this.nextLowerPair(e,hn);return t&&t[0]}setPairs(e,t){let n=0;for(const r of e)this.set(r[0],r[1],t)&&n++;return n}forRange(e,t,n,r,i){const o=this._root.forRange(e,t,n,!1,this,i||0,r);return typeof o=="number"?o:o.break}editRange(e,t,n,r,i){let o=this._root;o.isShared&&(this._root=o=o.clone());try{const a=o.forRange(e,t,n,!0,this,i||0,r);return typeof a=="number"?a:a.break}finally{let a;for(;o.keys.length<=1&&!o.isLeaf;)a||=o.isShared,this._root=o=o.keys.length===0?jt:o.children[0];a&&(o.isShared=!0)}}}class nt{get isLeaf(){return this.children===void 0}constructor(e=[],t){this.keys=e,this.values=t||H,this.isShared=void 0}maxKey(){return this.keys[this.keys.length-1]}indexOf(e,t,n){const r=this.keys;let i=0,o=r.length,a=o>>1;for(;i<o;){const c=n(r[a],e);if(c<0)i=a+1;else if(c>0)o=a;else{if(c===0)return a;if(e===e)return r.length;throw new Error("BTree: NaN was used as a key")}a=i+o>>1}return a^t}minKey(){return this.keys[0]}minPair(e){if(this.keys.length!==0)return e[0]=this.keys[0],e[1]=this.values[0],e}maxPair(e){if(this.keys.length===0)return;const t=this.keys.length-1;return e[0]=this.keys[t],e[1]=this.values[t],e}clone(){const e=this.values;return new nt(this.keys.slice(0),e===H?e:e.slice(0))}get(e,t,n){const r=this.indexOf(e,-1,n._compare);return r<0?t:this.values[r]}getPairOrNextLower(e,t,n,r){const i=this.indexOf(e,-1,t),o=i<0?~i-1:n?i:i-1;if(o>=0)return r[0]=this.keys[o],r[1]=this.values[o],r}getPairOrNextHigher(e,t,n,r){const i=this.indexOf(e,-1,t),o=i<0?~i:n?i:i+1,a=this.keys;if(o<a.length)return r[0]=a[o],r[1]=this.values[o],r}set(e,t,n,r){let i=this.indexOf(e,-1,r._compare);if(i<0){if(i=~i,r._size++,this.keys.length<r._maxNodeSize)return this.insertInLeaf(i,e,t,r);{const o=this.splitOffRightSide();let a=this;return i>this.keys.length&&(i-=this.keys.length,a=o),a.insertInLeaf(i,e,t,r),o}}else return n!==!1&&(t!==void 0&&this.reifyValues(),this.keys[i]=e,this.values[i]=t),!1}reifyValues(){return this.values===H?this.values=this.values.slice(0,this.keys.length):this.values}insertInLeaf(e,t,n,r){if(this.keys.splice(e,0,t),this.values===H){for(;H.length<r._maxNodeSize;)H.push(void 0);if(n===void 0)return!0;this.values=H.slice(0,this.keys.length-1)}return this.values.splice(e,0,n),!0}takeFromRight(e){let t=this.values;e.values===H?t!==H&&t.push(void 0):(t=this.reifyValues(),t.push(e.values.shift())),this.keys.push(e.keys.shift())}takeFromLeft(e){let t=this.values;e.values===H?t!==H&&t.unshift(void 0):(t=this.reifyValues(),t.unshift(e.values.pop())),this.keys.unshift(e.keys.pop())}splitOffRightSide(){const e=this.keys.length>>1,t=this.keys.splice(e),n=this.values===H?H:this.values.splice(e);return new nt(t,n)}forRange(e,t,n,r,i,o,a){const c=i._compare;let l,u;if(t===e){if(!n||(u=(l=this.indexOf(e,-1,c))+1,l<0))return o}else l=this.indexOf(e,0,c),u=this.indexOf(t,-1,c),u<0?u=~u:n===!0&&u++;const h=this.keys,y=this.values;if(a!==void 0)for(let f=l;f<u;f++){const d=h[f],p=a(d,y[f],o++);if(p!==void 0){if(r===!0){if(d!==h[f]||this.isShared===!0)throw new Error("BTree illegally changed or cloned in editRange");p.delete?(this.keys.splice(f,1),this.values!==H&&this.values.splice(f,1),i._size--,f--,u--):p.hasOwnProperty("value")&&(y[f]=p.value)}if(p.break!==void 0)return p}}else o+=u-l;return o}mergeSibling(e,t){if(this.keys.push.apply(this.keys,e.keys),this.values===H){if(e.values===H)return;this.values=this.values.slice(0,this.keys.length)}this.values.push.apply(this.values,e.reifyValues())}}class xs extends nt{constructor(e,t){if(!t){t=[];for(let n=0;n<e.length;n++)t[n]=e[n].maxKey()}super(t),this.children=e}minKey(){return this.children[0].minKey()}minPair(e){return this.children[0].minPair(e)}maxPair(e){return this.children[this.children.length-1].maxPair(e)}get(e,t,n){const r=this.indexOf(e,0,n._compare),i=this.children;return r<i.length?i[r].get(e,t,n):void 0}getPairOrNextLower(e,t,n,r){const i=this.indexOf(e,0,t),o=this.children;if(i>=o.length)return this.maxPair(r);const a=o[i].getPairOrNextLower(e,t,n,r);return a===void 0&&i>0?o[i-1].maxPair(r):a}getPairOrNextHigher(e,t,n,r){const i=this.indexOf(e,0,t),o=this.children,a=o.length;if(i>=a)return;const c=o[i].getPairOrNextHigher(e,t,n,r);return c===void 0&&i<a-1?o[i+1].minPair(r):c}set(e,t,n,r){const i=this.children,o=r._maxNodeSize,a=r._compare;let c=Math.min(this.indexOf(e,0,a),i.length-1),l=i[c];if(l.isShared&&(i[c]=l=l.clone()),l.keys.length>=o){let h;c>0&&(h=i[c-1]).keys.length<o&&a(l.keys[0],e)<0?(h.isShared&&(i[c-1]=h=h.clone()),h.takeFromRight(l),this.keys[c-1]=h.maxKey()):(h=i[c+1])!==void 0&&h.keys.length<o&&a(l.maxKey(),e)<0&&(h.isShared&&(i[c+1]=h=h.clone()),h.takeFromLeft(l),this.keys[c]=i[c].maxKey())}const u=l.set(e,t,n,r);if(u===!1)return!1;if(this.keys[c]=l.maxKey(),u===!0)return!0;if(this.keys.length<o)return this.insert(c+1,u),!0;{const h=this.splitOffRightSide();let y=this;return a(u.maxKey(),this.maxKey())>0&&(y=h,c-=this.keys.length),y.insert(c+1,u),h}}insert(e,t){this.children.splice(e,0,t),this.keys.splice(e,0,t.maxKey())}splitOffRightSide(){const e=this.children.length>>1;return new xs(this.children.splice(e),this.keys.splice(e))}takeFromRight(e){this.keys.push(e.keys.shift()),this.children.push(e.children.shift())}takeFromLeft(e){this.keys.unshift(e.keys.pop()),this.children.unshift(e.children.pop())}forRange(e,t,n,r,i,o,a){const c=i._compare,l=this.keys,u=this.children;let h=this.indexOf(e,0,c),y=h;const f=Math.min(t===e?h:this.indexOf(t,0,c),l.length-1);if(r){if(y<=f)try{for(;y<=f;y++){u[y].isShared&&(u[y]=u[y].clone());const d=u[y].forRange(e,t,n,r,i,o,a);if(l[y]=u[y].maxKey(),typeof d!="number")return d;o=d}}finally{const d=i._maxNodeSize>>1;for(h>0&&h--,y=f;y>=h;y--)u[y].keys.length<=d&&(u[y].keys.length!==0?this.tryMerge(y,i._maxNodeSize):(l.splice(y,1),u.splice(y,1)));u.length!==0&&u[0].keys.length===0&&ra(!1,"emptiness bug")}}else for(;y<=f;y++){const d=u[y].forRange(e,t,n,r,i,o,a);if(typeof d!="number")return d;o=d}return o}tryMerge(e,t){const n=this.children;return e>=0&&e+1<n.length&&n[e].keys.length+n[e+1].keys.length<=t?(n[e].isShared&&(n[e]=n[e].clone()),n[e].mergeSibling(n[e+1],t),n.splice(e+1,1),this.keys.splice(e+1,1),this.keys[e]=n[e].maxKey(),!0):!1}mergeSibling(e,t){const n=this.keys.length;this.keys.push.apply(this.keys,e.keys);const r=e.children;if(this.children.push.apply(this.children,r),e.isShared&&!this.isShared)for(const i of r)i.isShared=!0;this.tryMerge(n-1,t)}}const H=[],sa={delete:!0},na=()=>sa,jt=(function(){const s=new nt;return s.isShared=!0,s})(),hn=[];function ra(s,...e){throw e.unshift("B+ tree"),new Error(e.join(" "))}function Fn(){const s=new Map;function e(t){const n=t.join(".");if(s.has(n))return s.get(n);const r=new Proxy({},{get(i,o,a){if(o==="__refProxy")return!0;if(o==="__path")return t;if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(i,o,a);const c=[...t,String(o)];return e(c)},has(i,o){return o==="__refProxy"||o==="__path"||o==="__type"?!0:Reflect.has(i,o)},ownKeys(i){return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,o){return o==="__refProxy"||o==="__path"||o==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(i,o)}});return s.set(n,r),r}return e([])}function ke(s){const e=new Map;let t=0;function n(i){const o=i.join(".");if(e.has(o))return e.get(o);const a=new Proxy({},{get(c,l,u){if(l==="__refProxy")return!0;if(l==="__path")return i;if(l==="__type")return;if(typeof l=="symbol")return Reflect.get(c,l,u);const h=[...i,String(l)];return n(h)},has(c,l){return l==="__refProxy"||l==="__path"||l==="__type"?!0:Reflect.has(c,l)},ownKeys(c){const l=++t,u=`__SPREAD_SENTINEL__${i.join(".")}__${l}`;return Object.prototype.hasOwnProperty.call(c,u)||Object.defineProperty(c,u,{enumerable:!0,configurable:!0,value:!0}),Reflect.ownKeys(c)},getOwnPropertyDescriptor(c,l){return l==="__refProxy"||l==="__path"||l==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(c,l)}});return e.set(o,a),a}return new Proxy({},{get(i,o,a){if(o==="__refProxy")return!0;if(o==="__path")return[];if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(i,o,a);const c=String(o);if(s.includes(c))return n([c])},has(i,o){return o==="__refProxy"||o==="__path"||o==="__type"||typeof o=="string"&&s.includes(o)?!0:Reflect.has(i,o)},ownKeys(i){return[...s,"__refProxy","__path","__type"]},getOwnPropertyDescriptor(i,o){if(o==="__refProxy"||o==="__path"||o==="__type")return{enumerable:!1,configurable:!0};if(typeof o=="string"&&s.includes(o))return{enumerable:!0,configurable:!0}}})}function dn(s){const e=ke(s),t=new Map;function n(i){const o=i.join(".");if(t.has(o))return t.get(o);const a=new Proxy({},{get(c,l,u){if(l==="__refProxy")return!0;if(l==="__path")return["$selected",...i];if(l==="__type")return;if(typeof l=="symbol")return Reflect.get(c,l,u);const h=[...i,String(l)];return n(h)},has(c,l){return l==="__refProxy"||l==="__path"||l==="__type"?!0:Reflect.has(c,l)},ownKeys(c){return Reflect.ownKeys(c)},getOwnPropertyDescriptor(c,l){return l==="__refProxy"||l==="__path"||l==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(c,l)}});return t.set(o,a),a}const r=n([]);return new Proxy(e,{get(i,o,a){return o==="$selected"?r:Reflect.get(i,o,a)},has(i,o){return o==="$selected"?!0:Reflect.has(i,o)},ownKeys(i){return[...Reflect.ownKeys(i),"$selected"]},getOwnPropertyDescriptor(i,o){return o==="$selected"?{enumerable:!0,configurable:!0,value:r}:Reflect.getOwnPropertyDescriptor(i,o)}})}function L(s){return ia(s)?new Y(s.__path):s&&typeof s=="object"&&"type"in s&&(s.type==="func"||s.type==="ref"||s.type==="val"||s.type==="agg")?s:new X(s)}function ia(s){return s&&typeof s=="object"&&s.__refProxy===!0}function Qt(s,e){return new se("eq",[L(s),L(e)])}function fn(s,e){return new se("gt",[L(s),L(e)])}function oa(s,e){return new se("gte",[L(s),L(e)])}function Jt(s,e){return new se("lt",[L(s),L(e)])}function Yt(s,e,...t){const n=[s,e,...t];return new se("and",n.map(r=>L(r)))}function aa(s,e,...t){const n=[s,e,...t];return new se("or",n.map(r=>L(r)))}function ca(s,e){return new se("in",[L(s),L(e)])}function Fl(s,e){return new se("ilike",[L(s),L(e)])}class la{constructor(e,t,n,r){this.lookupCount=0,this.totalLookupTime=0,this.lastUpdated=new Date,this.id=e,this.expression=t,this.compareOptions=ws,this.name=n,this.initialize(r)}supports(e){return this.supportedOperations.has(e)}matchesField(e){return this.expression.type==="ref"&&this.expression.path.length===e.length&&this.expression.path.every((t,n)=>t===e[n])}matchesCompareOptions(e){const t={...this.compareOptions,direction:void 0},n={...e,direction:void 0};return le(t,n)}matchesDirection(e){return this.compareOptions.direction===e}getStats(){return{entryCount:this.keyCount,lookupCount:this.lookupCount,averageLookupTime:this.lookupCount>0?this.totalLookupTime/this.lookupCount:0,lastUpdated:this.lastUpdated}}evaluateIndexExpression(e){return gs(this.expression)(e)}trackLookup(e){const t=performance.now()-e;this.lookupCount++,this.totalLookupTime+=t}updateTimestamp(){this.lastUpdated=new Date}}class Zt extends la{constructor(e,t,n,r){super(e,t,n,r),this.supportedOperations=new Set(["eq","gt","gte","lt","lte","in"]),this.valueMap=new Map,this.indexedKeys=new Set,this.compareFn=qt;const i=r?.compareFn??qt;this.compareFn=(o,a)=>i(qe(o),qe(a)),r?.compareOptions&&(this.compareOptions=r.compareOptions),this.orderedEntries=new ta(this.compareFn)}initialize(e){}add(e,t){let n;try{n=this.evaluateIndexExpression(t)}catch(i){throw new Error(`Failed to evaluate index expression for key ${e}: ${i}`)}const r=we(n);if(this.valueMap.has(r))this.valueMap.get(r).add(e);else{const i=new Set([e]);this.valueMap.set(r,i),this.orderedEntries.set(r,void 0)}this.indexedKeys.add(e),this.updateTimestamp()}remove(e,t){let n;try{n=this.evaluateIndexExpression(t)}catch(i){console.warn(`Failed to evaluate index expression for key ${e} during removal:`,i);return}const r=we(n);if(this.valueMap.has(r)){const i=this.valueMap.get(r);i.delete(e),i.size===0&&(this.valueMap.delete(r),this.orderedEntries.delete(r))}this.indexedKeys.delete(e),this.updateTimestamp()}update(e,t,n){this.remove(e,t),this.add(e,n)}build(e){this.clear();for(const[t,n]of e)this.add(t,n)}clear(){this.orderedEntries.clear(),this.valueMap.clear(),this.indexedKeys.clear(),this.updateTimestamp()}lookup(e,t){const n=performance.now();let r;switch(e){case"eq":r=this.equalityLookup(t);break;case"gt":r=this.rangeQuery({from:t,fromInclusive:!1});break;case"gte":r=this.rangeQuery({from:t,fromInclusive:!0});break;case"lt":r=this.rangeQuery({to:t,toInclusive:!1});break;case"lte":r=this.rangeQuery({to:t,toInclusive:!0});break;case"in":r=this.inArrayLookup(t);break;default:throw new Error(`Operation ${e} not supported by BTreeIndex`)}return this.trackLookup(n),r}get keyCount(){return this.indexedKeys.size}equalityLookup(e){const t=we(e);return new Set(this.valueMap.get(t)??[])}rangeQuery(e={}){const{from:t,to:n,fromInclusive:r=!0,toInclusive:i=!0}=e,o=new Set,a="from"in e,c="to"in e,l=a?we(t):this.orderedEntries.minKey(),u=c?we(n):this.orderedEntries.maxKey();return this.orderedEntries.forRange(l,u,i,(h,y)=>{if(!r&&this.compareFn(h,t)===0)return;const f=this.valueMap.get(h);f&&f.forEach(d=>o.add(d))}),o}rangeQueryReversed(e={}){const{from:t,to:n,fromInclusive:r=!0,toInclusive:i=!0}=e,o="from"in e,a="to"in e;return this.rangeQuery({from:a?n:this.orderedEntries.maxKey(),to:o?t:this.orderedEntries.minKey(),fromInclusive:i,toInclusive:r})}takeInternal(e,t,n,r,i=!1){const o=new Set,a=[];let c,l=n;for(;(c=t(l))!==void 0&&a.length<e;){l=c[0];const u=this.valueMap.get(l);if(u&&u.size>0){const h=Array.from(u).sort(St);i&&h.reverse();for(const y of h){if(a.length>=e)break;!o.has(y)&&(r?.(y)??!0)&&(a.push(y),o.add(y))}}}return a}take(e,t,n){const r=o=>this.orderedEntries.nextHigherPair(o),i=we(t);return this.takeInternal(e,r,i,n)}takeFromStart(e,t){const n=r=>this.orderedEntries.nextHigherPair(r);return this.takeInternal(e,n,void 0,t)}takeReversed(e,t,n){const r=o=>this.orderedEntries.nextLowerPair(o),i=we(t);return this.takeInternal(e,r,i,n,!0)}takeReversedFromEnd(e,t){const n=r=>this.orderedEntries.nextLowerPair(r);return this.takeInternal(e,n,void 0,t,!0)}inArrayLookup(e){const t=new Set;for(const n of e){const r=we(n),i=this.valueMap.get(r);i&&i.forEach(o=>t.add(o))}return t}get indexedKeysSet(){return this.indexedKeys}get orderedEntriesArray(){return this.orderedEntries.keysArray().map(e=>[qe(e),this.valueMap.get(e)??new Set])}get orderedEntriesArrayReversed(){return this.takeReversedFromEnd(this.orderedEntries.size).map(e=>[qe(e),this.valueMap.get(e)??new Set])}get valueMapData(){const e=new Map;for(const[t,n]of this.valueMap)e.set(qe(t),n);return e}}function jn(s){return s.config.autoIndex==="eager"}function _t(s,e,t,n,r){if(!jn(t))return;const i=n??{...ws,...t.compareOptions};if(!Array.from(t.indexes.values()).find(a=>a.matchesField(e)&&a.matchesCompareOptions(i)))try{t.createIndex(a=>{let c=a;for(const l of e)c=c[l];return c},{name:`auto:${e.join(".")}`,indexType:Zt,options:r?{compareFn:r,compareOptions:i}:{}})}catch(a){console.warn(`${t.id?`[${t.id}] `:""}Failed to create auto-index for field path "${e.join(".")}":`,a)}}function ua(s,e){if(!jn(e))return;const t=ha(s);for(const{fieldName:n,fieldPath:r}of t)_t(n,r,e)}function ha(s){const e=[];function t(n){if(n.type!=="func")return;const r=n;if(r.name==="and"){for(const l of r.args)t(l);return}if(!["eq","gt","gte","lt","lte","in"].includes(r.name)||r.args.length<1||r.args[0].type!=="ref")return;const a=r.args[0].path;if(a.length===0)return;const c=a.join("_");e.push({fieldName:c,fieldPath:a})}return t(s),e}const{sum:da,count:fa,avg:pa,min:ya,max:ga}=Do;function ma(s,e){const t=new Map,n=[...s];if(!e)return{selectToGroupByIndex:t,groupByExpressions:n};for(const[r,i]of Object.entries(e)){if(i.type==="agg")continue;const o=n.findIndex(a=>xt(i,a));if(o===-1)throw new vi(r);t.set(r,o)}return{selectToGroupByIndex:t,groupByExpressions:n}}function pn(s,e,t,n,r){if(e.length===0){const l={};if(n){for(const[h,y]of Object.entries(n))if(y.type==="agg"){const f=y;l[h]=yn(f)}}const u=()=>({__singleGroup:!0});if(s=s.pipe(sn(u,l)),s=s.pipe(J(([,h])=>{const f={...h.$selected||{}};if(n)for(const[d,p]of Object.entries(n))p.type==="agg"&&(f[d]=h[d]);return["single_group",{...h,$selected:f}]})),t&&t.length>0)for(const h of t){const y=$s(h),f=Ct(y,n||{},"$selected"),d=ee(f);s=s.pipe(Se(([,p])=>{const g={$selected:p.$selected};return De(d(g))}))}if(r&&r.length>0)for(const h of r)s=s.pipe(Se(([,y])=>{const f={$selected:y.$selected};return De(h(f))}));return s}const i=ma(e,n),o=e.map(l=>ee(l)),a=([,l])=>{const u={...l};delete u.$selected;const h={};for(let y=0;y<e.length;y++){const f=o[y],d=f(u);h[`__key_${y}`]=d}return h},c={};if(n){for(const[l,u]of Object.entries(n))if(u.type==="agg"){const h=u;c[l]=yn(h)}}if(s=s.pipe(sn(a,c)),s=s.pipe(J(([,l])=>{const u=l.$selected||{},h={};if(n)for(const[f,d]of Object.entries(n))if(d.type!=="agg"){const p=i.selectToGroupByIndex.get(f);p!==void 0?h[f]=l[`__key_${p}`]:h[f]=u[f]}else h[f]=l[f];else for(let f=0;f<e.length;f++)h[`__key_${f}`]=l[`__key_${f}`];let y;if(e.length===1)y=l.__key_0;else{const f=[];for(let d=0;d<e.length;d++)f.push(l[`__key_${d}`]);y=bs(f)}return[y,{...l,$selected:h}]})),t&&t.length>0)for(const l of t){const u=$s(l),h=Ct(u,n||{}),y=ee(h);s=s.pipe(Se(([,f])=>{const d={$selected:f.$selected};return y(d)}))}if(r&&r.length>0)for(const l of r)s=s.pipe(Se(([,u])=>{const h={$selected:u.$selected};return De(l(h))}));return s}function xt(s,e){if(!s||!e||s.type!==e.type)return!1;switch(s.type){case"ref":return!s.path||!e.path||s.path.length!==e.path.length?!1:s.path.every((t,n)=>t===e.path[n]);case"val":return s.value===e.value;case"func":return s.name===e.name&&s.args?.length===e.args?.length&&(s.args||[]).every((t,n)=>xt(t,e.args[n]));case"agg":return s.name===e.name&&s.args?.length===e.args?.length&&(s.args||[]).every((t,n)=>xt(t,e.args[n]));default:return!1}}function yn(s){const e=ee(s.args[0]),t=([,i])=>{const o=e(i);return typeof o=="number"?o:o!=null?Number(o):0},n=([,i])=>{const o=e(i);return typeof o=="number"||typeof o=="string"||typeof o=="bigint"||o instanceof Date?o:o!=null?Number(o):0},r=([,i])=>e(i);switch(s.name.toLowerCase()){case"sum":return da(t);case"count":return fa(r);case"avg":return pa(t);case"min":return ya(n);case"max":return ga(n);default:throw new bi(s.name)}}function Ct(s,e,t="$selected"){switch(s.type){case"agg":{const n=s;for(const[r,i]of Object.entries(e))if(i.type==="agg"&&wa(n,i))return new Y([t,r]);throw new Si(n.name)}case"func":{const n=s,r=n.args.map(i=>Ct(i,e));return new se(n.name,r)}case"ref":return s;case"val":return s;default:throw new xi(s.type)}}function wa(s,e){return s.name===e.name&&s.args.length===e.args.length&&s.args.every((t,n)=>xt(t,e.args[n]))}function va(s,e,t,n,r,i,o,a,c){const l=t.map(d=>{const p=Ct(d.expression,n,"$selected");return{compiledExpression:ee(p),compareOptions:Xt(d,r)}}),u=d=>{const p=d;return t.length>1?l.map(g=>g.compiledExpression(p)):t.length===1?l[0].compiledExpression(p):null},h=(d,p)=>{if(t.length>1){const g=d,m=p;for(let w=0;w<t.length;w++){const S=l[w],k=bt(S.compareOptions)(g[w],m[w]);if(k!==0)return k}return g.length-m.length}if(t.length===1){const g=l[0];return bt(g.compareOptions)(d,p)}return qt(d,p)};let y,f;if(a){let d,p,g,m=s.from.alias;const w=t[0],S=w.expression;if(S.type==="ref"){const b=tt(s,S,r);if(b){p=b.collection;const k=b.path[0],_=Xt(w,p);k&&_t(k,b.path,p,_,h),g=ee(new Y(b.path),!0),d=at(p,b.path,_),d?.supports("gt")||(d=void 0),m=S.path.length>1?String(S.path[0]):s.from.alias}}if(g){const k=t.every(v=>v.expression.type==="ref")?t.map(v=>{const x=v.expression,M=tt(s,x,r);return ee(M?new Y(M.path):v.expression,!0)}):void 0;f={alias:m,offset:c??0,limit:a,comparator:(v,x)=>{if(t.length===1){const M=v&&g(v),K=x&&g(x);return h(M,K)}if(k){const M=K=>K&&k.map(B=>B(K));return h(M(v),M(x))}return 0},valueExtractorForRawRow:v=>{if(t.length===1)return g(v);if(k)return k.map(x=>x(v))},firstColumnValueExtractor:g,index:d,orderBy:t};const I=p?.id??r.id;i[I]=f,d&&(y=v=>{i[I].dataNeeded=()=>{const x=v();return Math.max(0,f.limit-x)}})}}return e.pipe(ea(u,{limit:a,offset:c,comparator:h,setSizeCallback:y,setWindowFn:d=>{o(p=>{d(p),f&&(f.offset=p.offset??f.offset,f.limit=p.limit??f.limit)})}}))}function Xt(s,e){return s.compareOptions.stringSort!==void 0?s.compareOptions:{...e.compareOptions,direction:s.compareOptions.direction,nulls:s.compareOptions.nulls}}function ba(s,e={}){const t=n=>{const r=[];for(const[i,o]of s.entries())(n?.(o)??!0)&&r.push({type:"insert",key:i,value:o});return r};if(e.limit!==void 0&&!e.orderBy)throw new Error("limit cannot be used without orderBy");if(e.orderBy){const n=e.where?Xe(e.where):void 0,r=xa(s,e.orderBy,e.limit,n,e.optimizedOnly);if(r===void 0)return;const i=[];for(const o of r){const a=s.get(o);a!==void 0&&i.push({type:"insert",key:o,value:a})}return i}if(!e.where)return t();try{const n=e.where,r=zi(n,s);if(r.canOptimize){const i=[];for(const o of r.matchingKeys){const a=s.get(o);a!==void 0&&i.push({type:"insert",key:o,value:a})}return i}else{if(e.optimizedOnly)return;const i=Xe(n);return t(i)}}catch(n){console.warn(`${s.id?`[${s.id}] `:""}Error processing where clause, falling back to full scan:`,n);const r=Xe(e.where);return e.optimizedOnly?void 0:t(r)}}function Xe(s){const e=gs(s);return t=>{try{const n=e(t);return De(n)}catch{return!1}}}function Sa(s,e){const t=Xe(e.whereExpression);return n=>{const r=[];for(const i of n)if(i.type==="insert")t(i.value)&&r.push(i);else if(i.type==="update"){const o=t(i.value),a=i.previousValue?t(i.previousValue):!1;o&&a?r.push(i):o&&!a?r.push({...i,type:"insert"}):!o&&a&&r.push({...i,type:"delete",value:i.previousValue})}else t(i.value)&&r.push(i);(r.length>0||n.length===0)&&s(r)}}function xa(s,e,t,n,r){if(e.length===1){const c=e[0],l=c.expression;if(l.type==="ref"){const h=l.path,y=Xt(c,s);_t(h[0],h,s,y);const f=at(s,h,y);if(f&&f.supports("gt")){const d=p=>{const g=s.get(p);return g===void 0?!1:n?.(g)??!0};return f.takeFromStart(t??f.keyCount,d)}}}if(r)return;const i=[];for(const[c,l]of s.entries())(n?.(l)??!0)&&i.push({key:c,value:l});const o=(c,l)=>{for(const u of e){const h=bt(u.compareOptions),y=gn(c.value,u.expression),f=gn(l.value,u.expression),d=h(y,f);if(d!==0)return d}return 0};i.sort(o);const a=i.map(c=>c.key);return t!==void 0?a.slice(0,t):a}function gn(s,e){if(e.type==="ref"){const t=e;let n=s;for(const r of t.path)n=n?.[r];return n}else return e.type==="val"?e.value:gs(e)(s)}class mn{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;){const i=Math.floor((n+r)/2),o=this.sortedKeys[i],a=St(e,o);if(a<0)r=i;else if(a>0)n=i+1;else return i}return n}for(;n<r;){const i=Math.floor((n+r)/2),o=this.sortedKeys[i],a=this.map.get(o),c=this.comparator(t,a);if(c<0)r=i;else if(c>0)n=i+1;else{const l=St(e,o);if(l<0)r=i;else if(l>0)n=i+1;else return i}}return n}set(e,t){if(this.map.has(e)){const r=this.map.get(e),i=this.indexOf(e,r);this.sortedKeys.splice(i,1)}const 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)){const 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(const 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(const e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(const t of this.sortedKeys)e(this.map.get(t),t,this.map)}}class Ca{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.size=0,this.syncedKeys=new Set,this.preSyncVisibleState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.commitPendingTransactions=()=>{let t=!1;for(const a of this.transactions.values())if(a.state==="persisting"){t=!0;break}const{committedSyncedTransactions:n,uncommittedSyncedTransactions:r,hasTruncateSync:i,hasImmediateSync:o}=this.pendingSyncedTransactions.reduce((a,c)=>(c.committed?(a.committedSyncedTransactions.push(c),c.truncate&&(a.hasTruncateSync=!0),c.immediate&&(a.hasImmediateSync=!0)):a.uncommittedSyncedTransactions.push(c),a),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1});if(!t||i||o){this.isCommittingSyncTransactions=!0;const a=i?n.find(f=>f.truncate)?.optimisticSnapshot:null,c=new Set;for(const f of n)for(const d of f.operations)c.add(d.key);let l=this.preSyncVisibleState;if(l.size===0){l=new Map;for(const f of c){const d=this.get(f);d!==void 0&&l.set(f,d)}}const u=[],h=this.config.sync.rowUpdateMode||"partial";for(const f of n){if(f.truncate){const d=new Set([...this.syncedData.keys(),...a?.upserts.keys()||[]]);for(const p of d){if(a?.deletes.has(p))continue;const g=a?.upserts.get(p)||this.syncedData.get(p);g!==void 0&&u.push({type:"delete",key:p,value:g})}this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear();for(const p of c)l.delete(p);this._events.emit("truncate",{type:"truncate",collection:this.collection})}for(const d of f.operations){const p=d.key;switch(this.syncedKeys.add(p),d.type){case"insert":this.syncedMetadata.set(p,d.metadata);break;case"update":this.syncedMetadata.set(p,Object.assign({},this.syncedMetadata.get(p),d.metadata));break;case"delete":this.syncedMetadata.delete(p);break}switch(d.type){case"insert":this.syncedData.set(p,d.value);break;case"update":{if(h==="partial"){const g=Object.assign({},this.syncedData.get(p),d.value);this.syncedData.set(p,g)}else this.syncedData.set(p,d.value);break}case"delete":this.syncedData.delete(p);break}}}if(i){const f=new Set;for(const g of n)for(const m of g.operations)(m.type==="insert"||m.type==="update")&&f.add(m.key);const d=new Map(a.upserts),p=new Set(a.deletes);for(const[g,m]of d)if(!p.has(g))if(f.has(g)){let w=!1;for(let S=u.length-1;S>=0;S--){const b=u[S];if(b.key===g&&b.type==="insert"){b.value=m,w=!0;break}}w||u.push({type:"insert",key:g,value:m})}else u.push({type:"insert",key:g,value:m});if(u.length>0&&p.size>0){const g=[];for(const m of u)m.type==="insert"&&p.has(m.key)||g.push(m);u.length=0,u.push(...g)}this.lifecycle.status!=="ready"&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,i&&a){for(const[f,d]of a.upserts)this.optimisticUpserts.set(f,d);for(const f of a.deletes)this.optimisticDeletes.add(f)}for(const f of this.transactions.values())if(!["completed","failed"].includes(f.state)){for(const d of f.mutations)if(this.isThisCollection(d.collection)&&d.optimistic)switch(d.type){case"insert":case"update":this.optimisticUpserts.set(d.key,d.modified),this.optimisticDeletes.delete(d.key);break;case"delete":this.optimisticUpserts.delete(d.key),this.optimisticDeletes.add(d.key);break}}const y=new Map;for(const f of this.transactions.values())if(f.state==="completed")for(const d of f.mutations)d.optimistic&&this.isThisCollection(d.collection)&&c.has(d.key)&&y.set(d.key,{type:d.type,value:d.modified});for(const f of c){const d=l.get(f),p=this.get(f),g=y.get(f);let m=!1;g&&(g.type==="delete"&&d!==void 0&&p===void 0&&le(g.value,d)||p!==void 0&&le(g.value,p))&&(m=!0),m||(d===void 0&&p!==void 0?u.push({type:"insert",key:f,value:p}):d!==void 0&&p===void 0?u.push({type:"delete",key:f,value:d}):d!==void 0&&p!==void 0&&!le(d,p)&&u.push({type:"update",key:f,value:p,previousValue:d}))}this.size=this.calculateSize(),u.length>0&&this.indexes.updateIndexes(u),this.changes.emitEvents(u,!0),this.pendingSyncedTransactions=r,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0)}},this.config=e,this.transactions=new mn((t,n)=>t.compareCreatedAt(n)),this.syncedData=new mn(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this._events=e.events}get(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;if(!t.has(e))return n.has(e)?n.get(e):r.get(e)}has(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;return t.has(e)?!1:n.has(e)?!0:r.has(e)}*keys(){const{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(const r of e.keys())t.has(r)||(yield r);for(const r of n.keys())!e.has(r)&&!t.has(r)&&(yield r)}*values(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){for(const[e,t]of this.entries())yield[e,t]}forEach(e){let t=0;for(const[n,r]of this.entries())e(r,n,t++)}map(e){const t=[];let n=0;for(const[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;const t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes);this.optimisticUpserts.clear(),this.optimisticDeletes.clear();const r=[];for(const a of this.transactions.values())["completed","failed"].includes(a.state)||r.push(a);for(const a of r)for(const c of a.mutations)if(this.isThisCollection(c.collection)&&c.optimistic)switch(c.type){case"insert":case"update":this.optimisticUpserts.set(c.key,c.modified),this.optimisticDeletes.delete(c.key);break;case"delete":this.optimisticUpserts.delete(c.key),this.optimisticDeletes.add(c.key);break}this.size=this.calculateSize();const i=[];this.collectOptimisticChanges(t,n,i);const o=i.filter(a=>!!(!this.recentlySyncedKeys.has(a.key)||e));if(this.pendingSyncedTransactions.length>0&&!e){const a=new Set;for(const l of this.pendingSyncedTransactions)for(const u of l.operations)a.add(u.key);const c=o.filter(l=>!(l.type==="delete"&&a.has(l.key)&&!r.some(h=>h.mutations.some(y=>this.isThisCollection(y.collection)&&y.key===l.key))));c.length>0&&this.indexes.updateIndexes(c),this.changes.emitEvents(c,e)}else o.length>0&&this.indexes.updateIndexes(o),this.changes.emitEvents(o,e)}calculateSize(){const e=this.syncedData.size,t=Array.from(this.optimisticDeletes).filter(r=>this.syncedData.has(r)&&!this.optimisticUpserts.has(r)).length,n=Array.from(this.optimisticUpserts.keys()).filter(r=>!this.syncedData.has(r)).length;return e-t+n}collectOptimisticChanges(e,t,n){const r=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(const i of r){const o=this.get(i),a=this.getPreviousValue(i,e,t);a!==void 0&&o===void 0?n.push({type:"delete",key:i,value:a}):a===void 0&&o!==void 0?n.push({type:"insert",key:i,value:o}):a!==void 0&&o!==void 0&&a!==o&&n.push({type:"update",key:i,value:o,previousValue:a})}}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;const e=new Set;for(const t of this.pendingSyncedTransactions)for(const n of t.operations)e.add(n.key);for(const t of e)this.recentlySyncedKeys.add(t);for(const t of e)if(!this.preSyncVisibleState.has(t)){const n=this.get(t);n!==void 0&&this.preSyncVisibleState.set(t,n)}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncedData.clear(),this.syncedMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.size=0,this.pendingSyncedTransactions=[],this.syncedKeys.clear(),this.hasReceivedFirstCommit=!1}}class Bn{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){const n=this.on(e,r=>{t(r),n()});return n}off(e,t){this.listeners.get(e)?.delete(t)}waitFor(e,t){return new Promise((n,r)=>{let i;const o=this.on(e,a=>{i&&(clearTimeout(i),i=void 0),n(a),o()});t&&(i=setTimeout(()=>{i=void 0,o(),r(new Error(`Timeout waiting for event ${String(e)}`))},t))})}emitInner(e,t){this.listeners.get(e)?.forEach(n=>{try{n(t)}catch(r){queueMicrotask(()=>{throw r})}})}clearListeners(){this.listeners.clear()}}function Ia(s,e){if(e.length===0||s.length===0)return;if(s.length===1){const{expression:n,compareOptions:r}=s[0];return(r.direction==="asc"?fn:Jt)(n,new X(e[0]))}const t=[];for(let n=0;n<s.length&&n<e.length;n++){const r=s[n],i=e[n],o=[];for(let l=0;l<n;l++){const u=s[l],h=e[l];o.push(Qt(u.expression,new X(h)))}const c=(r.compareOptions.direction==="asc"?fn:Jt)(r.expression,new X(i));if(o.length===0)t.push(c);else{const l=[...o,c];t.push(l.reduce((u,h)=>Yt(u,h)))}}return t.length===1?t[0]:t.reduce((n,r)=>aa(n,r))}class Ea extends Bn{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",i=>n.onUnsubscribe(i)),n.whereExpression&&ua(n.whereExpression,this.collection);const r=i=>{t(i),this.trackSentKeys(i)};this.callback=r,this.filteredCallback=n.whereExpression?Sa(this.callback,n):this.callback,this.truncateCleanup=this.collection.on("truncate",()=>{this.handleTruncate()})}get status(){return this._status}handleTruncate(){const 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(const n of e){const r=this.collection._sync.loadSubset(n);this.loadedSubsets.push(n),this.trackLoadSubsetPromise(r),r instanceof Promise&&(this.pendingTruncateRefetches.add(r),r.catch(()=>{}).finally(()=>{this.pendingTruncateRefetches.delete(r),this.checkTruncateRefetchComplete()}))}this.pendingTruncateRefetches.size===0&&this.flushTruncateBuffer()}})}checkTruncateRefetchComplete(){this.pendingTruncateRefetches.size===0&&this.isBufferingForTruncate&&this.flushTruncateBuffer()}flushTruncateBuffer(){this.isBufferingForTruncate=!1;const e=this.truncateBuffer.flat();e.length>0&&this.filteredCallback(e),this.truncateBuffer=[]}setOrderByIndex(e){this.orderByIndex=e}setStatus(e){if(this._status===e)return;const t=this._status;this._status=e,this.emitInner("status:change",{type:"status:change",subscription:this,previousStatus:t,status:e});const 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){const t=this.filterAndFlipChanges(e);this.isBufferingForTruncate?t.length>0&&this.truncateBuffer.push(t):this.filteredCallback(t)}requestSnapshot(e){if(this.loadedInitialState)return!1;const t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if("where"in e){const c=e.where;if(t.where){const l=t.where,u=Yt(l,c);t.where=u}else t.where=c}}else this.loadedInitialState=!0;const 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);const o=this.collection.currentStateAsChanges(t);if(o===void 0)return!1;const a=o.filter(c=>!this.sentKeys.has(c.key));for(const c of a)this.sentKeys.add(c.key);return this.snapshotSent=!0,this.callback(a),!0}requestLimitedSnapshot({orderBy:e,limit:t,minValues:n,offset:r,trackLoadSubsetPromise:i=!0,onLoadSubsetResult:o}){if(!t)throw new Error("limit is required");if(!this.orderByIndex)throw new Error("Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.");const a=n!==void 0&&n.length>0,l=n?.[0],u=this.orderByIndex,h=this.options.whereExpression,y=h?Xe(h):void 0,f=v=>{if(v!==void 0&&this.sentKeys.has(v))return!1;const x=this.collection.get(v);return x===void 0?!1:y?.(x)??!0};let d=l;const p=[];let g=[];if(a){const{expression:v}=e[0],x=this.collection.currentStateAsChanges({where:Qt(v,new X(l))});if(x){const M=x.map(B=>B.key).filter(B=>!this.sentKeys.has(B)&&f(B));g.push(...M);const K=u.take(t-g.length,l,f);g.push(...K)}else g=u.take(t,l,f)}else g=u.takeFromStart(t,f);const m=()=>Math.max(t-p.length,0),w=()=>g.length===0,S=e[0].expression,b=S.type==="ref"?ee(new Y(S.path),!0):null;for(;m()>0&&!w();){const v=new Set;for(const x of g){const M=this.collection.get(x);p.push({type:"insert",key:x,value:M}),d=b?b(M):M,v.add(x)}g=u.take(m(),d,f)}const k=this.limitedSnapshotRowCount;for(const v of p)this.sentKeys.add(v.key);this.callback(p),this.limitedSnapshotRowCount+=p.length,p.length>0&&(this.lastSentKey=p[p.length-1].key);let _;if(n!==void 0&&n.length>0){const v=Ia(e,n);if(v){const{expression:x}=e[0],M=n[0];let K;if(M instanceof Date){const B=new Date(M.getTime()+1);K=Yt(oa(x,new X(M)),Jt(x,new X(B)))}else K=Qt(x,new X(M));_={whereFrom:v,whereCurrent:K,lastKey:this.lastSentKey}}}const D={where:h,limit:t,orderBy:e,cursor:_,offset:r??k,subscription:this},I=this.collection._sync.loadSubset(D);o?.(I),this.loadedSubsets.push(D),i&&this.trackLoadSubsetPromise(I)}filterAndFlipChanges(e){if(this.loadedInitialState||this.skipFiltering)return e;const t=this.isBufferingForTruncate,n=[];for(const r of e){let i=r;if(this.sentKeys.has(r.key)){if(r.type==="insert")continue;r.type==="delete"&&this.sentKeys.delete(r.key)}else{if(r.type==="update")i={...r,type:"insert",previousValue:void 0};else if(r.type==="delete"&&!t)continue;this.sentKeys.add(r.key)}n.push(i)}return n}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering)){for(const 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(const e of this.loadedSubsets)this.collection._sync.unloadSubset(e);this.loadedSubsets=[],this.emitInner("unsubscribed",{type:"unsubscribed",subscription:this}),this.clearListeners()}}class Ra{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}emitEmptyReadyEvent(){for(const e of this.changeSubscriptions)e.emitEvents([])}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)for(const r of this.changeSubscriptions)r.emitEvents(n)}subscribeChanges(e,t={}){if(this.addSubscriber(),t.where&&t.whereExpression)throw new Error("Cannot specify both 'where' and 'whereExpression' options. Use one or the other.");const{where:n,...r}=t;let i=r.whereExpression;if(n){const a=Fn(),c=n(a);i=L(c)}const o=new Ea(this.collection,e,{...r,whereExpression:i,onUnsubscribe:()=>{this.removeSubscriber(),this.changeSubscriptions.delete(o)}});return t.onStatusChange&&o.on("status:change",t.onStatusChange),t.includeInitialState?o.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetResult:t.onLoadSubsetResult}):t.includeInitialState===!1&&o.markAllStateAsSeen(),this.changeSubscriptions.add(o),o}addSubscriber(){const 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(){const e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new Pr;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}}const ka=s=>setTimeout(()=>{s({didTimeout:!0,timeRemaining:()=>50})},0),Oa=s=>{clearTimeout(s)},_a=typeof window<"u"&&"requestIdleCallback"in window?(s,e)=>window.requestIdleCallback(s,e):(s,e)=>ka(s),Bt=typeof window<"u"&&"cancelIdleCallback"in window?s=>window.cancelIdleCallback(s):Oa;class Aa{constructor(e,t){this.status="idle",this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.gcTimeoutId=null,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)return;if(!{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 Mr(e,t,this.id)}setStatus(e,t=!1){if(e==="ready"&&!t)throw new ot(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);const n=this.status;this.status=e,e==="ready"&&!this.indexes.isIndexesResolved&&this.indexes.resolveAllIndexes().catch(r=>{console.warn(`${this.config.id?`[${this.config.id}] `:""}Failed to resolve indexes:`,r)}),this.events.emitStatusChange(e,n)}validateCollectionUsable(e){switch(this.status){case"error":throw new Ar(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||(this.hasReceivedFirstCommit=!0);const e=[...this.onFirstReadyCallbacks];this.onFirstReadyCallbacks=[],e.forEach(t=>t())}this.changes.changeSubscriptions.size>0&&this.changes.emitEmptyReadyEvent()}}startGCTimer(){this.gcTimeoutId&&clearTimeout(this.gcTimeoutId);const e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||(this.gcTimeoutId=setTimeout(()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()},e))}cancelGCTimer(){this.gcTimeoutId&&(clearTimeout(this.gcTimeoutId),this.gcTimeoutId=null),this.idleCallbackId!==null&&(Bt(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Bt(this.idleCallbackId),this.idleCallbackId=_a(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(),this.gcTimeoutId&&(clearTimeout(this.gcTimeoutId),this.gcTimeoutId=null),this.hasBeenReady=!1;const n=[...this.onFirstReadyCallbacks];return this.onFirstReadyCallbacks=[],n.forEach(r=>{try{r()}catch(i){console.error(`${this.config.id?`[${this.config.id}] `:""}Error in onFirstReady callback during cleanup:`,i)}}),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&&(Bt(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}const Cs=Symbol("liveQueryInternal");class Ma{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{const e=Ta(this.config.sync.sync({collection:this.collection,begin:t=>{this.state.pendingSyncedTransactions.push({committed:!1,operations:[],deletedKeys:new Set,immediate:t?.immediate})},write:t=>{const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!n)throw new Ws;if(n.committed)throw new Gs;let r;"key"in t?r=t.key:r=this.config.getKey(t.value);let i=t.type;if(t.type==="insert"){const a=this.state.syncedData.has(r),c=n.deletedKeys.has(r),l=n.truncate===!0;if(a&&!c&&!l){const u=this.state.syncedData.get(r);if(u!==void 0&&le(u,t.value))i="update";else{const f=this.config.utils[Cs];throw new jr(r,this.id,{hasCustomGetKey:f?.hasCustomGetKey??!1,hasJoins:f?.hasJoins??!1,hasDistinct:f?.hasDistinct??!1})}}}const o={...t,type:i,key:r};n.operations.push(o),i==="delete"&&n.deletedKeys.add(r)},commit:()=>{const t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!t)throw new Yr;if(t.committed)throw new Zr;t.committed=!0,this.state.commitPendingTransactions()},markReady:()=>{this.lifecycle.markReady()},truncate:()=>{const t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!t)throw new Ws;if(t.committed)throw new Gs;t.operations=[],t.deletedKeys.clear(),t.truncate=!0,t.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}}}));if(this.syncCleanupFn=e?.cleanup??null,this.syncLoadSubsetFn=e?.loadSubset??null,this.syncUnloadSubsetFn=e?.unloadSubset??null,this.syncMode==="on-demand"&&!this.syncLoadSubsetFn)throw new it(`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}}}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 Tr);return}if(this.lifecycle.onFirstReady(()=>{e()}),this.lifecycle.status==="idle"||this.lifecycle.status==="cleaned-up")try{this.startSync()}catch(n){t(n);return}}),this.preloadPromise)}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}trackLoadPromise(e){const 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(()=>{const n=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"})})}loadSubset(e){if(this.syncMode==="eager")return!0;if(this.syncLoadSubsetFn){const 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(),this.syncCleanupFn=null)}catch(e){queueMicrotask(()=>{if(e instanceof Error){const t=new Js(this.id,e);throw t.cause=e,t.stack=e.stack,t}else throw new Js(this.id,e)})}this.preloadPromise=null}}function Ta(s){if(typeof s=="function")return{cleanup:s};if(typeof s=="object")return s}function Ln(s){return typeof s=="function"&&s.prototype!==void 0&&s.prototype.constructor===s}async function Pa(s){return Ln(s)?s:await s()}class Da{constructor(e,t,n,r,i,o){this.id=e,this.expression=t,this.name=n,this.resolver=r,this.options=i,this.collectionEntries=o,this.indexPromise=null,this.resolvedIndex=null,Ln(this.resolver)&&(this.resolvedIndex=new this.resolver(this.id,this.expression,this.name,this.options),this.collectionEntries&&this.resolvedIndex.build(this.collectionEntries))}async resolve(){return this.resolvedIndex?this.resolvedIndex:(this.indexPromise||(this.indexPromise=this.createIndex()),this.resolvedIndex=await this.indexPromise,this.resolvedIndex)}isResolved(){return this.resolvedIndex!==null}getResolved(){if(!this.resolvedIndex)throw new Error(`Index ${this.id} has not been resolved yet. Ensure collection is synced.`);return this.resolvedIndex}getId(){return this.id}getName(){return this.name}getExpression(){return this.expression}async createIndex(){const e=await Pa(this.resolver);return new e(this.id,this.expression,this.name,this.options)}}class Ka{constructor(e,t){this.indexId=e,this.lazyIndex=t}get index(){return this.lazyIndex.getResolved()}get isReady(){return this.lazyIndex.isResolved()}async whenReady(){return await this.lazyIndex.resolve()}get id(){return this.indexId}get name(){return this.isReady?this.index.name:this.lazyIndex.getName()}get expression(){return this.lazyIndex.getExpression()}supports(e){return this.index.supports(e)}getStats(){return this.index.getStats()}matchesField(e){const t=this.expression;return t.type==="ref"&&t.path.length===e.length&&t.path.every((n,r)=>n===e[r])}get keyCount(){return this.index.keyCount}get indexedKeysSet(){return this.index.indexedKeysSet}get orderedEntriesArray(){return this.index.orderedEntriesArray}get valueMapData(){return this.index.valueMapData}equalityLookup(e){return this.index.equalityLookup?.(e)??new Set}rangeQuery(e){return this.index.rangeQuery?.(e)??new Set}inArrayLookup(e){return this.index.inArrayLookup?.(e)??new Set}_getLazyWrapper(){return this.lazyIndex}}class Fa{constructor(){this.lazyIndexes=new Map,this.resolvedIndexes=new Map,this.isIndexesResolved=!1,this.indexCounter=0}setDeps(e){this.state=e.state,this.lifecycle=e.lifecycle}createIndex(e,t={}){this.lifecycle.validateCollectionUsable("createIndex");const n=++this.indexCounter,r=Fn(),i=e(r),o=L(i),a=t.indexType??Zt,c=new Da(n,o,t.name,a,t.options,this.state.entries());if(this.lazyIndexes.set(n,c),a===Zt)try{const l=c.getResolved();this.resolvedIndexes.set(n,l)}catch(l){console.warn("Failed to resolve BTreeIndex:",l)}else if(typeof a=="function"&&a.prototype)try{const l=c.getResolved();this.resolvedIndexes.set(n,l)}catch{this.resolveSingleIndex(n,c).catch(l=>{console.warn("Failed to resolve single index:",l)})}else this.isIndexesResolved&&this.resolveSingleIndex(n,c).catch(l=>{console.warn("Failed to resolve single index:",l)});return new Ka(n,c)}async resolveAllIndexes(){if(this.isIndexesResolved)return;const e=Array.from(this.lazyIndexes.entries()).map(async([t,n])=>{const r=await n.resolve();return r.build(this.state.entries()),this.resolvedIndexes.set(t,r),{indexId:t,resolvedIndex:r}});await Promise.all(e),this.isIndexesResolved=!0}async resolveSingleIndex(e,t){const n=await t.resolve();return n.build(this.state.entries()),this.resolvedIndexes.set(e,n),n}get indexes(){return this.resolvedIndexes}updateIndexes(e){for(const t of this.resolvedIndexes.values())for(const 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.lazyIndexes.clear(),this.resolvedIndexes.clear()}}var ja={};const Ba=new Set(["find","findLast","findIndex","findLastIndex","filter","map","flatMap","forEach","some","every","reduce","reduceRight"]),La=new Set(["pop","push","shift","unshift","splice","sort","reverse","fill","copyWithin"]),za=new Set(["set","delete","clear","add"]),Na=new Set(["entries","keys","values","forEach"]);function Is(s){return s!==null&&typeof s=="object"&&!(s instanceof Date)&&!(s instanceof RegExp)&&!Ye(s)}function $a(s,e,t,n){if(Ba.has(s))return function(...r){const i=r[0];if(typeof i!="function")return e.apply(t.copy_,r);const o=(l,u)=>{if(Is(l)){const h={tracker:t,prop:String(u)},{proxy:y}=n(l,h);return y}return l},a=function(l,u,h){const y=o(l,u);return i.call(this,y,u,h)};if(s==="reduce"||s==="reduceRight"){const l=function(u,h,y,f){const d=o(h,y);return i.call(this,u,d,y,f)};return e.apply(t.copy_,[l,...r.slice(1)])}const c=e.apply(t.copy_,[a,...r.slice(1)]);if((s==="find"||s==="findLast")&&c&&typeof c=="object"){const l=t.copy_.indexOf(c);if(l!==-1)return o(c,l)}return s==="filter"&&Array.isArray(c)?c.map(l=>{const u=t.copy_.indexOf(l);return u!==-1?o(l,u):l}):c}}function Ua(s,e){return function(){const t=s.copy_;let n=0;return{next(){if(n>=t.length)return{done:!0,value:void 0};const r=t[n];let i=r;if(Is(r)){const o={tracker:s,prop:String(n)},{proxy:a}=e(r,o);i=a}return n++,{done:!1,value:i}},[Symbol.iterator](){return this}}}}function wn(s,e,t){return function(...n){const r=s.apply(e.copy_,n);return t(e),r}}function Va(s,e,t,n,r,i,o){if(Na.has(s)||e===Symbol.iterator)return function(...c){const l=t.apply(r.copy_,c);if(s==="forEach"){const h=c[0];if(typeof h=="function"){const y=function(f,d,p){const g=h.call(this,f,d,p);return o(r),g};return t.apply(n,[y,...c.slice(1)])}}if(s==="entries"||s==="values"||s===Symbol.iterator.toString()||e===Symbol.iterator){const h=l,y=new Map;if(s==="values"&&n instanceof Map)for(const[d,p]of r.copy_.entries())y.set(p,d);const f=new Map;if(n instanceof Set)for(const d of r.copy_.values())f.set(d,d);return{next(){const d=h.next();if(!d.done&&d.value&&typeof d.value=="object"){if(s==="entries"&&Array.isArray(d.value)&&d.value.length===2){if(d.value[1]&&typeof d.value[1]=="object"){const p=d.value[0],g={tracker:r,prop:p,updateMap:w=>{r.copy_ instanceof Map&&r.copy_.set(p,w)}},{proxy:m}=i(d.value[1],g);d.value[1]=m}}else if(s==="values"||s===Symbol.iterator.toString()||e===Symbol.iterator)if(s==="values"&&n instanceof Map){const p=y.get(d.value);if(p!==void 0){const g={tracker:r,prop:p,updateMap:w=>{r.copy_ instanceof Map&&r.copy_.set(p,w)}},{proxy:m}=i(d.value,g);d.value=m}}else if(n instanceof Set){const p=d.value,g={tracker:r,prop:p,updateSet:w=>{r.copy_ instanceof Set&&(r.copy_.delete(p),r.copy_.add(w),f.set(p,w))}},{proxy:m}=i(d.value,g);d.value=m}else{const p=Symbol("iterator-value"),{proxy:g}=i(d.value,{tracker:r,prop:p});d.value=g}}return d},[Symbol.iterator](){return this}}}return l}}function A(...s){const e=typeof window<"u"&&typeof localStorage<"u";e&&localStorage.getItem("DEBUG")==="true"?console.log("[proxy]",...s):!e&&typeof process<"u"&&ja.DEBUG==="true"&&console.log("[proxy]",...s)}function ge(s,e=new WeakMap){if(s==null||typeof s!="object")return s;if(e.has(s))return e.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(Array.isArray(s)){const r=[];return e.set(s,r),s.forEach((i,o)=>{r[o]=ge(i,e)}),r}if(ArrayBuffer.isView(s)&&!(s instanceof DataView)){const r=Object.getPrototypeOf(s).constructor,i=new r(s.length);e.set(s,i);for(let o=0;o<s.length;o++)i[o]=s[o];return i}if(s instanceof Map){const r=new Map;return e.set(s,r),s.forEach((i,o)=>{r.set(o,ge(i,e))}),r}if(s instanceof Set){const r=new Set;return e.set(s,r),s.forEach(i=>{r.add(ge(i,e))}),r}if(Ye(s))return s;const t={};e.set(s,t);for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t[r]=ge(s[r],e));const n=Object.getOwnPropertySymbols(s);for(const r of n)t[r]=ge(s[r],e);return t}let vn=0;function qa(){return vn+=1,vn}function Es(s,e){const t=new Map;function n(h,y){if(A("Object ID:",h.constructor.name),t.has(h))return t.get(h);{const f=Es(h,y);return t.set(h,f),f}}const r=new Map,i={copy_:ge(s),originalObject:ge(s),proxyCount:qa(),modified:!1,assigned_:{},parent:e,target:s};A("createChangeProxy called for target",s,i.proxyCount);function o(h){h.modified||(h.modified=!0),h.parent&&(A("propagating change to parent"),"updateMap"in h.parent?h.parent.updateMap(h.copy_):"updateSet"in h.parent?h.parent.updateSet(h.copy_):(h.parent.tracker.copy_[h.parent.prop]=h.copy_,h.parent.tracker.assigned_[h.parent.prop]=!0),o(h.parent.tracker))}function a(h){if(A("checkIfReverted called with assigned keys:",Object.keys(h.assigned_)),Object.keys(h.assigned_).length===0&&Object.getOwnPropertySymbols(h.assigned_).length===0)return A("No assigned properties, returning true"),!0;for(const f in h.assigned_)if(h.assigned_[f]===!0){const d=h.copy_[f],p=h.originalObject[f];if(A(`Checking property ${String(f)}, current:`,d,"original:",p),!le(d,p))return A(`Property ${String(f)} is different, returning false`),!1}else if(h.assigned_[f]===!1)return A(`Property ${String(f)} was deleted, returning false`),!1;const y=Object.getOwnPropertySymbols(h.assigned_);for(const f of y)if(h.assigned_[f]===!0){const d=h.copy_[f],p=h.originalObject[f];if(!le(d,p))return A("Symbol property is different, returning false"),!1}else if(h.assigned_[f]===!1)return A("Symbol property was deleted, returning false"),!1;return A("All properties match original values, returning true"),!0}function c(h,y){A("checkParentStatus called for child prop:",y);const f=a(h);A("Parent checkIfReverted returned:",f),f&&(A("Parent is fully reverted, clearing tracking"),h.modified=!1,h.assigned_={},h.parent&&(A("Continuing up the parent chain"),c(h.parent.tracker,h.parent.prop)))}function l(h){if(A("createObjectProxy",h),r.has(h))return A("proxyCache found match"),r.get(h);const y=new Proxy(h,{get(f,d){A("get",f,d);const p=i.copy_[d]??i.originalObject[d],g=i.originalObject[d];if(A("value (at top of proxy get)",p),Object.getOwnPropertyDescriptor(f,d)?.get)return p;if(typeof p=="function"){if(Array.isArray(f)){const w=d.toString();if(La.has(w))return wn(p,i,o);const S=$a(w,p,i,n);if(S)return S;if(d===Symbol.iterator)return Ua(i,n)}if(f instanceof Map||f instanceof Set){const w=d.toString();if(za.has(w))return wn(p,i,o);const S=Va(w,d,p,f,i,n,o);if(S)return S}return p.bind(f)}if(Is(p)){const w={tracker:i,prop:String(d)},{proxy:S}=n(g,w);return r.set(p,S),S}return p},set(f,d,p){const g=i.copy_[d];if(A(`set called for property ${String(d)}, current:`,g,"new:",p),le(g,p))A("Value unchanged, not tracking");else{const m=i.originalObject[d],w=le(p,m);if(A("value:",p,"original:",m,"isRevertToOriginal:",w),w){A(`Reverting property ${String(d)} to original value`),delete i.assigned_[d.toString()],A(`Updating copy with original value for ${String(d)}`),i.copy_[d]=ge(m),A("Checking if all properties reverted");const S=a(i);A("All reverted:",S),S?(A("All properties reverted, clearing tracking"),i.modified=!1,i.assigned_={},e&&(A("Updating parent for property:",e.prop),c(e.tracker,e.prop))):(A("Some properties still changed, keeping modified flag"),i.modified=!0)}else A(`Setting new value for property ${String(d)}`),i.copy_[d]=p,i.assigned_[d.toString()]=!0,A("Marking object and ancestors as modified",i),o(i)}return!0},defineProperty(f,d,p){const g=Reflect.defineProperty(f,d,p);return g&&"value"in p&&(i.copy_[d]=ge(p.value),i.assigned_[d.toString()]=!0,o(i)),g},getOwnPropertyDescriptor(f,d){return Reflect.getOwnPropertyDescriptor(f,d)},preventExtensions(f){return Reflect.preventExtensions(f)},isExtensible(f){return Reflect.isExtensible(f)},deleteProperty(f,d){A("deleteProperty",f,d);const p=typeof d=="symbol"?d.toString():d;if(p in f){const g=p in i.originalObject,m=Reflect.deleteProperty(f,d);return m&&(g?(i.assigned_[p]=!1,o(i)):(delete i.assigned_[p],Object.keys(i.assigned_).length===0&&Object.getOwnPropertySymbols(i.assigned_).length===0?i.modified=!1:i.modified=!0)),m}return!0}});return r.set(h,y),y}return{proxy:l(i.copy_),getChanges:()=>{if(A("getChanges called, modified:",i.modified),A(i),!i.modified)return A("Object not modified, returning empty object"),{};if(typeof i.copy_!="object"||Array.isArray(i.copy_)||Object.keys(i.assigned_).length===0)return i.copy_;const h={};for(const y in i.copy_)i.assigned_[y]===!0&&y in i.copy_&&(h[y]=i.copy_[y]);return A("Returning copy:",h),h}}}function Wa(s){const e=s.map(t=>Es(t));return{proxies:e.map(t=>t.proxy),getChanges:()=>e.map(t=>t.getChanges())}}function Ga(s,e){const{proxy:t,getChanges:n}=Es(s);return e(t),n()}function Ha(s,e){const{proxies:t,getChanges:n}=Wa(s);return e(t),n()}function Qa(){let s,e,t=!0;return{promise:new Promise((r,i)=>{s=o=>{t=!1,r(o)},e=o=>{t=!1,i(o)}}),resolve:s,reject:e,isPending:()=>t}}function Ja(s){return typeof s=="object"&&s!==null&&typeof s.hasPendingGraphRun=="function"}class Ya{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(typeof e>"u"){r();return}const i=this.getOrCreateContext(e);if(i.jobs.has(t)||i.queue.push(t),i.jobs.set(t,r),n){const o=new Set(n);o.delete(t),i.dependencies.set(t,o)}else i.dependencies.has(t)||i.dependencies.set(t,new Set);i.completed.delete(t)}flush(e){const t=this.contexts.get(e);if(!t)return;const{queue:n,jobs:r,dependencies:i,completed:o}=t;for(;n.length>0;){let a=!1;const c=n.length;for(let l=0;l<c;l++){const u=n.shift(),h=r.get(u);if(!h){i.delete(u),o.delete(u);continue}const y=i.get(u);let f=!y;if(y){f=!0;for(const d of y){if(d===u)continue;const p=Ja(d)&&d.hasPendingGraphRun(e);if(r.has(d)&&!o.has(d)||!r.has(d)&&p){f=!1;break}}}f?(r.delete(u),i.delete(u),h(),o.add(u),a=!0):n.push(u)}if(!a)throw new Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}flushAll(){for(const 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){const t=this.contexts.get(e);return!!t&&t.jobs.size>0}clearJob(e,t){const n=this.contexts.get(e);n&&(n.jobs.delete(t),n.dependencies.delete(t),n.completed.delete(t),n.queue=n.queue.filter(r=>r!==t),n.jobs.size===0&&this.contexts.delete(e))}}const It=new Ya,Et=[];let rt=[],Za=0;function Xa(s,e){switch(`${s.type}-${e.type}`){case"insert-update":return{...s,type:"insert",original:{},modified:e.modified,changes:{...s.changes,...e.changes},key:s.key,globalKey:s.globalKey,metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata},mutationId:e.mutationId,updatedAt:e.updatedAt};case"insert-delete":return null;case"update-delete":return e;case"update-update":return{...e,original:s.original,changes:{...s.changes,...e.changes},metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata}};case"delete-delete":case"insert-insert":return e;default:{const t=`${s.type}-${e.type}`;throw new Error(`Unhandled mutation combination: ${t}`)}}}function gt(s){const e=new nc(s);return Et.push(e),e}function vt(){if(rt.length>0)return rt.slice(-1)[0]}function ec(s){It.clear(s.id),rt.push(s)}function tc(s){try{It.flush(s.id)}finally{rt=rt.filter(e=>e.id!==s.id)}}function sc(s){const e=Et.findIndex(t=>t.id===s.id);e!==-1&&Et.splice(e,1)}class nc{constructor(e){if(typeof e.mutationFn>"u")throw new Gr;this.id=e.id??crypto.randomUUID(),this.mutationFn=e.mutationFn,this.state="pending",this.mutations=[],this.isPersisted=Qa(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=Za++,this.metadata=e.metadata??{}}setState(e){this.state=e,(e==="completed"||e==="failed")&&sc(this)}mutate(e){if(this.state!=="pending")throw new Hr;ec(this);try{e()}finally{tc(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){for(const t of e){const n=this.mutations.findIndex(r=>r.globalKey===t.globalKey);if(n>=0){const r=this.mutations[n],i=Xa(r,t);i===null?this.mutations.splice(n,1):this.mutations[n]=i}else this.mutations.push(t)}}rollback(e){const t=e?.isSecondaryRollback??!1;if(this.state==="completed")throw new Qr;if(this.setState("failed"),!t){const n=new Set;this.mutations.forEach(r=>n.add(r.globalKey));for(const r of Et)r.state==="pending"&&r.mutations.some(i=>n.has(i.globalKey))&&r.rollback({isSecondaryRollback:!0})}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){const e=new Set;for(const 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 Jr;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){const t=e instanceof Error?e:new Error(String(e));throw this.error={message:t.message,error:t},this.rollback(),t}return this}compareCreatedAt(e){const t=this.createdAt.getTime()-e.createdAt.getTime();return t!==0?t:this.sequenceNumber-e.sequenceNumber}}class rc{constructor(e,t){this.insert=(n,r)=>{this.lifecycle.validateCollectionUsable("insert");const i=this.state,o=vt();if(!o&&!this.config.onInsert)throw new Vr;const a=Array.isArray(n)?n:[n],c=[],l=new Set;if(a.forEach(u=>{const h=this.validateData(u,"insert"),y=this.config.getKey(h);if(this.state.has(y)||l.has(y))throw new Fr(y);l.add(y);const f=this.generateGlobalKey(y,u),d={mutationId:crypto.randomUUID(),original:{},modified:h,changes:Object.fromEntries(Object.keys(u).map(p=>[p,h[p]])),globalKey:f,key:y,metadata:r?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:r?.optimistic??!0,type:"insert",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(d)}),o)return o.applyMutations(c),i.transactions.set(o.id,o),i.scheduleTransactionCleanup(o),i.recomputeOptimisticState(!0),o;{const u=gt({mutationFn:async h=>await this.config.onInsert({transaction:h.transaction,collection:this.collection})});return u.applyMutations(c),u.commit().catch(()=>{}),i.transactions.set(u.id,u),i.scheduleTransactionCleanup(u),i.recomputeOptimisticState(!0),u}},this.delete=(n,r)=>{const i=this.state;this.lifecycle.validateCollectionUsable("delete");const o=vt();if(!o&&!this.config.onDelete)throw new Wr;if(Array.isArray(n)&&n.length===0)throw new $r;const a=Array.isArray(n)?n:[n],c=[];for(const u of a){if(!this.state.has(u))throw new Ur(u);const h=this.generateGlobalKey(u,this.state.get(u)),y={mutationId:crypto.randomUUID(),original:this.state.get(u),modified:this.state.get(u),changes:this.state.get(u),globalKey:h,key:u,metadata:r?.metadata,syncMetadata:i.syncedMetadata.get(u)||{},optimistic:r?.optimistic??!0,type:"delete",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(y)}if(o)return o.applyMutations(c),i.transactions.set(o.id,o),i.scheduleTransactionCleanup(o),i.recomputeOptimisticState(!0),o;const l=gt({autoCommit:!0,mutationFn:async u=>this.config.onDelete({transaction:u.transaction,collection:this.collection})});return l.applyMutations(c),l.commit().catch(()=>{}),i.transactions.set(l.id,l),i.scheduleTransactionCleanup(l),i.recomputeOptimisticState(!0),l},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 _r}validateData(e,t,n){if(!this.config.schema)return e;const r=this.ensureStandardSchema(this.config.schema);if(t==="update"&&n){const o=this.state.get(n);if(o&&e&&typeof e=="object"&&typeof o=="object"){const a=Object.assign({},o,e),c=r["~standard"].validate(a);if(c instanceof Promise)throw new qs;if("issues"in c&&c.issues){const y=c.issues.map(f=>({message:f.message,path:f.path?.map(d=>String(d))}));throw new Vs(t,y)}const l=c.value,u=Object.keys(e);return Object.fromEntries(u.map(y=>[y,l[y]]))}}const i=r["~standard"].validate(e);if(i instanceof Promise)throw new qs;if("issues"in i&&i.issues){const o=i.issues.map(a=>({message:a.message,path:a.path?.map(c=>String(c))}));throw new Vs(t,o)}return i.value}generateGlobalKey(e,t){if(typeof e!="string"&&typeof e!="number")throw typeof e>"u"?new Dr(t):new Kr(e,t);return`KEY::${this.id}/${e}`}update(e,t,n){if(typeof e>"u")throw new Br;const r=this.state;this.lifecycle.validateCollectionUsable("update");const i=vt();if(!i&&!this.config.onUpdate)throw new qr;const o=Array.isArray(e),a=o?e:[e];if(o&&a.length===0)throw new Lr;const c=typeof t=="function"?t:n,l=typeof t=="function"?{}:t,u=a.map(d=>{const p=this.state.get(d);if(!p)throw new zr(d);return p});let h;o?h=Ha(u,c):h=[Ga(u[0],c)];const y=a.map((d,p)=>{const g=h[p];if(!g||Object.keys(g).length===0)return null;const m=u[p],w=this.validateData(g,"update",d),S=Object.assign({},m,w),b=this.config.getKey(m),k=this.config.getKey(S);if(b!==k)throw new Nr(b,k);const _=this.generateGlobalKey(k,S);return{mutationId:crypto.randomUUID(),original:m,modified:S,changes:Object.fromEntries(Object.keys(g).map(D=>[D,S[D]])),globalKey:_,key:d,metadata:l.metadata,syncMetadata:r.syncedMetadata.get(d)||{},optimistic:l.optimistic??!0,type:"update",createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(y.length===0){const d=gt({mutationFn:async()=>{}});return d.commit().catch(()=>{}),r.scheduleTransactionCleanup(d),d}if(i)return i.applyMutations(y),r.transactions.set(i.id,i),r.scheduleTransactionCleanup(i),r.recomputeOptimisticState(!0),i;const f=gt({mutationFn:async d=>this.config.onUpdate({transaction:d.transaction,collection:this.collection})});return f.applyMutations(y),f.commit().catch(()=>{}),r.transactions.set(f.id,f),r.scheduleTransactionCleanup(f),r.recomputeOptimisticState(!0),f}}class ic extends Bn{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});const 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})}cleanup(){this.clearListeners()}}function Rs(s){const e=new ks(s);return s.utils?e.utils=s.utils:e.utils={},e}class ks{constructor(e){if(this.utils={},this.insert=(t,n)=>this._mutations.insert(t,n),this.delete=(t,n)=>this._mutations.delete(t,n),!e)throw new kr;if(!e.sync)throw new Or;e.id?this.id=e.id:this.id=crypto.randomUUID(),this.config={...e,autoIndex:e.autoIndex??"eager"},this._changes=new Ra,this._events=new ic,this._indexes=new Fa,this._lifecycle=new Aa(e,this.id),this._mutations=new rc(e,this.id),this._state=new Ca(e),this._sync=new Ma(e,this.id),this.comparisonOpts=oc(e),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle}),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.get(e)}has(e){return this._state.has(e)}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){yield*this._state.values()}*entries(){yield*this._state.entries()}*[Symbol.iterator](){yield*this._state[Symbol.iterator]()}forEach(e){return this._state.forEach(e)}map(e){return this._state.map(e)}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,t={}){return this._indexes.createIndex(e,t)}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(){const e=new Map;for(const[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 ba(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 oc(s){if(s.defaultStringCollation){const e=s.defaultStringCollation;return{stringSort:e.stringSort??"locale",locale:e.stringSort==="locale"?e.locale:void 0,localeOptions:e.stringSort==="locale"?e.localeOptions:void 0}}else return{stringSort:"locale"}}class ${constructor(e={}){this.query={},this.query={...e}}_createRefForSource(e,t){let n;try{n=Object.keys(e)}catch{const a=e===null?"null":"undefined";throw new pt(t,a)}if(Array.isArray(e))throw new pt(t,"array");if(n.length!==1)throw n.length===0?new pt(t,"empty object"):n.every(a=>!isNaN(Number(a)))?new pt(t,"string"):new Xr(t);const r=n[0],i=e[r];let o;if(i instanceof ks)o=new Ke(i,r);else if(i instanceof $){const a=i._getQuery();if(!a.from)throw new ei(t);o=new oe(a,r)}else throw new ti(r);return[r,o]}from(e){const[,t]=this._createRefForSource(e,"from clause");return new $({...this.query,from:t})}join(e,t,n="left"){const[r,i]=this._createRefForSource(e,"join clause"),a=[...this._getCurrentAliases(),r],c=ke(a),l=t(c);let u,h;if(l.type==="func"&&l.name==="eq"&&l.args.length===2)u=l.args[0],h=l.args[1];else throw new si;const y={from:i,type:n,left:u,right:h},f=this.query.join||[];return new $({...this.query,join:[...f,y]})}leftJoin(e,t){return this.join(e,t,"left")}rightJoin(e,t){return this.join(e,t,"right")}innerJoin(e,t){return this.join(e,t,"inner")}fullJoin(e,t){return this.join(e,t,"full")}where(e){const t=this._getCurrentAliases(),n=ke(t),r=e(n);if(!et(r))throw new Hs(bn(r));const i=this.query.where||[];return new $({...this.query,where:[...i,r]})}having(e){const t=this._getCurrentAliases(),n=this.query.select||this.query.fnSelect?dn(t):ke(t),r=e(n);if(!et(r))throw new Hs(bn(r));const i=this.query.having||[];return new $({...this.query,having:[...i,r]})}select(e){const t=this._getCurrentAliases(),n=ke(t),r=e(n),i=zn(r);return new $({...this.query,select:i,fnSelect:void 0})}orderBy(e,t="asc"){const n=this._getCurrentAliases(),r=this.query.select||this.query.fnSelect?dn(n):ke(n),i=e(r),o=typeof t=="string"?{direction:t,nulls:"first"}:{direction:t.direction??"asc",nulls:t.nulls??"first",stringSort:t.stringSort,locale:t.stringSort==="locale"?t.locale:void 0,localeOptions:t.stringSort==="locale"?t.localeOptions:void 0},a=u=>({expression:L(u),compareOptions:o}),c=Array.isArray(i)?i.map(u=>a(u)):[a(i)],l=this.query.orderBy||[];return new $({...this.query,orderBy:[...l,...c]})}groupBy(e){const t=this._getCurrentAliases(),n=ke(t),r=e(n),i=Array.isArray(r)?r.map(a=>L(a)):[L(r)],o=this.query.groupBy||[];return new $({...this.query,groupBy:[...o,...i]})}limit(e){return new $({...this.query,limit:e})}offset(e){return new $({...this.query,offset:e})}distinct(){return new $({...this.query,distinct:!0})}findOne(){return new $({...this.query,singleResult:!0})}_getCurrentAliases(){const e=[];if(this.query.from&&e.push(this.query.from.alias),this.query.join)for(const t of this.query.join)e.push(t.from.alias);return e}get fn(){const e=this;return{select(t){return new $({...e.query,select:void 0,fnSelect:t})},where(t){return new $({...e.query,fnWhere:[...e.query.fnWhere||[],t]})},having(t){return new $({...e.query,fnHaving:[...e.query.fnHaving||[],t]})}}}_getQuery(){if(!this.query.from)throw new ni;return this.query}}function bn(s){return s===null?"null":s===void 0?"undefined":typeof s=="object"?"object":typeof s}function ac(s){return s===void 0?L(null):s instanceof kn||s instanceof se||s instanceof Y||s instanceof X?s:L(s)}function cc(s){return s!==null&&typeof s=="object"&&!et(s)&&!s.__refProxy}function zn(s){if(!cc(s))return ac(s);const e={};for(const[t,n]of Object.entries(s)){if(typeof t=="string"&&t.startsWith("__SPREAD_SENTINEL__")){e[t]=n;continue}e[t]=zn(n)}return e}function lc(s){const e=s(new $);return Nn(e)}function Nn(s){return s._getQuery()}function uc(s){const e=hc(s);let t=s,n,r=0;const i=10;for(;r<i&&!le(t,n);)n=t,t=es(t),r++;return{optimizedQuery:$n(t),sourceWhereClauses:e}}function hc(s){const e=new Map;if(!s.where||s.where.length===0)return e;const n=ss(s.where).map(i=>Un(i)),r=Vn(n);for(const[i,o]of r.singleSource)dc(s,i)&&e.set(i,o);return e}function dc(s,e){if(s.from.alias===e)return s.from.type==="collectionRef";if(s.join){for(const t of s.join)if(t.from.alias===e)return t.from.type==="collectionRef"}return!1}function es(s){const e={...s,from:s.from.type==="queryRef"?new oe(es(s.from.query),s.from.alias):s.from,join:s.join?.map(t=>({...t,from:t.from.type==="queryRef"?new oe(es(t.from.query),t.from.alias):t.from}))};return fc(e)}function fc(s){if(!s.where||s.where.length===0)return s;if(!s.join||s.join.length===0){if(s.where.length>1){const a=ss(s.where),c=Rt(a);return{...s,where:[c]}}return s}const e=s.where.filter(a=>!Us(a)),n=ss(e).map(a=>Un(a)),r=Vn(n),i=yc(s,r),o=s.where.filter(a=>Us(a));return o.length>0&&(i.where=[...i.where||[],...o]),i}function $n(s){return{...s,from:ts(s.from),join:s.join?.map(e=>({...e,from:ts(e.from)}))}}function ts(s){if(s.type==="collectionRef")return s;const e=$n(s.query);if(pc(e)){const t=ts(e.from);return t.type==="collectionRef"?new Ke(t.collection,s.alias):new oe(t.query,s.alias)}return new oe(e,s.alias)}function pc(s){return(!s.where||s.where.length===0)&&!s.select&&(!s.groupBy||s.groupBy.length===0)&&(!s.having||s.having.length===0)&&(!s.orderBy||s.orderBy.length===0)&&(!s.join||s.join.length===0)&&s.limit===void 0&&s.offset===void 0&&!s.fnSelect&&(!s.fnWhere||s.fnWhere.length===0)&&(!s.fnHaving||s.fnHaving.length===0)}function ss(s){const e=[];for(const t of s){const n=fs(t);e.push(...Os(n))}return e}function Os(s){if(s.type==="func"&&s.name==="and"){const e=[];for(const t of s.args)e.push(...Os(t));return e}else return[s]}function Un(s){const e=new Set;let t=!1;function n(r){switch(r.type){case"ref":if(r.path&&r.path.length>0){const i=r.path[0];i&&(e.add(i),r.path.length===1&&(t=!0))}break;case"func":r.args&&r.args.forEach(n);break;case"val":break;case"agg":r.args&&r.args.forEach(n);break}}return n(s),{expression:s,touchedSources:e,hasNamespaceOnlyRef:t}}function Vn(s){const e=new Map,t=[];for(const i of s)if(i.touchedSources.size===1&&!i.hasNamespaceOnlyRef){const o=Array.from(i.touchedSources)[0];e.has(o)||e.set(o,[]),e.get(o).push(i.expression)}else(i.touchedSources.size>1||i.hasNamespaceOnlyRef)&&t.push(i.expression);const n=new Map;for(const[i,o]of e)n.set(i,Rt(o));const r=t.length>0?Rt(t):void 0;return{singleSource:n,multiSource:r}}function yc(s,e){const t=new Set,n=Sn(s.from,e.singleSource,t),r=s.join?s.join.map(l=>({...l,from:Sn(l.from,e.singleSource,t)})):void 0,i=[];e.multiSource&&i.push(e.multiSource);const o=s.join&&s.join.some(l=>l.type==="left"||l.type==="right"||l.type==="full");for(const[l,u]of e.singleSource)t.has(l)?o&&i.push(Er(u)):i.push(u);const a=i.length>1?[Rt(i.flatMap(l=>Os(fs(l))))]:i;return{select:s.select,groupBy:s.groupBy?[...s.groupBy]:void 0,having:s.having?[...s.having]:void 0,orderBy:s.orderBy?[...s.orderBy]:void 0,limit:s.limit,offset:s.offset,distinct:s.distinct,fnSelect:s.fnSelect,fnWhere:s.fnWhere?[...s.fnWhere]:void 0,fnHaving:s.fnHaving?[...s.fnHaving]:void 0,from:n,join:r,where:a.length>0?a:[]}}function Pe(s){return{from:s.from.type==="collectionRef"?new Ke(s.from.collection,s.from.alias):new oe(Pe(s.from.query),s.from.alias),select:s.select,join:s.join?s.join.map(e=>({type:e.type,left:e.left,right:e.right,from:e.from.type==="collectionRef"?new Ke(e.from.collection,e.from.alias):new oe(Pe(e.from.query),e.from.alias)})):void 0,where:s.where?[...s.where]:void 0,groupBy:s.groupBy?[...s.groupBy]:void 0,having:s.having?[...s.having]:void 0,orderBy:s.orderBy?[...s.orderBy]:void 0,limit:s.limit,offset:s.offset,fnSelect:s.fnSelect,fnWhere:s.fnWhere?[...s.fnWhere]:void 0,fnHaving:s.fnHaving?[...s.fnHaving]:void 0}}function Sn(s,e,t){const n=e.get(s.alias);if(!n)return s.type==="collectionRef"?new Ke(s.collection,s.alias):new oe(Pe(s.query),s.alias);if(s.type==="collectionRef"){const o={from:new Ke(s.collection,s.alias),where:[n]};return t.add(s.alias),new oe(o,s.alias)}if(!Sc(s.query,n,s.alias))return new oe(Pe(s.query),s.alias);if(Cc(s.query,n,s.alias))return new oe(Pe(s.query),s.alias);const r=s.query.where||[],i={...Pe(s.query),where:[...r,n]};return t.add(s.alias),new oe(i,s.alias)}function gc(s,e,t){return s.select?qn(s.select)||xc(s.select,e,t):!1}function mc(s){return s.groupBy&&s.groupBy.length>0}function wc(s){return s.having&&s.having.length>0}function vc(s){return s.orderBy&&s.orderBy.length>0&&(s.limit!==void 0||s.offset!==void 0)}function bc(s){return s.fnSelect||s.fnWhere&&s.fnWhere.length>0||s.fnHaving&&s.fnHaving.length>0}function Sc(s,e,t){return!(gc(s,e,t)||mc(s)||wc(s)||vc(s)||bc(s))}function qn(s){for(const e of Object.values(s))if(typeof e=="object"){const t=e;if(t.type==="agg"||!("type"in t)&&qn(t))return!0}return!1}function _s(s){const e=[];if(s==null||typeof s!="object")return e;switch(s.type){case"ref":e.push(s);break;case"func":case"agg":for(const t of s.args??[])e.push(..._s(t));break}return e}function xc(s,e,t){const n=new Set;for(const[i,o]of Object.entries(s))i.startsWith("__SPREAD_SENTINEL__")||o instanceof Y||n.add(i);const r=_s(e);for(const i of r){const o=i.path;if(!Array.isArray(o)||o.length<2)continue;const a=o[0],c=o[1];if(a===t&&n.has(c))return!0}return!1}function Cc(s,e,t){const n=_s(e);if(n.every(i=>i.path[0]!==t))return!1;if(s.fnSelect)return!0;const r=s.select;if(!r)return!1;for(const i of n){const o=i.path;if(o.length<2||o[0]!==t)continue;const a=r[o[1]];if(!a)continue;if(!(a instanceof Y)||a.path.length<2)return!0;const[c,l]=a.path;if(c!==t&&c!==s.from.alias||l!==o[1])return!0}return!1}function Rt(s){if(s.length===0)throw new Ii;return s.length===1?s[0]:new se("and",s)}function Ic(s,e,t,n,r,i,o,a,c,l,u,h,y,f,d,p,g,m,w){let S=s;for(const b of e)S=Ec(S,b,t,n,r,i,o,a,c,l,u,h,y,f,d,p,g,m,w);return S}function Ec(s,e,t,n,r,i,o,a,c,l,u,h,y,f,d,p,g,m,w){const S=e.from.type==="collectionRef",{alias:b,input:k,collectionId:_}=kc(e.from,i,c,l,u,h,y,f,o,a,p,g,m,w);t[b]=k,S&&(g[b]=_);const D=c[n],I=c[_];if(!D)throw new Qs(n);if(!I)throw new Qs(_);const{activeSource:v,lazySource:x}=_c(e.type,D,I),M=Object.keys(t),{mainExpr:K,joinedExpr:B}=Rc(e.left,e.right,M,b),Be=ee(K),Le=ee(B);let Ie=s.pipe(J(([pe,me])=>[Be(me),[pe,me]])),ze=k.pipe(J(([pe,me])=>{const T={[b]:me};return[Le(T),[pe,T]]}));if(!["inner","left","right","full"].includes(e.type))throw new di(e.type);if(v){const pe=v==="main"?e.from:d.from,me=pe.type==="queryRef"&&(pe.query.limit||pe.query.offset),T=K.type==="func"||B.type==="func";if(!me&&!T){const O=v==="main"?b:r;h.add(O);const E=v==="main"?Ie:ze,q=tt(d,v==="main"?B:K,x),ue=q.collection,Ae=q.path[0];Ae&&_t(Ae,q.path,ue);const Ne=E.pipe(Fo(ct=>{const $e=m[O]||O,Me=l[$e];if(!Me)throw new Ei($e,O,x.id,Object.keys(l));if(Me.hasLoadedInitialState())return;const Ue=ct.getInner().map(([[Mt]])=>Mt),lt=new Y(q.path);Me.requestSnapshot({where:ca(lt,Ue),optimizedOnly:!0})||Me.requestSnapshot()}));v==="main"?Ie=Ne:ze=Ne}}return Ie.pipe(Uo(ze,e.type),Oc(e.type))}function Rc(s,e,t,n){const r=t.filter(a=>a!==n),i=ns(s),o=ns(e);if(i&&r.includes(i)&&o===n)return{mainExpr:s,joinedExpr:e};if(i===n&&o&&r.includes(o))return{mainExpr:e,joinedExpr:s};throw!i||!o?new pi:i===o?new fi(i):r.includes(i)?o!==n?new gi(n):new mi:new yi(i)}function ns(s){switch(s.type){case"ref":return s.path[0]||null;case"func":{const e=new Set;for(const t of s.args){const n=ns(t);n&&e.add(n)}return e.size===1?Array.from(e)[0]:null}default:return null}}function kc(s,e,t,n,r,i,o,a,c,l,u,h,y,f){switch(s.type){case"collectionRef":{const d=e[s.alias];if(!d)throw new On(s.alias,s.collection.id,Object.keys(e));return h[s.alias]=s.collection.id,{alias:s.alias,input:d,collectionId:s.collection.id}}case"queryRef":{const d=l.get(s.query)||s.query,p=u(d,e,t,n,r,i,o,a,c,l);Object.assign(h,p.aliasToCollectionId),Object.assign(y,p.aliasRemapping);const g=l.has(s.query),m=s.query.from.alias;if(!(!g&&s.alias===m))for(const[_,D]of p.sourceWhereClauses)f.set(_,D);const S=Object.keys(p.aliasToCollectionId).find(_=>p.aliasToCollectionId[_]===p.collectionId);S&&S!==s.alias&&(y[s.alias]=S);const k=p.pipeline.pipe(J(_=>{const[D,[I,v]]=_;return[D,I]}));return{alias:s.alias,input:k,collectionId:p.collectionId}}default:throw new wi(s.type)}}function Oc(s){return function(e){return e.pipe(Se(t=>{const[n,[r,i]]=t,o=r?.[1],a=i?.[1];return s==="inner"?!!(o&&a):s==="left"?!!o:s==="right"?!!a:!0}),J(t=>{const[n,[r,i]]=t,o=r?.[0],a=r?.[1],c=i?.[0],l=i?.[1],u={};return a&&Object.assign(u,a),l&&Object.assign(u,l),[`[${o},${c}]`,u]}))}}function _c(s,e,t){switch(s){case"left":return{activeSource:"main",lazySource:t};case"right":return{activeSource:"joined",lazySource:e};case"inner":return e.size<t.size?{activeSource:"main",lazySource:t}:{activeSource:"joined",lazySource:e};default:return{activeSource:void 0,lazySource:void 0}}}function rs(s){return s instanceof X?s.value:s}function Ac(s,e,t){const n=s.source(e);if(n&&typeof n=="object"){let r=t;const i=s.targetPath;if(i.length===0)for(const[o,a]of Object.entries(n))t[o]=rs(a);else for(let o=0;o<i.length;o++){const a=i[o];if(o===i.length-1){const c=r[a]??={};if(typeof c=="object")for(const[l,u]of Object.entries(n))c[l]=rs(u)}else{const c=r[a];(c==null||typeof c!="object")&&(r[a]={}),r=r[a]}}}}function Mc(s,e,t){const n=s.alias.split(".");if(n.length===1)t[s.alias]=s.compiled(e);else{let r=t;for(let i=0;i<n.length-1;i++){const o=n[i],a=r[o];(a==null||typeof a!="object")&&(r[o]={}),r=r[o]}r[n[n.length-1]]=rs(s.compiled(e))}}function Tc([s,e],t){const n={};for(const r of t)r.kind==="merge"?Ac(r,e,n):Mc(r,e,n);return[s,{...e,$selected:n}]}function Pc(s,e,t){const n=[];return Wn([],e,n),s.pipe(J(r=>Tc(r,n)))}function Dc(s){return s.type==="agg"}function Kc(s){return s&&typeof s=="object"&&!et(s)}function Wn(s,e,t){for(const[n,r]of Object.entries(e)){if(n.startsWith("__SPREAD_SENTINEL__")){const o=n.slice(19),a=o.lastIndexOf("__"),c=a>=0?o.slice(0,a):o,l=r&&typeof r=="object"&&"type"in r&&r.type==="ref";if(c.includes(".")||l){const u=[...s],h=l?r:new Y(c.split(".")),y=ee(h);t.push({kind:"merge",targetPath:u,source:y})}else{const u=c,h=[...s];t.push({kind:"merge",targetPath:h,source:y=>y[u]})}continue}const i=r;if(Kc(i)){Wn([...s,n],i,t);continue}if(Dc(i))t.push({kind:"field",alias:[...s,n].join("."),compiled:()=>null});else{if(i===void 0||!et(i)){t.push({kind:"field",alias:[...s,n].join("."),compiled:()=>i});continue}if(i instanceof X){const o=i.value;t.push({kind:"field",alias:[...s,n].join("."),compiled:()=>o})}else t.push({kind:"field",alias:[...s,n].join("."),compiled:ee(i)})}}}function As(s,e,t,n,r,i,o,a,c=new WeakMap,l=new WeakMap){const u=c.get(s);if(u)return u;is(s);const{optimizedQuery:h,sourceWhereClauses:y}=uc(s);l.set(h,s),as(h,s,l);const f={...e},d={},p={},g={},{alias:m,input:w,collectionId:S}=jc(h.from,f,t,n,r,i,o,a,c,l,d,p,y);g[m]=w;let b=w.pipe(J(([I,v])=>[I,{[m]:v}]));if(h.join&&h.join.length>0&&(b=Ic(b,h.join,g,S,m,f,c,l,t,n,r,i,o,a,s,As,d,p,y)),h.where&&h.where.length>0)for(const I of h.where){const v=fs(I),x=ee(v);b=b.pipe(Se(([M,K])=>De(x(K))))}if(h.fnWhere&&h.fnWhere.length>0)for(const I of h.fnWhere)b=b.pipe(Se(([v,x])=>De(I(x))));if(h.distinct&&!h.fnSelect&&!h.select)throw new ri;if(h.fnSelect?b=b.pipe(J(([I,v])=>{const x=h.fnSelect(v);return[I,{...v,$selected:x}]})):h.select?b=Pc(b,h.select):b=b.pipe(J(([I,v])=>{const x=!h.join&&!h.groupBy?v[m]:v;return[I,{...v,$selected:x}]})),h.groupBy&&h.groupBy.length>0?b=pn(b,h.groupBy,h.having,h.select,h.fnHaving):h.select&&Object.values(h.select).some(v=>v.type==="agg")&&(b=pn(b,[],h.having,h.select,h.fnHaving)),h.having&&(!h.groupBy||h.groupBy.length===0)&&!(h.select?Object.values(h.select).some(v=>v.type==="agg"):!1))throw new ii;if(h.fnHaving&&h.fnHaving.length>0&&(!h.groupBy||h.groupBy.length===0))for(const I of h.fnHaving)b=b.pipe(Se(([v,x])=>I(x)));if(h.distinct&&(b=b.pipe(qo(([I,v])=>v.$selected))),h.orderBy&&h.orderBy.length>0){const x=va(s,b,h.orderBy,h.select||{},t[S],o,a,h.limit,h.offset).pipe(J(([K,[B,Be]])=>{const Le=B.$selected,Ie=os(Le);return[K,[Ie,Be]]})),M={collectionId:S,pipeline:x,sourceWhereClauses:y,aliasToCollectionId:d,aliasRemapping:p};return c.set(s,M),M}else if(h.limit!==void 0||h.offset!==void 0)throw new oi;const _=b.pipe(J(([I,v])=>{const x=v.$selected,M=os(x);return[I,[M,void 0]]})),D={collectionId:S,pipeline:_,sourceWhereClauses:y,aliasToCollectionId:d,aliasRemapping:p};return c.set(s,D),D}function Fc(s){const e=new Set;if(s.from.type==="collectionRef"&&e.add(s.from.alias),s.join)for(const t of s.join)t.from.type==="collectionRef"&&e.add(t.from.alias);return e}function is(s,e=new Set){const t=Fc(s);for(const r of t)if(e.has(r))throw new ai(r,Array.from(e));const n=new Set([...e,...t]);if(s.from.type==="queryRef"&&is(s.from.query,n),s.join)for(const r of s.join)r.from.type==="queryRef"&&is(r.from.query,n)}function jc(s,e,t,n,r,i,o,a,c,l,u,h,y){switch(s.type){case"collectionRef":{const f=e[s.alias];if(!f)throw new On(s.alias,s.collection.id,Object.keys(e));return u[s.alias]=s.collection.id,{alias:s.alias,input:f,collectionId:s.collection.id}}case"queryRef":{const f=l.get(s.query)||s.query,d=As(f,e,t,n,r,i,o,a,c,l);Object.assign(u,d.aliasToCollectionId),Object.assign(h,d.aliasRemapping);const p=l.has(s.query),g=s.query.from.alias;if(!(!p&&s.alias===g))for(const[k,_]of d.sourceWhereClauses)y.set(k,_);const w=Object.keys(d.aliasToCollectionId).find(k=>d.aliasToCollectionId[k]===d.collectionId);w&&w!==s.alias&&(h[s.alias]=w);const b=d.pipeline.pipe(J(k=>{const[_,[D,I]]=k,v=os(D);return[_,v]}));return{alias:s.alias,input:b,collectionId:d.collectionId}}default:throw new ci(s.type)}}function Bc(s){return s instanceof X||s&&typeof s=="object"&&"type"in s&&s.type==="val"}function os(s){return Bc(s)?s.value:s}function as(s,e,t){if(s.from.type==="queryRef"&&e.from.type==="queryRef"&&(t.set(s.from.query,e.from.query),as(s.from.query,e.from.query,t)),s.join&&e.join)for(let n=0;n<s.join.length&&n<e.join.length;n++){const r=s.join[n],i=e.join[n];r.from.type==="queryRef"&&i.from.type==="queryRef"&&(t.set(r.from.query,i.from.query),as(r.from.query,i.from.query,t))}}function Ms(s,e){const t=s.type;if(t==="val")return new X(s.value);if(t==="ref"){const n=s.path;if(Array.isArray(n)){if(n[0]===e&&n.length>1)return new Y(n.slice(1));if(n.length===1&&n[0]!==void 0)return new Y([n[0]])}return new Y(Array.isArray(n)?n:[String(n)])}else{const n=[];for(const r of s.args){const i=Ms(r,e);n.push(i)}return new se(s.name,n)}}function Lt(s,e){return s.map(n=>{const r=Ms(n.expression,e);return{...n,expression:r}})}const xn=Symbol.for("@tanstack/db.collection-config-builder");class Lc{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(){const e=this.getWhereClauseForAlias();if(e){const t=Ms(e,this.alias);return this.subscribeToChanges(t)}return this.subscribeToChanges()}subscribeToChanges(e){const t=this.getOrderByInfo(),n=a=>{a instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(a)},r=a=>{const c=a.subscription;if(a.status==="loadingSubset")this.ensureLoadingPromise(c);else{const l=this.subscriptionLoadingPromises.get(c);l&&(this.subscriptionLoadingPromises.delete(c),l.resolve())}};let i;if(t)i=this.subscribeToOrderedChanges(e,t,r,n);else{const a=!this.collectionConfigBuilder.isLazyAlias(this.alias);i=this.subscribeToMatchingChanges(e,a,r)}i.status==="loadingSubset"&&this.ensureLoadingPromise(i);const o=()=>{const a=this.subscriptionLoadingPromises.get(i);a&&(this.subscriptionLoadingPromises.delete(i),a.resolve()),i.unsubscribe()};return this.collectionConfigBuilder.currentSyncState.unsubscribeCallbacks.add(o),i}sendChangesToPipeline(e,t){const n=Array.isArray(e)?e:[...e],r=[];for(const c of n){if(c.type==="insert"){if(this.sentToD2Keys.has(c.key))continue;this.sentToD2Keys.add(c.key)}else c.type==="delete"&&this.sentToD2Keys.delete(c.key);r.push(c)}const i=this.collectionConfigBuilder.currentSyncState.inputs[this.alias],a=zc(i,r,this.collection.config.getKey)>0?t:void 0;this.collectionConfigBuilder.scheduleGraphRun(a,{alias:this.alias})}subscribeToMatchingChanges(e,t,n){const r=p=>{this.sendChangesToPipeline(p)},{orderBy:i,limit:o,offset:a}=this.collectionConfigBuilder.query,c=o!==void 0&&a!==void 0?o+a:o,l=i?Lt(i,this.alias):void 0,u=l?.every(p=>{const g=p.expression;if(g.type!=="ref")return!1;const m=g.path;return Array.isArray(m)&&m.length===1})??!1,h=u?l:void 0,y=u?c:void 0,f=t?p=>{p instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(p)}:void 0;return this.collection.subscribeChanges(r,{...t&&{includeInitialState:t},whereExpression:e,onStatusChange:n,orderBy:h,limit:y,onLoadSubsetResult:f})}subscribeToOrderedChanges(e,t,n,r){const{orderBy:i,offset:o,limit:a,index:c}=t,l=p=>{p instanceof Promise&&(this.pendingOrderedLoadPromise=p,p.finally(()=>{this.pendingOrderedLoadPromise===p&&(this.pendingOrderedLoadPromise=void 0)})),r(p)};this.orderedLoadSubsetResult=l;const u={},h=p=>{const g=Array.isArray(p)?p:[...p];this.trackSentValues(g,t.comparator);const m=Nc(g);this.sendChangesToPipelineWithTracking(m,u.current)},y=this.collection.subscribeChanges(h,{whereExpression:e,onStatusChange:n});u.current=y;const f=this.collection.on("truncate",()=>{this.biggest=void 0,this.lastLoadRequestKey=void 0,this.pendingOrderedLoadPromise=void 0,this.sentToD2Keys.clear()});y.on("unsubscribed",()=>{f()});const d=Lt(i,this.alias);return c?(y.setOrderByIndex(c),y.requestLimitedSnapshot({limit:o+a,orderBy:d,trackLoadSubsetPromise:!1,onLoadSubsetResult:l})):y.requestSnapshot({orderBy:d,limit:o+a,trackLoadSubsetPromise:!1,onLoadSubsetResult:l}),y}loadMoreIfNeeded(e){const t=this.getOrderByInfo();if(!t)return!0;const{dataNeeded:n}=t;if(!n||this.pendingOrderedLoadPromise)return!0;const r=n();return r>0&&this.loadNextItems(r,e),!0}sendChangesToPipelineWithTracking(e,t){if(!this.getOrderByInfo()){this.sendChangesToPipeline(e);return}const r=t;r[xn]??=this.loadMoreIfNeeded.bind(this,t),this.sendChangesToPipeline(e,r[xn])}loadNextItems(e,t){const n=this.getOrderByInfo();if(!n)return;const{orderBy:r,valueExtractorForRawRow:i,offset:o}=n,a=this.biggest,c=a?i(a):void 0;let l;c!==void 0&&(l=Array.isArray(c)?c:[c]);const u=this.getLoadRequestKey({minValues:l,offset:o,limit:e});if(this.lastLoadRequestKey===u)return;const h=Lt(r,this.alias);t.requestLimitedSnapshot({orderBy:h,limit:e,minValues:l,trackLoadSubsetPromise:!1,onLoadSubsetResult:this.orderedLoadSubsetResult}),this.lastLoadRequestKey=u}getWhereClauseForAlias(){const e=this.collectionConfigBuilder.sourceWhereClausesCache;if(e)return e.get(this.alias)}getOrderByInfo(){const e=this.collectionConfigBuilder.optimizableOrderByCollections[this.collectionId];if(e&&e.alias===this.alias)return e}trackSentValues(e,t){for(const n of e){if(n.type==="delete")continue;const r=!this.sentToD2Keys.has(n.key);this.biggest?t(this.biggest,n.value)<0?(this.biggest=n.value,this.lastLoadRequestKey=void 0):r&&(this.lastLoadRequestKey=void 0):(this.biggest=n.value,this.lastLoadRequestKey=void 0)}}ensureLoadingPromise(e){if(this.subscriptionLoadingPromises.has(e))return;let t;const n=new Promise(r=>{t=r});this.subscriptionLoadingPromises.set(e,{resolve:t}),this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(n)}getLoadRequestKey(e){return bs({minValues:e.minValues??null,offset:e.offset,limit:e.limit})}}function zc(s,e,t){const n=[];for(const r of e){const i=t(r.value);r.type==="insert"?n.push([[i,r.value],1]):r.type==="update"?(n.push([[i,r.previousValue],-1]),n.push([[i,r.value],1])):n.push([[i,r.value],-1])}return n.length!==0&&s.sendData(new U(n)),n.length}function*Nc(s){for(const e of s)e.type==="update"?(yield{type:"delete",key:e.key,value:e.previousValue},yield{type:"insert",key:e.key,value:e.value}):yield e}const Gn=new WeakMap;function $c(s){return s.utils?.[Cs]?.getBuilder?.()}function Uc(s,e){Gn.set(s,e)}function Vc(s){return Gn.get(s)}let qc=0;class Wc{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-${++qc}`,this.query=Gc(e),this.collections=Qc(this.query);const t=Jc(this.query);this.collectionByAlias={};for(const[n,r]of t.entries()){const i=this.collections[n];if(i)for(const o of r)this.collectionByAlias[o]=i}this.query.orderBy&&this.query.orderBy.length>0&&(this.compare=Hc(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??Hn(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)),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),[Cs]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(e){if(!this.windowFn)throw new ki;return this.currentWindow=e,this.windowFn(e),this.maybeRunGraphFn?.(),this.liveQueryCollection?.isLoadingSubset?new Promise(t=>{const n=this.liveQueryCollection.on("loadingSubset:change",r=>{r.isLoadingSubset||(n(),t())})}):!0}getWindow(){if(!(!this.windowFn||!this.currentWindow))return{offset:this.currentWindow.offset??0,limit:this.currentWindow.limit??0}}getCollectionIdForAlias(e){const t=this.compiledAliasToCollectionId[e];if(t)return t;const n=this.collectionByAlias[e];if(n)return n.id;throw new Error(`Unknown source alias "${e}"`)}isLazyAlias(e){return this.lazySources.has(e)}maybeRunGraph(e){if(!this.isGraphRunning){if(!this.currentSyncConfig||!this.currentSyncState)throw new Error("maybeRunGraph called without active sync session. This should not happen.");this.isGraphRunning=!0;try{const{begin:t,commit:n}=this.currentSyncConfig,r=this.currentSyncState;if(this.isInErrorState)return;if(r.subscribedToAllCollections){for(;r.graph.pendingWork();)r.graph.run(),r.flushPendingChanges?.(),e?.();r.messagesCount===0&&(t(),n()),this.updateLiveQueryStatus(this.currentSyncConfig)}}finally{this.isGraphRunning=!1}}}scheduleGraphRun(e,t){const n=t?.contextId??vt()?.id,r=t?.jobId??this,i=(()=>{if(t?.dependencies)return t.dependencies;const c=new Set(this.builderDependencies);if(t?.alias){const l=this.aliasDependencies[t.alias];if(l)for(const u of l)c.add(u)}return c.delete(this),Array.from(c)})();if(n)for(const c of i)typeof c.scheduleGraphRun=="function"&&c.scheduleGraphRun(void 0,{contextId:n});if(!this.currentSyncConfig||!this.currentSyncState)throw new Error("scheduleGraphRun called without active sync session. This should not happen.");let o=n?this.pendingGraphRuns.get(n):void 0;o||(o={loadCallbacks:new Set},n&&this.pendingGraphRuns.set(n,o)),e&&o.loadCallbacks.add(e);const a=n?void 0:o;It.schedule({contextId:n,jobId:r,dependencies:i,run:()=>this.executeGraphRun(n,a)})}clearPendingGraphRun(e){this.pendingGraphRuns.delete(e)}hasPendingGraphRun(e){return this.pendingGraphRuns.has(e)}executeGraphRun(e,t){const n=t??(e?this.pendingGraphRuns.get(e):void 0);if(e&&this.pendingGraphRuns.delete(e),!n||!this.currentSyncConfig||!this.currentSyncState)return;this.incrementRunCount();const r=()=>{let i=!0,o;if(n.loadCallbacks.forEach(a=>{try{i=a()&&i}catch(c){i=!1,o??=c}}),o)throw o;return i};this.maybeRunGraph(r)}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;const t={messagesCount:0,subscribedToAllCollections:!1,unsubscribeCallbacks:new Set},n=this.extendPipelineWithChangeProcessing(e,t);this.currentSyncState=n,this.unsubscribeFromSchedulerClears=It.onClear(o=>{this.clearPendingGraphRun(o)});const r=e.collection.on("loadingSubset:change",o=>{o.isLoadingSubset||this.updateLiveQueryStatus(e)});t.unsubscribeCallbacks.add(r);const i=this.subscribeToAllCollections(e,n);return this.maybeRunGraphFn=()=>this.scheduleGraphRun(i),this.scheduleGraphRun(i),()=>{t.unsubscribeCallbacks.forEach(o=>o()),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.lazySources.clear(),this.optimizableOrderByCollections={},this.lazySourcesCallbacks={},Object.keys(this.subscriptions).forEach(o=>delete this.subscriptions[o]),this.compiledAliasToCollectionId={},this.unsubscribeFromSchedulerClears?.(),this.unsubscribeFromSchedulerClears=void 0}}compileBasePipeline(){this.graphCache=new Io,this.inputsCache=Object.fromEntries(Object.keys(this.collectionByAlias).map(n=>[n,this.graphCache.newInput()]));const e=As(this.query,this.inputsCache,this.collections,this.subscriptions,this.lazySourcesCallbacks,this.lazySources,this.optimizableOrderByCollections,n=>{this.windowFn=n});this.pipelineCache=e.pipeline,this.sourceWhereClausesCache=e.sourceWhereClauses,this.compiledAliasToCollectionId=e.aliasToCollectionId;const t=Object.keys(this.compiledAliasToCollectionId).filter(n=>!Object.hasOwn(this.inputsCache,n));if(t.length>0)throw new Ri(t)}maybeCompileBasePipeline(){return(!this.graphCache||!this.inputsCache||!this.pipelineCache)&&this.compileBasePipeline(),{graph:this.graphCache,inputs:this.inputsCache,pipeline:this.pipelineCache}}extendPipelineWithChangeProcessing(e,t){const{begin:n,commit:r}=e,{graph:i,inputs:o,pipeline:a}=this.maybeCompileBasePipeline();let c=new Map;return a.pipe(Lo(l=>{const u=l.getInner();t.messagesCount+=u.length,u.reduce(Yc,c)})),t.flushPendingChanges=()=>{c.size!==0&&(n(),c.forEach(this.applyChanges.bind(this,e)),r(),c=new Map)},i.finalize(),t.graph=i,t.inputs=o,t.pipeline=a,t}applyChanges(e,t,n){const{write:r,collection:i}=e,{deletes:o,inserts:a,value:c,orderByIndex:l}=t;if(this.resultKeys.set(c,n),l!==void 0&&this.orderByIndices.set(c,l),a&&o===0)r({value:c,type:"insert"});else if(a>o||a===o&&i.has(i.getKeyFromItem(c)))r({value:c,type:"update"});else if(o>0)r({value:c,type:"delete"});else throw new Error(`Could not apply changes: ${JSON.stringify(t)}. This should never happen.`)}handleSourceStatusChange(e,t,n){const{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){const{markReady:t}=e;if(this.isInErrorState)return;const 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){const n=Object.entries(this.compiledAliasToCollectionId);if(n.length===0)throw new Error(`Compiler returned no alias metadata for query '${this.id}'. This should not happen; please report.`);const r=n.map(([o,a])=>{const c=this.collectionByAlias[o]??this.collections[a],l=Vc(c);l&&l!==this?(this.aliasDependencies[o]=[l],this.builderDependencies.add(l)):this.aliasDependencies[o]=[];const u=new Lc(o,a,c,this),h=c.on("status:change",d=>{this.handleSourceStatusChange(e,a,d)});t.unsubscribeCallbacks.add(h);const y=u.subscribe();return this.subscriptions[o]=y,u.loadMoreIfNeeded.bind(u,y)}),i=()=>(r.map(o=>o()),!0);return t.subscribedToAllCollections=!0,i}}function Gc(s){return typeof s.query=="function"?lc(s.query):Nn(s.query)}function Hc(s){return(e,t)=>{const n=s.get(e),r=s.get(t);return n&&r?n<r?-1:n>r?1:0:0}}function Qc(s){const e={};function t(r){r.type==="collectionRef"?e[r.collection.id]=r.collection:r.type==="queryRef"&&n(r.query)}function n(r){if(r.from&&t(r.from),r.join&&Array.isArray(r.join))for(const i of r.join)i.from&&t(i.from)}return n(s),e}function Hn(s){const e=s.from;if(e.type==="collectionRef")return e.collection;if(e.type==="queryRef")return Hn(e.query);throw new Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(s)}`)}function Jc(s){const e=new Map;function t(r){if(r)if(r.type==="collectionRef"){const{id:i}=r.collection,o=e.get(i);o?o.add(r.alias):e.set(i,new Set([r.alias]))}else r.type==="queryRef"&&n(r.query)}function n(r){if(r&&(t(r.from),r.join))for(const i of r.join)t(i.from)}return n(s),e}function Yc(s,[[e,t],n]){const[r,i]=t,o=s.get(e)||{deletes:0,inserts:0,value:r,orderByIndex:i};return n<0?o.deletes+=Math.abs(n):n>0&&(o.inserts+=n,o.value=r,i!==void 0&&(o.orderByIndex=i)),s.set(e,o),s}function Cn(s){return new Wc(s).getConfig()}function zt(s){if(typeof s=="function"){const t=Cn({query:s});return In(t)}else{const e=s,t=Cn(e);return e.utils&&(t.utils={...t.utils,...e.utils}),In(t)}}function In(s){const e=Rs(s),t=$c(s);return t&&Uc(e,t),e}const Nt=1;function jl(s,e=[]){const t=s&&typeof s=="object"&&typeof s.subscribeChanges=="function"&&typeof s.startSyncImmediate=="function"&&typeof s.id=="string",n=z.useRef(null),r=z.useRef(null),i=z.useRef(null),o=z.useRef(0),a=z.useRef(null),c=!n.current||t&&i.current!==s||!t&&(r.current===null||r.current.length!==e.length||r.current.some((d,p)=>d!==e[p]));if(c)if(t)s.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.
8
+
9
+ Instead, use a query builder function:
10
+ const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))
11
+
12
+ Or switch to syncMode "eager" if you want all data to sync automatically.`),s.startSyncImmediate(),n.current=s,i.current=s;else if(typeof s=="function"){const d=new $,p=s(d);if(p==null)n.current=null;else if(p instanceof ks)p.startSyncImmediate(),n.current=p;else if(p instanceof $)n.current=zt({query:s,startSync:!0,gcTime:Nt});else if(p&&typeof p=="object")n.current=zt({startSync:!0,gcTime:Nt,...p});else throw new Error(`useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof p}`);r.current=[...e]}else n.current=zt({startSync:!0,gcTime:Nt,...s}),r.current=[...e];c&&(o.current=0,a.current=null);const l=z.useRef(null);(!l.current||c)&&(l.current=d=>{if(!n.current)return()=>{};const p=n.current.subscribeChanges(()=>{o.current+=1,d()});return n.current.status==="ready"&&(o.current+=1,d()),()=>{p.unsubscribe()}});const u=z.useRef(null);(!u.current||c)&&(u.current=()=>{const d=o.current,p=n.current;return(!a.current||a.current.version!==d||a.current.collection!==p)&&(a.current={collection:p,version:d}),a.current});const h=z.useSyncExternalStore(l.current,u.current),y=z.useRef(null),f=z.useRef(null);if(!y.current||y.current.version!==h.version||y.current.collection!==h.collection){if(!h.collection)f.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{const d=Array.from(h.collection.entries()),g=h.collection.config.singleResult;let m=null,w=null;f.current={get state(){return m||(m=new Map(d)),m},get data(){return w||(w=d.map(([,S])=>S)),g?w[0]:w},collection:h.collection,status:h.collection.status,isLoading:h.collection.status==="loading",isReady:h.collection.status==="ready",isIdle:h.collection.status==="idle",isError:h.collection.status==="error",isCleanedUp:h.collection.status==="cleaned-up",isEnabled:!0}}y.current=h}return f.current}class Ce extends ne{constructor(e){super(e),this.name="QueryCollectionError"}}class Zc extends Ce{constructor(){super("[QueryCollection] queryKey must be provided."),this.name="QueryKeyRequiredError"}}class Xc extends Ce{constructor(){super("[QueryCollection] queryFn must be provided."),this.name="QueryFnRequiredError"}}class el extends Ce{constructor(){super("[QueryCollection] queryClient must be provided."),this.name="QueryClientRequiredError"}}class tl extends Ce{constructor(){super("[QueryCollection] getKey must be provided."),this.name="GetKeyRequiredError"}}class sl extends Ce{constructor(){super("Collection must be in 'ready' state for manual sync operations. Sync not initialized yet."),this.name="SyncNotInitializedError"}}class nl extends Ce{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name="DuplicateKeyInBatchError"}}class rl extends Ce{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name="UpdateOperationItemNotFoundError"}}class il extends Ce{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name="DeleteOperationItemNotFoundError"}}const Re=new WeakMap;function ol(s,e){const t=Array.isArray(s)?s:[s],n=[];for(const r of t)if(r.type==="delete"){const i=Array.isArray(r.key)?r.key:[r.key];for(const o of i)n.push({type:"delete",key:o})}else{const i=Array.isArray(r.data)?r.data:[r.data];for(const o of i){let a;if(r.type==="update")a=e.getKey(o);else{const c=e.collection.validateData(o,r.type==="upsert"?"insert":r.type);a=e.getKey(c)}n.push({type:r.type,key:a,data:o})}}return n}function al(s,e){const t=new Set;for(const n of s){if(t.has(n.key))throw new nl(n.key);if(t.add(n.key),n.type==="update"){if(!e.collection._state.syncedData.has(n.key))throw new rl(n.key)}else if(n.type==="delete"&&!e.collection._state.syncedData.has(n.key))throw new il(n.key)}}function We(s,e){const t=ol(s,e);al(t,e),e.begin({immediate:!0});for(const r of t)switch(r.type){case"insert":{const i=e.collection.validateData(r.data,"insert");e.write({type:"insert",value:i});break}case"update":{const o={...e.collection._state.syncedData.get(r.key),...r.data},a=e.collection.validateData(o,"update",r.key);e.write({type:"update",value:a});break}case"delete":{const i=e.collection._state.syncedData.get(r.key);e.write({type:"delete",value:i});break}case"upsert":{const i=e.collection._state.syncedData.has(r.key),o=e.collection.validateData(r.data,i?"update":"insert",r.key);i?e.write({type:"update",value:o}):e.write({type:"insert",value:o});break}}e.commit();const n=Array.from(e.collection._state.syncedData.values());e.updateCacheData?e.updateCacheData(n):e.queryClient.setQueryData(e.queryKey,n)}function cl(s){function e(){const t=s();if(!t)throw new sl;return t}return{writeInsert(t){const n={type:"insert",data:t},r=e(),i=Re.get(r);if(i?.isActive){i.operations.push(n);return}We(n,r)},writeUpdate(t){const n={type:"update",data:t},r=e(),i=Re.get(r);if(i?.isActive){i.operations.push(n);return}We(n,r)},writeDelete(t){const n={type:"delete",key:t},r=e(),i=Re.get(r);if(i?.isActive){i.operations.push(n);return}We(n,r)},writeUpsert(t){const n={type:"upsert",data:t},r=e(),i=Re.get(r);if(i?.isActive){i.operations.push(n);return}We(n,r)},writeBatch(t){const n=e();if(Re.get(n)?.isActive)throw new Error("Cannot nest writeBatch calls. Complete the current batch before starting a new one.");const i={operations:[],isActive:!0};Re.set(n,i);try{const o=t();if(o&&typeof o=="object"&&"then"in o&&typeof o.then=="function")throw new Error("writeBatch does not support async callbacks. The callback must be synchronous.");i.operations.length>0&&We(i.operations,n)}finally{i.isActive=!1,Re.delete(n)}}}}function ll(s){if(!s)return;const e={};return s.where&&(e.where=cs(s.where)),s.orderBy?.length&&(e.orderBy=s.orderBy.map(t=>{const n={expression:cs(t.expression),direction:t.compareOptions.direction,nulls:t.compareOptions.nulls,stringSort:t.compareOptions.stringSort};return t.compareOptions.stringSort==="locale"?{...n,locale:t.compareOptions.locale,localeOptions:t.compareOptions.localeOptions}:n})),s.limit!==void 0&&(e.limit=s.limit),s.offset!==void 0&&(e.offset=s.offset),Object.keys(e).length===0?void 0:JSON.stringify(e)}function cs(s){if(!s)return null;switch(s.type){case"val":return{type:"val",value:ls(s.value)};case"ref":return{type:"ref",path:[...s.path]};case"func":return{type:"func",name:s.name,args:s.args.map(e=>cs(e))};default:return null}}function ls(s){if(s===void 0)return{__type:"undefined"};if(typeof s=="number"){if(Number.isNaN(s))return{__type:"nan"};if(s===Number.POSITIVE_INFINITY)return{__type:"infinity",sign:1};if(s===Number.NEGATIVE_INFINITY)return{__type:"infinity",sign:-1}}return s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:s instanceof Date?{__type:"date",value:s.toJSON()}:Array.isArray(s)?s.map(e=>ls(e)):typeof s=="object"?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,ls(t)])):s}class ul{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 Qn(s){const{queryKey:e,queryFn:t,select:n,queryClient:r,enabled:i,refetchInterval:o,retry:a,retryDelay:c,staleTime:l,getKey:u,onInsert:h,onUpdate:y,onDelete:f,meta:d,...p}=s,g=p.syncMode??"eager";if(!e)throw new Zc;if(!t)throw new Xc;if(!r)throw new el;if(!u)throw new tl;const m={lastError:void 0,errorCount:0,lastErrorUpdatedAt:0,observers:new Map},w=new Map,S=new Map,b=new Map,k=new Map,_=new Map,D=(T,O)=>{const E=b.get(T)||new Set;E.add(O),b.set(T,E);const G=S.get(O)||new Set;G.add(T),S.set(O,G)},I=(T,O)=>{const E=b.get(T)||new Set;E.delete(O),b.set(T,E);const G=S.get(O)||new Set;return G.delete(T),S.set(O,G),E.size===0},v=T=>{const{begin:O,write:E,commit:G,markReady:q,collection:ue}=T;let Ae=!1;const Ne=C=>{if(typeof e=="function")return e(C);if(g==="on-demand"){const F=ll(C);return F!==void 0?[...e,F]:e}else return e},ct=(C={},F=t)=>{const j=Ne(C),P=ft(j),Z={...d,loadSubsetOptions:C};if(m.observers.has(P)){_.set(P,(_.get(P)||0)+1);const ie=m.observers.get(P),ye=ie.getCurrentResult();return ye.isSuccess?!0:ye.isError?Promise.reject(ye.error):r.getQueryData(j)!==void 0?!0:new Promise((Ve,Xn)=>{const Ks=ie.subscribe(Tt=>{queueMicrotask(()=>{Tt.isSuccess?(Ks(),Ve()):Tt.isError&&(Ks(),Xn(Tt.error))})})})}const ae={queryKey:j,queryFn:F,meta:Z,structuralSharing:!0,notifyOnChangeProps:"all",...i!==void 0&&{enabled:i},...o!==void 0&&{refetchInterval:o},...a!==void 0&&{retry:a},...c!==void 0&&{retryDelay:c},...l!==void 0&&{staleTime:l}},Ee=new xr(r,ae);if(w.set(P,j),m.observers.set(P,Ee),_.set(P,(_.get(P)||0)+1),r.getQueryData(j)!==void 0)return(Ae||ue.subscriberCount>0)&&Ue(Ee,P),!0;const te=new Promise((ie,ye)=>{const ht=Ee.subscribe(Ve=>{queueMicrotask(()=>{Ve.isSuccess?(ht(),ie()):Ve.isError&&(ht(),ye(Ve.error))})})});return(Ae||ue.subscriberCount>0)&&Ue(Ee,P),te},$e=C=>{const F=ft(C);return P=>{if(P.isSuccess){m.lastError=void 0,m.errorCount=0;const Z=P.data,ae=n?n(Z):Z;if(!Array.isArray(ae)||ae.some(te=>typeof te!="object")){const te=n?`@tanstack/query-db-collection: select() must return an array of objects. Got: ${typeof ae} for queryKey ${JSON.stringify(C)}`:`@tanstack/query-db-collection: queryFn must return an array of objects. Got: ${typeof ae} for queryKey ${JSON.stringify(C)}`;console.error(te);return}const Ee=new Map(ue._state.syncedData.entries()),ut=new Map;ae.forEach(te=>{const ie=u(te);ut.set(ie,te)}),O(),Ee.forEach((te,ie)=>{const ye=ut.get(ie);ye?le(te,ye)||E({type:"update",value:ye}):I(ie,F)&&E({type:"delete",value:te})}),ut.forEach((te,ie)=>{D(ie,F),Ee.has(ie)||E({type:"insert",value:te})}),G(),q()}else P.isError&&((P.errorUpdatedAt!==m.lastErrorUpdatedAt||P.error!==m.lastError)&&(m.lastError=P.error,m.errorCount++,m.lastErrorUpdatedAt=P.errorUpdatedAt),console.error(`[QueryCollection] Error observing query ${String(C)}:`,P.error),q())}},Me=C=>k.has(C),Ue=(C,F)=>{if(!Me(F)){const j=w.get(F),P=$e(j),Z=C.subscribe(P);k.set(F,Z);const ae=C.getCurrentResult();(ae.isSuccess||ae.isError)&&P(ae)}},lt=()=>{m.observers.forEach(Ue)},At=()=>{k.forEach(C=>{C()}),k.clear()};Ae=!0;const Mt=ue.on("subscribers:change",({subscriberCount:C})=>{C>0?lt():C===0&&At()});if(g==="eager"){const C=ct({});C instanceof Promise&&C.catch(()=>{})}else q();lt(),m.observers.forEach((C,F)=>{const j=w.get(F);$e(j)(C.getCurrentResult())});const Ps=C=>{k.get(C)?.(),k.delete(C);const F=S.get(C)??new Set,j=[];F.forEach(P=>{const Z=b.get(P);Z&&(Z.delete(C),Z.size===0&&(b.delete(P),ue.has(P)&&j.push(ue.get(P))))}),j.length>0&&(O(),j.forEach(P=>{E({type:"delete",value:P})}),G()),m.observers.delete(C),S.delete(C),w.delete(C),_.delete(C)},Ds=C=>{const F=_.get(C)||0,j=m.observers.get(C);if(F<=0&&(k.get(C)?.(),k.delete(C)),j?.hasListeners()??!1){_.set(C,0);return}F>0&&console.warn(`[cleanupQueryIfIdle] Invariant violation: refcount=${F} but no listeners. Cleaning up to prevent leak.`,{hashedQueryKey:C}),Ps(C)},Yn=C=>{Ps(C)},Zn=r.getQueryCache().subscribe(C=>{const F=C.query.queryHash;C.type==="removed"&&w.has(F)&&Ds(F)});return{loadSubset:g==="eager"?void 0:ct,unloadSubset:g==="eager"?void 0:C=>{const F=Ne(C),j=ft(F),Z=(_.get(j)||0)-1;Z<=0?(_.set(j,0),Ds(j)):_.set(j,Z)},cleanup:async()=>{Mt(),At();const C=[...w.values()],F=[...m.observers.keys()];for(const j of F)Yn(j);Zn(),await Promise.all(C.map(async j=>{await r.cancelQueries({queryKey:j,exact:!0}),r.removeQueries({queryKey:j,exact:!0})}))}}},x=async T=>{const E=[...w.values()].map(G=>m.observers.get(ft(G)).refetch({throwOnError:T?.throwOnError}));return Promise.all(E)},M=(T,O)=>{n?r.setQueryData(T,E=>{if(!E||typeof E!="object")return E;if(Array.isArray(E))return O;const G=n(E);if(Array.isArray(G)){for(const q of Object.keys(E))if(E[q]===G)return{...E,[q]:O}}if(Array.isArray(E.data))return{...E,data:O};if(Array.isArray(E.items))return{...E,items:O};if(Array.isArray(E.results))return{...E,results:O};for(const q of Object.keys(E))if(Array.isArray(E[q]))return{...E,[q]:O};return E}):r.setQueryData(T,O)},K=T=>{const O=Array.from(w.values());if(O.length>0)for(const E of O)M(E,T);else{const E=typeof e=="function"?e({}):e;M(E,T)}};let B=null;const Be=T=>{const{begin:O,write:E,commit:G,collection:q}=T,ue=typeof e=="function"?e({}):e;return B={collection:q,queryClient:r,queryKey:ue,getKey:u,begin:O,write:E,commit:G,updateCacheData:K},v(T)},Le=cl(()=>B),Ie=h?async T=>{const O=await h(T)??{};return O.refetch!==!1&&await x(),O}:void 0,ze=y?async T=>{const O=await y(T)??{};return O.refetch!==!1&&await x(),O}:void 0,pe=f?async T=>{const O=await f(T)??{};return O.refetch!==!1&&await x(),O}:void 0,me=new ul(m,x,Le);return{...p,getKey:u,syncMode:g,sync:{sync:Be},onInsert:Ie,onUpdate:ze,onDelete:pe,utils:me}}const hl=us("07328c8ae0c7#getCollectionItems",hs,void 0,void 0,"getCollectionItems"),dl=us("07328c8ae0c7#getDocumentItems",hs,void 0,void 0,"getDocumentItems"),fl=us("07328c8ae0c7#deleteDocumentAction",hs,void 0,void 0,"deleteDocumentAction"),Bl=Rs(Qn({queryClient:En,queryKey:["collections"],queryFn:()=>hl(),getKey:s=>s.id})),Ll=Rs(Qn({queryClient:En,queryKey:["documents"],queryFn:()=>dl(),getKey:s=>`${s.collectionId}-${s.id}`,onDelete:async({transaction:s})=>{const t=s.mutations[0].original;if(t.permissions.delete)try{await fl(t.id,t.collectionId)}catch(n){throw console.error("Delete failed, rolling back:",n),n}}}));function pl({...s}){return R.jsx(ur,{"data-slot":"sheet",...s})}function yl({...s}){return R.jsx(yr,{"data-slot":"sheet-portal",...s})}function gl({className:s,...e}){return R.jsx(gr,{"data-slot":"sheet-overlay",className:N("data-closed:fade-out-0 data-open:fade-in-0 fixed inset-0 z-50 bg-black/80 duration-100 data-closed:animate-out data-open:animate-in data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",s),...e})}function ml({className:s,children:e,side:t="right",showCloseButton:n=!0,...r}){return R.jsxs(yl,{children:[R.jsx(gl,{}),R.jsxs(hr,{"data-slot":"sheet-content","data-side":t,className:N("data-[side=right]:data-closed:slide-out-to-right-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=top]:data-closed:slide-out-to-top-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:fade-out-0 data-open:fade-in-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=bottom]:data-open:slide-in-from-bottom-10 fixed z-50 flex flex-col bg-background bg-clip-padding text-sm shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=top]:inset-x-0 data-[side=left]:inset-y-0 data-[side=right]:inset-y-0 data-[side=top]:top-0 data-[side=right]:right-0 data-[side=bottom]:bottom-0 data-[side=left]:left-0 data-[side=bottom]:h-auto data-[side=left]:h-full data-[side=right]:h-full data-[side=top]:h-auto data-[side=left]:w-3/4 data-[side=right]:w-3/4 data-closed:animate-out data-open:animate-in data-[side=bottom]:border-t data-[side=left]:border-r data-[side=top]:border-b data-[side=right]:border-l data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",s),...r,children:[e,n&&R.jsx(dr,{"data-slot":"sheet-close",asChild:!0,children:R.jsxs(Rn,{variant:"ghost",className:"absolute top-4 right-4",size:"icon-sm",children:[R.jsx(ar,{}),R.jsx("span",{className:"sr-only",children:"Close"})]})})]})]})}function wl({className:s,...e}){return R.jsx("div",{"data-slot":"sheet-header",className:N("flex flex-col gap-1.5 p-6",s),...e})}function vl({className:s,...e}){return R.jsx(fr,{"data-slot":"sheet-title",className:N("font-medium text-base text-foreground",s),...e})}function bl({className:s,...e}){return R.jsx(pr,{"data-slot":"sheet-description",className:N("text-muted-foreground text-sm",s),...e})}const $t=768;function Sl(){const[s,e]=z.useState(void 0);return z.useEffect(()=>{const t=window.matchMedia(`(max-width: ${$t-1}px)`),n=()=>{e(window.innerWidth<$t)};return t.addEventListener("change",n),e(window.innerWidth<$t),()=>t.removeEventListener("change",n)},[]),!!s}const xl="sidebar_state",Cl=3600*24*7,Il="16rem",El="18rem",Rl="3rem",kl="b",Jn=z.createContext(null);function Ts(){const s=z.useContext(Jn);if(!s)throw new Error("useSidebar must be used within a SidebarProvider.");return s}function zl({defaultOpen:s=!0,open:e,onOpenChange:t,className:n,style:r,children:i,...o}){const a=Sl(),[c,l]=z.useState(!1),[u,h]=z.useState(s),y=e??u,f=z.useCallback(m=>{const w=typeof m=="function"?m(y):m;t?t(w):h(w),document.cookie=`${xl}=${w}; path=/; max-age=${Cl}`},[t,y]),d=z.useEffectEvent(()=>a?l(m=>!m):f(m=>!m));z.useEffect(()=>{const m=w=>{w.key===kl&&(w.metaKey||w.ctrlKey)&&(w.preventDefault(),d())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[]);const p=y?"expanded":"collapsed",g=z.useMemo(()=>({state:p,open:y,setOpen:f,isMobile:a,openMobile:c,setOpenMobile:l,toggleSidebar:d}),[p,y,f,a,c,l]);return R.jsx(Jn.Provider,{value:g,children:R.jsx("div",{"data-slot":"sidebar-wrapper",style:{"--sidebar-width":Il,"--sidebar-width-icon":Rl,...r},className:N("group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",n),...o,children:i})})}function Nl({side:s="left",variant:e="sidebar",collapsible:t="offExamples",className:n,children:r,...i}){const{isMobile:o,state:a,openMobile:c,setOpenMobile:l}=Ts();return t==="none"?R.jsx("div",{"data-slot":"sidebar",className:N("flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",n),...i,children:r}):o?R.jsx(pl,{open:c,onOpenChange:l,...i,children:R.jsxs(ml,{"data-sidebar":"sidebar","data-slot":"sidebar","data-mobile":"true",className:"w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden",style:{"--sidebar-width":El},side:s,children:[R.jsxs(wl,{className:"sr-only",children:[R.jsx(vl,{children:"Sidebar"}),R.jsx(bl,{children:"Displays the mobile sidebar."})]}),R.jsx("div",{className:"flex h-full w-full flex-col",children:r})]})}):R.jsxs("div",{className:"group peer hidden text-sidebar-foreground md:block","data-state":a,"data-collapsible":a==="collapsed"?t:"","data-variant":e,"data-side":s,"data-slot":"sidebar",children:[R.jsx("div",{"data-slot":"sidebar-gap",className:N("relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offExamples]:w-0","group-data-[side=right]:rotate-180",e==="floating"||e==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)")}),R.jsx("div",{"data-slot":"sidebar-container",className:N("fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",s==="left"?"left-0 group-data-[collapsible=offExamples]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offExamples]:right-[calc(var(--sidebar-width)*-1)]",e==="floating"||e==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",n),...i,children:R.jsx("div",{"data-sidebar":"sidebar","data-slot":"sidebar-inner",className:N("flex size-full flex-col bg-sidebar",e==="floating"&&"rounded-lg shadow-sm ring-1 ring-sidebar-border"),children:r})})]})}function $l({className:s,onClick:e,...t}){const{toggleSidebar:n}=Ts();return R.jsxs(Rn,{"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon-sm",className:N(s),onClick:r=>{e?.(r),n()},...t,children:[R.jsx(Sr,{}),R.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})}function Ul({className:s,...e}){return R.jsx("main",{"data-slot":"sidebar-inset",className:N("relative flex min-w-0 w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2 md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm",s),...e})}function Vl({className:s,...e}){return R.jsx("div",{"data-slot":"sidebar-header","data-sidebar":"header",className:N("flex flex-col gap-2 p-2",s),...e})}function ql({className:s,...e}){return R.jsx("div",{"data-slot":"sidebar-footer","data-sidebar":"footer",className:N("flex flex-col gap-2 p-2",s),...e})}function Wl({className:s,...e}){return R.jsx("div",{"data-slot":"sidebar-content","data-sidebar":"content",className:N("no-scrollbar flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",s),...e})}function Gl({className:s,...e}){return R.jsx("div",{"data-slot":"sidebar-group","data-sidebar":"group",className:N("relative flex w-full min-w-0 flex-col p-2",s),...e})}function Hl({className:s,...e}){return R.jsx("div",{"data-slot":"sidebar-group-content","data-sidebar":"group-content",className:N("w-full text-sm",s),...e})}function Ql({className:s,...e}){return R.jsx("ul",{"data-slot":"sidebar-menu","data-sidebar":"menu",className:N("flex w-full min-w-0 flex-col gap-1",s),...e})}function Jl({className:s,...e}){return R.jsx("li",{"data-slot":"sidebar-menu-item","data-sidebar":"menu-item",className:N("group/menu-item relative",s),...e})}const Ol=lr("ring-sidebar-ring rounded-lg hover:text-sidebar-accent-foreground group-data-popup-open/menu-item:bg-sidebar-accent group-data-popup-open/menu-item:text-sidebar-accent-foreground gap-2 p-3 text-left text-sm transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 peer/menu-button flex w-full items-center overflow-hidden outline-hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground"},size:{default:"h-9 text-sm",sm:"h-8 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:p-0!"}},defaultVariants:{variant:"default",size:"default"}});function Yl({asChild:s=!1,isActive:e=!1,variant:t="default",size:n="default",tooltip:r,className:i,...o}){const a=s?cr:"button",{isMobile:c,state:l}=Ts(),u=R.jsx(a,{"data-slot":"sidebar-menu-button","data-sidebar":"menu-button","data-size":n,"data-active":e,className:N(Ol({variant:t,size:n}),i),...o});return r?(typeof r=="string"&&(r={children:r}),R.jsxs(mr,{children:[R.jsx(wr,{asChild:!0,children:u}),R.jsx(vr,{side:"right",align:"center",hidden:l!=="collapsed"||c,...r})]})):u}export{$l as S,Yt as a,Nl as b,Bl as c,Ll as d,Qt as e,Vl as f,Yl as g,Wl as h,Gl as i,Hl as j,Ql as k,ql as l,Fl as m,Jl as n,aa as o,zl as p,Ul as q,jl as u};
@@ -1 +1 @@
1
- import{j as r}from"./react-D58ornpH.js";import{S as a}from"./separator-BDe8wWVP.js";import{S as t}from"./sidebar-DNKkYLTA.js";function m({children:e}){return r.jsxs("header",{className:"flex h-10 m-2 top-2 shrink-0 items-center gap-2 border rounded-lg sticky bg-card text-card-foreground z-30 px-3 shadow-md",children:[r.jsx(t,{className:"-mx-2"}),r.jsx(a,{orientation:"vertical",className:"mx-2 data-[orientation=vertical]:h-4"}),e]})}export{m as S};
1
+ import{j as r}from"./react-CzFdRS7Y.js";import{S as a}from"./separator-0kwG7IIM.js";import{S as t}from"./sidebar-ByyQE2QS.js";function m({children:e}){return r.jsxs("header",{className:"flex h-10 m-2 top-2 shrink-0 items-center gap-2 border rounded-lg sticky bg-card text-card-foreground z-30 px-3 shadow-md",children:[r.jsx(t,{className:"-mx-2"}),r.jsx(a,{orientation:"vertical",className:"mx-2 data-[orientation=vertical]:h-4"}),e]})}export{m as S};
@@ -0,0 +1 @@
1
+ import{j as o}from"./react-CzFdRS7Y.js";import{c as r,d as s}from"./index-DrT4Adhh.js";const i=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],n=r("loader-circle",i);function d({className:a,...e}){return o.jsx(n,{role:"status","aria-label":"Loading",className:s("size-4 animate-spin",a),...e})}export{n as L,d as S};