@undefineds.co/xpod 0.4.28 → 0.4.30

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 (179) hide show
  1. package/dist/api/ApiServer.js +4 -0
  2. package/dist/api/ai-gateway/AiGatewayService.d.ts +55 -0
  3. package/dist/api/ai-gateway/AiGatewayService.js +145 -6
  4. package/dist/api/ai-gateway/auth/AiConnectionsInvocationKeyIssuer.js +5 -3
  5. package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.d.ts +16 -49
  6. package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.js +6 -71
  7. package/dist/api/ai-gateway/auth/InvocationTokenAuthenticator.js +1 -0
  8. package/dist/api/ai-gateway/auth/InvocationTokenCodec.d.ts +4 -0
  9. package/dist/api/ai-gateway/auth/InvocationTokenCodec.js +8 -1
  10. package/dist/api/ai-gateway/connect/FileSessionImportAdapter.d.ts +3 -0
  11. package/dist/api/ai-gateway/connect/FileSessionImportAdapter.js +23 -3
  12. package/dist/api/ai-gateway/connect/SessionImportProfiles.d.ts +9 -1
  13. package/dist/api/ai-gateway/connect/SessionImportProfiles.js +4 -3
  14. package/dist/api/ai-gateway/connect/index.d.ts +40 -0
  15. package/dist/api/ai-gateway/connect/index.js +194 -4
  16. package/dist/api/ai-gateway/models/PodModelSelectionRepository.js +1 -1
  17. package/dist/api/ai-gateway/pod/OwnerPodAccess.js +5 -0
  18. package/dist/api/ai-gateway/pod/PodBaseUrlResolver.d.ts +11 -2
  19. package/dist/api/ai-gateway/pod/PodBaseUrlResolver.js +72 -10
  20. package/dist/api/ai-gateway/quota/ProviderQuotaAdapter.js +1 -1
  21. package/dist/api/ai-gateway/routing/ModelRouter.d.ts +7 -0
  22. package/dist/api/ai-gateway/routing/ModelRouter.js +13 -10
  23. package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.d.ts +1 -5
  24. package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.js +8 -63
  25. package/dist/api/auth/AuthContext.d.ts +4 -0
  26. package/dist/api/auth/ClientCredentialsAuthenticator.js +11 -5
  27. package/dist/api/auth/SolidSessionFactory.d.ts +50 -4
  28. package/dist/api/auth/SolidSessionFactory.js +114 -4
  29. package/dist/api/chatkit/pod-store.d.ts +8 -1
  30. package/dist/api/chatkit/pod-store.js +54 -3
  31. package/dist/api/container/common.js +34 -60
  32. package/dist/api/container/index.js +0 -3
  33. package/dist/api/container/routes.js +1 -8
  34. package/dist/api/container/types.d.ts +2 -9
  35. package/dist/api/container/types.js +0 -5
  36. package/dist/api/handlers/AiGatewayManagementHandler.d.ts +4 -12
  37. package/dist/api/handlers/AiGatewayManagementHandler.js +18 -258
  38. package/dist/api/middleware/AuthMiddleware.js +29 -1
  39. package/dist/api/runs/PiAgentRuntimeDriver.js +6 -1
  40. package/dist/cli/index.js +2 -1
  41. package/dist/identity/oidc/PodOwnershipResolver.js +16 -6
  42. package/dist/runtime/ingress-port.d.ts +9 -2
  43. package/dist/runtime/ingress-port.js +7 -2
  44. package/dist/runtime/local-secret-file.d.ts +1 -1
  45. package/dist/runtime/runner/node/CommunitySolidServerCssRunner.d.ts +3 -1
  46. package/dist/runtime/runner/node/CommunitySolidServerCssRunner.js +31 -1
  47. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.d.ts +3 -1
  48. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +96 -67
  49. package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.d.ts +2 -1
  50. package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.js +2 -2
  51. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.d.ts +1 -2
  52. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.js +2 -2
  53. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +81 -23
  54. package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.d.ts +2 -1
  55. package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.js +2 -2
  56. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.d.ts +2 -1
  57. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.js +2 -2
  58. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.js +1 -1
  59. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/fingerprint.d.ts +1 -0
  60. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/fingerprint.js +7 -0
  61. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.d.ts +1 -2
  62. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.js +0 -33
  63. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.d.ts +1 -1
  64. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.js +68 -22
  65. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/types.d.ts +37 -10
  66. package/node_modules/@undefineds.co/ai-connections/dist/controller.js +5 -54
  67. package/node_modules/@undefineds.co/ai-connections/dist/error-wording.js +7 -2
  68. package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.cjs +405 -0
  69. package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.d.ts +14 -0
  70. package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.js +36 -0
  71. package/node_modules/@undefineds.co/ai-connections/dist/service-access.js +5 -26
  72. package/node_modules/@undefineds.co/ai-connections/package.json +10 -2
  73. package/node_modules/@undefineds.co/extension-sdk/dist/solid-permissions.js +131 -13
  74. package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +7 -1
  75. package/node_modules/@undefineds.co/extension-sdk/package.json +1 -1
  76. package/node_modules/@undefineds.co/pod-collections/dist/index.cjs +38 -5
  77. package/node_modules/@undefineds.co/pod-collections/dist/mapping.d.ts +8 -0
  78. package/node_modules/@undefineds.co/pod-collections/dist/mapping.js +34 -0
  79. package/node_modules/@undefineds.co/pod-collections/dist/mutations.d.ts +2 -1
  80. package/node_modules/@undefineds.co/pod-collections/dist/mutations.js +6 -4
  81. package/node_modules/@undefineds.co/pod-collections/dist/sync.js +4 -3
  82. package/node_modules/@undefineds.co/pod-collections/package.json +1 -1
  83. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.d.ts +1 -1
  84. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.js +2 -2
  85. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpViews.js +2 -2
  86. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.d.ts +3 -3
  87. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.js +5 -5
  88. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.d.ts +5 -5
  89. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.js +5 -5
  90. package/node_modules/@undefineds.co/shared-ui/dist/theme.css +32 -5
  91. package/node_modules/@undefineds.co/shared-ui/package.json +1 -1
  92. package/package.json +2 -2
  93. package/static/app/assets/main.css +1 -1
  94. package/static/app/assets/main.js +18 -18
  95. package/static/dashboard/assets/{AccountAuthBoundary-Dv52SZc6.js → AccountAuthBoundary-CuqXFEW4.js} +1 -1
  96. package/static/dashboard/assets/{DesktopOidcCallback-DaT_Rumf.js → DesktopOidcCallback-7i-yOvPW.js} +1 -1
  97. package/static/dashboard/assets/DevicePages-D1m_BNtX.js +2 -0
  98. package/static/dashboard/assets/ModelsPage-0qWGa5Y6.js +12 -0
  99. package/static/dashboard/assets/{PaneListHeader-DtvnRmFq.js → PaneListHeader-uWdPgJ0E.js} +1 -1
  100. package/static/dashboard/assets/{PodDeletionAuthorizationPanel-BJk_8rJq.js → PodDeletionAuthorizationPanel-C22bhZeD.js} +3 -3
  101. package/static/dashboard/assets/{PodPage-C4gzEspV.js → PodPage-Dyo3yCb-.js} +1 -1
  102. package/static/dashboard/assets/{SystemSettingsPage-HaNrP1H1.js → SystemSettingsPage-CeX-oG_a.js} +1 -1
  103. package/static/dashboard/assets/{TasksPage-BdO5K2L7.js → TasksPage-B0EoyRYT.js} +1 -1
  104. package/static/dashboard/assets/{WebDesktopEntry-Cj9_ZfJU.js → WebDesktopEntry-DT44RrTa.js} +1 -1
  105. package/static/dashboard/assets/XpodAiConnectionsPodStore-EXCqZPmb.js +3 -0
  106. package/static/dashboard/assets/XpodShellApp-BEzi4f1j.css +1 -0
  107. package/static/dashboard/assets/XpodShellApp-DAFsxamX.js +4 -0
  108. package/static/dashboard/assets/{account-session-DlcKNG7k.js → account-session-rRAOF7nF.js} +1 -1
  109. package/static/dashboard/assets/{button-wslF55uZ.js → button-WVnQUNG-.js} +1 -1
  110. package/static/dashboard/assets/{collection-runtime-uxxgEu13.js → collection-runtime-BAJQ8Qub.js} +1 -1
  111. package/static/dashboard/assets/{createLucideIcon-BJQl82Qk.js → createLucideIcon-BWelSi3L.js} +1 -1
  112. package/static/dashboard/assets/dashboard-hSOBxPcP.css +1 -0
  113. package/static/dashboard/assets/{dashboard-Or0gnkou.js → dashboard-vmne1ZE0.js} +2 -2
  114. package/static/dashboard/assets/{index-BqFeOML9.js → index-HDQQ8asz.js} +1 -1
  115. package/static/dashboard/assets/{index-DgKn1twH.js → index-gtv-MAHl.js} +1 -1
  116. package/static/dashboard/assets/{label-CS6Sx6Zb.js → label-tKuCTJm2.js} +1 -1
  117. package/static/dashboard/assets/{list-UyhlCFKk.js → list-CKq3KHke.js} +1 -1
  118. package/static/dashboard/assets/{nav-item-style-CW1Nnorq.js → nav-item-style-B2gI7c52.js} +1 -1
  119. package/static/dashboard/assets/pod-collections-host-BqOAkacM.js +8 -0
  120. package/static/dashboard/assets/{safe-continuation-ClWAhcma.js → safe-continuation-BsKjDpAA.js} +1 -1
  121. package/static/dashboard/assets/{section-header-CEIEcco-.js → section-header-DM0JU-wk.js} +1 -1
  122. package/static/dashboard/assets/{setting-row-CaYv3dfF.js → setting-row-XiH7UjWy.js} +1 -1
  123. package/static/dashboard/assets/{xpod-remembered-login-BUF9fin1.js → xpod-remembered-login-nv1g1sfC.js} +4 -4
  124. package/static/dashboard/dashboard.html +2 -2
  125. package/static/settings/assets/{AccountAuthBoundary-Chqd38oU.js → AccountAuthBoundary-DAUR0omy.js} +1 -1
  126. package/static/settings/assets/{DesktopOidcCallback-VUrOSM_q.js → DesktopOidcCallback-BNZAZMWY.js} +1 -1
  127. package/static/settings/assets/DevicePages-BO9SrXRp.js +2 -0
  128. package/static/settings/assets/ModelsPage-DREEXdf3.js +12 -0
  129. package/static/settings/assets/{PaneListHeader-B5RkRqr4.js → PaneListHeader-CeUH0JjQ.js} +1 -1
  130. package/static/settings/assets/{PodDeletionAuthorizationPanel-DPM-5Izt.js → PodDeletionAuthorizationPanel-Ch4--l4b.js} +3 -3
  131. package/static/settings/assets/{PodPage-CxND6wwc.js → PodPage-CqJBj3GJ.js} +1 -1
  132. package/static/settings/assets/{SystemSettingsPage-C8EdMkW7.js → SystemSettingsPage-2LSjpqUa.js} +1 -1
  133. package/static/settings/assets/{TasksPage-DuqptEm8.js → TasksPage-DA5IRxlP.js} +1 -1
  134. package/static/settings/assets/{WebDesktopEntry-BRcyktkv.js → WebDesktopEntry-BVelF1q0.js} +1 -1
  135. package/static/settings/assets/XpodAiConnectionsPodStore-O5-2qBsx.js +3 -0
  136. package/static/settings/assets/XpodShellApp-BEzi4f1j.css +1 -0
  137. package/static/settings/assets/XpodShellApp-D1b3kqD0.js +4 -0
  138. package/static/settings/assets/XpodThemeProvider-hSOBxPcP.css +1 -0
  139. package/static/settings/assets/{XpodThemeProvider-DK3pIdRG.js → XpodThemeProvider-rUdAw66p.js} +2 -2
  140. package/static/settings/assets/{account-session-DJOZ03xr.js → account-session-BD1q8D_o.js} +1 -1
  141. package/static/settings/assets/auth-callback-PWS7okI8.js +1 -0
  142. package/static/settings/assets/{button-D3yW-2o1.js → button-ZJYFB218.js} +1 -1
  143. package/static/settings/assets/{collection-runtime-DfGo25mh.js → collection-runtime-C2FHCCXJ.js} +1 -1
  144. package/static/settings/assets/{createLucideIcon-CacwLsmB.js → createLucideIcon-B2wXvYTD.js} +1 -1
  145. package/static/settings/assets/{index-r5KRYsKC.js → index-JFAkaKZH.js} +1 -1
  146. package/static/settings/assets/{label-MJjUmvzG.js → label-BLrTAmGy.js} +1 -1
  147. package/static/settings/assets/{list-Ce-5k1MX.js → list-Cm96vvJO.js} +1 -1
  148. package/static/settings/assets/{nav-item-style-ZUbL8KOZ.js → nav-item-style-C2upI7sr.js} +1 -1
  149. package/static/settings/assets/pod-collections-host-BqOAkacM.js +8 -0
  150. package/static/settings/assets/{safe-continuation-vlBZFSlU.js → safe-continuation-CYaRj3rj.js} +1 -1
  151. package/static/settings/assets/{section-header-DGJdEvQw.js → section-header-BviL5H8E.js} +1 -1
  152. package/static/settings/assets/{setting-row-C7tuFiho.js → setting-row-BYikj0YO.js} +1 -1
  153. package/static/settings/assets/{settings-CyQPih1O.js → settings-CpoDG_Qr.js} +1 -1
  154. package/static/settings/assets/{xpod-remembered-login-D-TzzT5K.js → xpod-remembered-login-BJ4QUSXy.js} +4 -4
  155. package/static/settings/auth-callback.html +3 -3
  156. package/static/settings/settings.html +3 -3
  157. package/dist/api/ai-gateway/auth/GatewayApiKey.d.ts +0 -28
  158. package/dist/api/ai-gateway/auth/GatewayApiKey.js +0 -162
  159. package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.d.ts +0 -26
  160. package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.js +0 -97
  161. package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.d.ts +0 -67
  162. package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.js +0 -340
  163. package/dist/runtime/gateway-locator-secret.d.ts +0 -5
  164. package/dist/runtime/gateway-locator-secret.js +0 -30
  165. package/static/dashboard/assets/DevicePages-HjclpIVm.js +0 -2
  166. package/static/dashboard/assets/ModelsPage-Be2TPd-x.js +0 -11
  167. package/static/dashboard/assets/XpodAiConnectionsPodStore-B7gmXBmC.js +0 -3
  168. package/static/dashboard/assets/XpodShellApp-Bwom2xL3.css +0 -1
  169. package/static/dashboard/assets/XpodShellApp-D_KY4nCW.js +0 -4
  170. package/static/dashboard/assets/dashboard-CbJ-JkrI.css +0 -1
  171. package/static/dashboard/assets/pod-collections-host-DjK2xf-b.js +0 -8
  172. package/static/settings/assets/DevicePages-C6qwvWwu.js +0 -2
  173. package/static/settings/assets/ModelsPage-Ry_dObRQ.js +0 -11
  174. package/static/settings/assets/XpodAiConnectionsPodStore-CyA_BJVC.js +0 -3
  175. package/static/settings/assets/XpodShellApp-Bwom2xL3.css +0 -1
  176. package/static/settings/assets/XpodShellApp-CsivHJl0.js +0 -4
  177. package/static/settings/assets/XpodThemeProvider-CbJ-JkrI.css +0 -1
  178. package/static/settings/assets/auth-callback-GIBYEz_7.js +0 -1
  179. package/static/settings/assets/pod-collections-host-DjK2xf-b.js +0 -8
@@ -1 +1 @@
1
- import{s as o,p as s}from"./xpod-remembered-login-BUF9fin1.js";import{C as u,P as C,a as p,b as P,c as S,d as g,e as c,f as h,g as b,h as T,i as j,S as v,j as x,k as B,l as f,m as I,n as y,o as A,q as D,r as O,t as V,u as k,v as q,w,x as z,y as J,z as N,A as U,B as E,D as F}from"./xpod-remembered-login-BUF9fin1.js";import"./createLucideIcon-BJQl82Qk.js";import"./dashboard-Or0gnkou.js";import"./button-wslF55uZ.js";import"./PodDeletionAuthorizationPanel-BJk_8rJq.js";import"./account-session-DlcKNG7k.js";import"@comunica/query-sparql-solid";export{u as ColumnBuilder,C as PodArrayColumn,p as PodBooleanColumn,P as PodColumnBase,S as PodDateTimeColumn,g as PodIntegerColumn,c as PodJsonColumn,h as PodObjectColumn,b as PodStringColumn,T as PodTable,j as PodUriColumn,v as SolidSchema,x as boolean,B as date,f as generateNanoId,I as hasStringValue,y as hasTermValue,A as id,D as integer,O as isSolidSchema,V as json,k as mergeSchemaColumns,q as object,s as podTable,w as real,z as resolveTermIri,J as solidSchema,o as string,N as text,U as timestamp,E as uri,F as validateColumnOverride};
1
+ import{s as o,p as s}from"./xpod-remembered-login-nv1g1sfC.js";import{C as u,P as C,a as p,b as P,c as S,d as g,e as c,f as h,g as b,h as T,i as j,S as v,j as x,k as B,l as f,m as I,n as y,o as A,q as D,r as O,t as V,u as k,v as q,w,x as z,y as J,z as N,A as U,B as E,D as F}from"./xpod-remembered-login-nv1g1sfC.js";import"./createLucideIcon-BWelSi3L.js";import"./dashboard-vmne1ZE0.js";import"./button-WVnQUNG-.js";import"./PodDeletionAuthorizationPanel-C22bhZeD.js";import"./account-session-rRAOF7nF.js";import"@comunica/query-sparql-solid";export{u as ColumnBuilder,C as PodArrayColumn,p as PodBooleanColumn,P as PodColumnBase,S as PodDateTimeColumn,g as PodIntegerColumn,c as PodJsonColumn,h as PodObjectColumn,b as PodStringColumn,T as PodTable,j as PodUriColumn,v as SolidSchema,x as boolean,B as date,f as generateNanoId,I as hasStringValue,y as hasTermValue,A as id,D as integer,O as isSolidSchema,V as json,k as mergeSchemaColumns,q as object,s as podTable,w as real,z as resolveTermIri,J as solidSchema,o as string,N as text,U as timestamp,E as uri,F as validateColumnOverride};
@@ -1,4 +1,4 @@
1
- import{n as m,D as R,T as j,N as B}from"./XpodShellApp-D_KY4nCW.js";import{B as W,d as z,e as H,L as V,f as Z,Q as X,Q as Y,V as J}from"./XpodShellApp-D_KY4nCW.js";import"./dashboard-Or0gnkou.js";import"./xpod-remembered-login-BUF9fin1.js";import"./createLucideIcon-BJQl82Qk.js";import"./button-wslF55uZ.js";import"./PodDeletionAuthorizationPanel-BJk_8rJq.js";import"./account-session-DlcKNG7k.js";import"@comunica/query-sparql-solid";import"./safe-continuation-ClWAhcma.js";import"./nav-item-style-CW1Nnorq.js";function O(a){return!!a&&a.termType==="DefaultGraph"}function f(a){return a.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}const P=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,T=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/,g="./",Q="../",p="?",$="#";class b{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!P.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!b.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",f(e)],i=[],s=[],r=/[^/?#]*([/?#])/y;let n,h=0,u=0,o=r.lastIndex=e.length;for(;!h&&!u&&(n=r.exec(this.base));)n[1]===$?u=r.lastIndex-1:(t.push(f(n[0]),"(?:"),i.push(")?"),n[1]!==p?s.push(o=r.lastIndex):(h=o=r.lastIndex,u=this.base.indexOf($,h),this._pathReplacements[h]=p));for(let _=0;_<s.length;_++)this._pathReplacements[s[_]]=Q.repeat(s.length-_-1);return this._pathReplacements[s[s.length-1]]=g,this._baseLength=u>0?u:this.base.length,t.push(f(this.base.substring(o,this._baseLength)),h?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...i].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const i=t[0].length;if(i===this._baseLength&&i===e.length)return"";const s=this._pathReplacements[i];if(s){const r=e.substring(i);return s!==p&&!T.test(r)?e:s===g&&/^[^?#]/.test(r)?r:s+r}return e.substring(i-1)}}const c=R.defaultGraph(),{rdf:S,xsd:l}=m,x=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,w=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,k={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class d extends j{equals(e){return e===this}}class U{constructor(e,t){if(this._prefixRegex=/$0^/,e&&typeof e.write!="function"&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=t.end===void 0?!0:!!t.end;else{let i="";this._outputStream={write(s,r,n){i+=s,n&&n()},end:s=>{s&&s(null,i)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=c,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseIri=new b(t.baseIRI)))}get _inDefaultGraph(){return c.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,i,s,r){try{s.equals(this._graph)||(this._write((this._subject===null?"":this._inDefaultGraph?`.
1
+ import{n as m,D as R,T as j,N as B}from"./XpodShellApp-DAFsxamX.js";import{B as W,d as z,e as H,L as V,f as Z,Q as X,Q as Y,V as J}from"./XpodShellApp-DAFsxamX.js";import"./dashboard-vmne1ZE0.js";import"./xpod-remembered-login-nv1g1sfC.js";import"./createLucideIcon-BWelSi3L.js";import"./button-WVnQUNG-.js";import"./PodDeletionAuthorizationPanel-C22bhZeD.js";import"./account-session-rRAOF7nF.js";import"@comunica/query-sparql-solid";import"./safe-continuation-BsKjDpAA.js";import"./nav-item-style-B2gI7c52.js";function O(a){return!!a&&a.termType==="DefaultGraph"}function f(a){return a.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}const P=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i,T=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/,g="./",Q="../",p="?",$="#";class b{constructor(e){this.base=e,this._baseLength=0,this._baseMatcher=null,this._pathReplacements=new Array(e.length+1)}static supports(e){return!P.test(e)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!b.supports(this.base))return this._baseMatcher=/.^/;const e=/^[^:]*:\/*/.exec(this.base)[0],t=["^",f(e)],i=[],s=[],r=/[^/?#]*([/?#])/y;let n,h=0,u=0,o=r.lastIndex=e.length;for(;!h&&!u&&(n=r.exec(this.base));)n[1]===$?u=r.lastIndex-1:(t.push(f(n[0]),"(?:"),i.push(")?"),n[1]!==p?s.push(o=r.lastIndex):(h=o=r.lastIndex,u=this.base.indexOf($,h),this._pathReplacements[h]=p));for(let _=0;_<s.length;_++)this._pathReplacements[s[_]]=Q.repeat(s.length-_-1);return this._pathReplacements[s[s.length-1]]=g,this._baseLength=u>0?u:this.base.length,t.push(f(this.base.substring(o,this._baseLength)),h?"(?:#|$)":"(?:[?#]|$)"),this._baseMatcher=new RegExp([...t,...i].join(""))}toRelative(e){const t=this._getBaseMatcher().exec(e);if(!t)return e;const i=t[0].length;if(i===this._baseLength&&i===e.length)return"";const s=this._pathReplacements[i];if(s){const r=e.substring(i);return s!==p&&!T.test(r)?e:s===g&&/^[^?#]/.test(r)?r:s+r}return e.substring(i-1)}}const c=R.defaultGraph(),{rdf:S,xsd:l}=m,x=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,w=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,k={"\\":"\\\\",'"':'\\"'," ":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class d extends j{equals(e){return e===this}}class U{constructor(e,t){if(this._prefixRegex=/$0^/,e&&typeof e.write!="function"&&(t=e,e=null),t=t||{},this._lists=t.lists,e)this._outputStream=e,this._endStream=t.end===void 0?!0:!!t.end;else{let i="";this._outputStream={write(s,r,n){i+=s,n&&n()},end:s=>{s&&s(null,i)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?(this._lineMode=!0,this._writeQuad=this._writeQuadLine):(this._lineMode=!1,this._graph=c,this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes),t.baseIRI&&(this._baseIri=new b(t.baseIRI)))}get _inDefaultGraph(){return c.equals(this._graph)}_write(e,t){this._outputStream.write(e,"utf8",t)}_writeQuad(e,t,i,s,r){try{s.equals(this._graph)||(this._write((this._subject===null?"":this._inDefaultGraph?`.
2
2
  `:`
3
3
  }
4
4
  `)+(c.equals(s)?"":`${this._encodeIriOrBlank(s)} {
@@ -1 +1 @@
1
- import{r as t,j as o}from"./dashboard-Or0gnkou.js";import{c as s}from"./button-wslF55uZ.js";const m=t.forwardRef(({className:e,...a},r)=>o.jsx("label",{ref:r,className:s("text-sm font-medium leading-none text-muted-foreground",e),...a}));m.displayName="Label";export{m as L};
1
+ import{r as t,j as o}from"./dashboard-vmne1ZE0.js";import{c as s}from"./button-WVnQUNG-.js";const m=t.forwardRef(({className:e,...a},r)=>o.jsx("label",{ref:r,className:s("text-sm font-medium leading-none text-muted-foreground",e),...a}));m.displayName="Label";export{m as L};
@@ -1 +1 @@
1
- import{r as d,j as s}from"./dashboard-Or0gnkou.js";import{S as m,c}from"./button-wslF55uZ.js";const u=d.forwardRef(({className:o,asChild:e=!1,children:r,...a},l)=>{const n=e?m:"div";return s.jsx(n,{ref:l,className:c("divide-y rounded-xl border border-border bg-card",o),...a,children:r})});u.displayName="ListSurface";const j=d.forwardRef(({className:o,leading:e,title:r,description:a,trailing:l,asChild:n=!1,children:t,...i},x)=>{const f=c("flex flex-wrap items-center gap-3 p-4 text-sm leading-normal",o),p=n?m:"div";return s.jsx(p,{ref:x,className:f,...i,children:n?t:s.jsxs(s.Fragment,{children:[e?s.jsx("span",{className:"shrink-0",children:e}):null,s.jsxs("div",{className:"min-w-0 flex-1 break-words",children:[r?s.jsx("div",{children:r}):null,a?s.jsx("p",{className:"mt-0.5 text-xs leading-normal text-muted-foreground",children:a}):null]}),l?s.jsx("span",{className:"shrink-0",children:l}):null,t?s.jsx("div",{className:"w-full min-w-0 break-words",children:t}):null]})})});j.displayName="ListRow";export{u as L,j as a};
1
+ import{r as d,j as s}from"./dashboard-vmne1ZE0.js";import{S as m,c}from"./button-WVnQUNG-.js";const u=d.forwardRef(({className:o,asChild:e=!1,children:r,...a},l)=>{const n=e?m:"div";return s.jsx(n,{ref:l,className:c("divide-y rounded-xl border border-border bg-card",o),...a,children:r})});u.displayName="ListSurface";const j=d.forwardRef(({className:o,leading:e,title:r,description:a,trailing:l,asChild:n=!1,children:t,...i},x)=>{const f=c("flex flex-wrap items-center gap-3 p-4 text-sm leading-normal",o),p=n?m:"div";return s.jsx(p,{ref:x,className:f,...i,children:n?t:s.jsxs(s.Fragment,{children:[e?s.jsx("span",{className:"shrink-0",children:e}):null,s.jsxs("div",{className:"min-w-0 flex-1 break-words",children:[r?s.jsx("div",{children:r}):null,a?s.jsx("p",{className:"mt-0.5 text-xs leading-normal text-muted-foreground",children:a}):null]}),l?s.jsx("span",{className:"shrink-0",children:l}):null,t?s.jsx("div",{className:"w-full min-w-0 break-words",children:t}):null]})})});j.displayName="ListRow";export{u as L,j as a};
@@ -1 +1 @@
1
- import{c as B}from"./createLucideIcon-BJQl82Qk.js";import{r as o,j as l}from"./dashboard-Or0gnkou.js";import{c as g}from"./button-wslF55uZ.js";const V=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],de=B("database",V);function fe(e){if(!R(e))throw new Error("Applet layout descriptor must be an object");if(typeof e.type!="string")throw new Error("Applet layout descriptor type must be a string");switch(e.type){case"single-pane":case"two-pane":return P(e.context),e;case"three-pane":return P(e.context),e;default:throw new Error(`Unsupported applet layout type: ${e.type}`)}}function R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function P(e){if(e!==void 0){if(!R(e))throw new Error("Applet layout descriptor context must be an object");if("collapsible"in e&&typeof e.collapsible!="boolean")throw new Error("Applet layout descriptor context.collapsible must be a boolean");if("initiallyCollapsed"in e&&typeof e.initiallyCollapsed!="boolean")throw new Error("Applet layout descriptor context.initiallyCollapsed must be a boolean")}}const G=184,p={narrow:768,wideObjects:1100};function K(e){const{pageType:t,contentWidth:n}=e,a=e.hasObjectCollection===!0;if(!Number.isFinite(n)||n<=0)throw new Error("Applet pane plan needs a positive contentWidth");return n<p.narrow?{pageType:t,navigation:"task-bar",panes:"single",showObjectColumn:!1}:n>=p.wideObjects&&t==="collection"&&a?{pageType:t,navigation:"rail",panes:"list-detail",showObjectColumn:!0}:{pageType:t,navigation:"rail",panes:t==="collection"&&n<p.wideObjects?"stack":"single",showObjectColumn:!1}}const D=o.createContext(null);function pe(){const e=o.useContext(D);if(!e)throw new Error("useWorkspaceLayout must be used inside TwoPaneLayout");return e}const Q=o.createContext(void 0),N="(max-width: 767px)",X={gridTemplateColumns:"210px minmax(0, 1fr)"};function Y(e){return e==="context"?"main":e}function I(e){if(typeof window>"u"||typeof window.matchMedia!="function")return()=>{};const t=window.matchMedia(N);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function U(){return typeof window>"u"||typeof window.matchMedia!="function"?"split":window.matchMedia(N).matches?"stack":"split"}function F(){return"split"}function z(e){const t=o.useSyncExternalStore(I,U,F);return e==="auto"?t:e}const T=`(min-width: ${p.wideObjects+G}px)`;function J(){return o.useSyncExternalStore(e=>{if(typeof window>"u"||typeof window.matchMedia!="function")return()=>{};const t=window.matchMedia(T);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>typeof window>"u"||typeof window.matchMedia!="function"?!0:window.matchMedia(T).matches,()=>!0)}function q(e){const t=o.useSyncExternalStore(I,U,F)==="stack",a=J()?p.wideObjects:t?p.narrow-1:p.narrow,r=K({pageType:e.pageType,contentWidth:a,hasObjectCollection:e.hasObjectCollection}),i=r.panes==="list-detail"?"split":"stack";return{resolvedMode:e.mode==="auto"?i:e.mode,showObjectColumn:r.showObjectColumn}}function Z({resolvedMode:e,history:t,resolvePane:n}){const[a,r]=o.useState("list"),i=o.useRef(null),x=o.useRef(null),k=o.useRef(null),y=o.useRef(null),m=o.useMemo(()=>({list:x,main:k,context:y}),[]),s=o.useCallback((c,f={})=>{const w=n?.(c)??c;r(w),e==="stack"&&(i.current=w,f.fromHistory||t?.push(w))},[t,n,e]),j=o.useCallback(()=>s("list"),[s]),v=o.useCallback(()=>s("main"),[s]),u=o.useCallback(()=>s("context"),[s]);return o.useLayoutEffect(()=>{if(e!=="stack"){i.current=null;return}const c=i.current;c&&(i.current=null,m[c].current?.focus())},[a,m,e]),o.useLayoutEffect(()=>{if(!(e!=="stack"||!t))return t.subscribe(c=>{s(c,{fromHistory:!0})})},[t,s,e]),{activePane:a,paneRefs:m,openList:j,openMain:v,openContext:u}}function he({listHeader:e,list:t,mainHeader:n,main:a,mode:r="auto",history:i,copy:x,className:k,pageType:y="collection",hasObjectCollection:m=!0}){const s=o.useContext(Q),{resolvedMode:j}=q({mode:r,pageType:y,hasObjectCollection:m}),v=z(r),u=s?v:j,c=y==="collection"&&m,{activePane:f,paneRefs:w,openList:C,openMain:A,openContext:S}=Z({resolvedMode:u,history:i,resolvePane:Y}),L=s?.onClose,O=o.useCallback(()=>{A(),L?.()},[A,L]),H=o.useMemo(()=>({mode:u,activePane:f,openList:C,openMain:O,openContext:S}),[f,S,C,O,u]),d=c&&u==="stack",M=!c||(s?u==="stack"&&!s.open:d&&f!=="list"),E=!s&&d&&f!=="main";return l.jsx(D.Provider,{value:H,children:l.jsx("section",{className:g("flex min-h-0 flex-1 flex-col bg-background",k),"data-workspace-layout":"two-pane","data-workspace-mode":u,children:l.jsxs("div",{className:g("grid min-h-0 flex-1",d||!c?"grid-cols-1":null),style:d||!c?void 0:X,"data-workspace-layout-mode":r,"data-workspace-object-column":c&&u==="split"?"shown":"hidden","data-workspace-active-pane":f,children:[l.jsxs("aside",{ref:w.list,className:g("min-h-0 flex-col overflow-hidden bg-layout-list-item @container",M?"hidden":"flex",d?"border-r-0":"border-r border-border"),"data-testid":"workspace-list-pane","data-workspace-pane":"list",hidden:M,tabIndex:d?-1:void 0,children:[l.jsx("header",{className:"h-12 shrink-0 border-b border-border bg-layout-list-header","data-workspace-list-header":"true",children:e}),l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:t})]}),l.jsxs("main",{ref:w.main,className:g("min-h-0 flex-col overflow-hidden bg-layout-content @container",E?"hidden":"flex"),"data-testid":"workspace-main-pane","data-workspace-pane":"main",hidden:E,inert:s?.open&&u==="stack"?!0:void 0,tabIndex:d?-1:void 0,children:[l.jsxs("header",{className:g("h-12 shrink-0 border-b border-border bg-layout-content",s?.headerLeading&&"flex min-w-0 items-center"),"data-workspace-main-header":"true",children:[s?.headerLeading?l.jsx("div",{className:"flex h-full shrink-0 items-center md:hidden","data-workspace-header-leading":!0,children:s.headerLeading}):null,s?.headerLeading?l.jsx("div",{className:"h-full min-w-0 flex-1",children:n}):n]}),l.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[d&&!s?l.jsx("button",{type:"button",className:"inline-flex items-center px-4 py-3 text-sm text-muted-foreground hover:text-foreground",onClick:C,children:x?.backToList??"返回列表"}):null,a]})]})]})})})}const h="/api/admin";async function ee(e={}){try{const t=await fetch(`${h}/status`,{signal:e.signal});if(t.ok)return await t.json()}catch(t){console.error("Failed to get admin status:",t)}return null}async function te(e={}){try{const t=await fetch(`${h}/config`,{signal:e.signal});if(t.ok)return await t.json()}catch(t){console.error("Failed to get admin config:",t)}return null}async function ne(e,t={}){try{const n=e?"?baseUrl="+encodeURIComponent(e):"",a=await fetch(h+"/public-ip"+n,{signal:t.signal});if(a.ok)return await a.json()}catch(n){console.error("Failed to get public ip check:",n)}return null}async function me(e){try{return(await fetch(`${h}/config`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({env:e})})).ok}catch(t){return console.error("Failed to update admin config:",t),!1}}async function we(){try{return(await fetch(`${h}/restart`,{method:"POST"})).ok}catch(e){return console.error("Failed to trigger restart:",e),!1}}async function ae(e={}){try{const t=await fetch("/service/status",{signal:e.signal});if(t.ok){const n=await t.json();if(Array.isArray(n))return n}}catch(t){console.error("Failed to get gateway status:",t)}return null}async function ge(e){try{const t=new URLSearchParams;e?.limit&&t.set("limit",e.limit.toString()),e?.level&&e.level!=="all"&&t.set("level",e.level),e?.source&&e.source!=="all"&&t.set("source",e.source);const n=t.toString(),a=n?`?${n}`:"";let r=await fetch(`/service/logs${a}`);if((r.status===404||r.status===405)&&(r=await fetch(`${h}/logs${a}`)),r.ok){const i=await r.json();return Array.isArray(i)?i:i.logs??[]}}catch(t){console.error("Failed to get logs:",t)}return[]}function oe(e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}/`:""}function re(e,t,n=""){return t?.baseUrl||oe(t?.fqdn)||e.CSS_BASE_URL||n}async function se(e={}){try{const t=await fetch(`${h}/ddns`,{signal:e.signal});if(t.ok)return await t.json()}catch(t){console.error("Failed to get ddns status:",t)}return null}async function ye(e={}){try{const t=await fetch("/provision/status",{signal:e.signal,credentials:"include",headers:{accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return{registered:n.registered===!0,managed:n.managed===!0,nodeId:b(n.nodeId),cloudUrl:b(n.cloudUrl),serviceProviderDomain:b(n.spDomain),publicUrl:b(n.publicUrl)}}catch(t){return console.error("Failed to get provision status:",t),null}}function b(e){return typeof e=="string"&&e.length>0?e:null}async function be(e={}){const[t,n,a,r]=await Promise.all([ae(e),ee(e),te(e),se(e)]),i=await ne(re(a?.env??{},r),e);return{servicesData:t,adminData:n,configData:a,ddnsData:r,publicCheck:i,checkedAt:new Date}}function xe(e){if(!["ArrowDown","ArrowUp","Home","End"].includes(e.key))return;const t=e.currentTarget.closest("[data-list-navigation]")??e.currentTarget.closest("nav");if(!t)return;const n=[...t.querySelectorAll('a[href]:not([aria-disabled="true"])')],a=n.indexOf(e.currentTarget);if(a<0||n.length===0)return;e.preventDefault();const r=e.key==="Home"?0:e.key==="End"?n.length-1:e.key==="ArrowDown"?(a+1)%n.length:(a-1+n.length)%n.length;n[r]?.focus()}const $="rounded-lg transition-colors",W="text-foreground hover:bg-accent/60",_="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function ke(e){return[$,_,e?"bg-accent text-accent-foreground":`text-foreground ${W}`,"relative flex h-10 w-10 items-center justify-center rounded-lg"].join(" ")}function je(e,t){const n=t?.compact===!0;return[$,_,e?"bg-accent text-accent-foreground":"",n?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",e?"font-medium":`${W} text-foreground`].join(" ")}export{de as D,he as T,Q as W,se as a,je as b,ge as c,te as d,me as e,be as f,ye as g,xe as h,ne as i,ke as j,fe as k,D as l,we as t,pe as u};
1
+ import{c as B}from"./createLucideIcon-BWelSi3L.js";import{r as o,j as l}from"./dashboard-vmne1ZE0.js";import{c as g}from"./button-WVnQUNG-.js";const V=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],de=B("database",V);function fe(e){if(!R(e))throw new Error("Applet layout descriptor must be an object");if(typeof e.type!="string")throw new Error("Applet layout descriptor type must be a string");switch(e.type){case"single-pane":case"two-pane":return P(e.context),e;case"three-pane":return P(e.context),e;default:throw new Error(`Unsupported applet layout type: ${e.type}`)}}function R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function P(e){if(e!==void 0){if(!R(e))throw new Error("Applet layout descriptor context must be an object");if("collapsible"in e&&typeof e.collapsible!="boolean")throw new Error("Applet layout descriptor context.collapsible must be a boolean");if("initiallyCollapsed"in e&&typeof e.initiallyCollapsed!="boolean")throw new Error("Applet layout descriptor context.initiallyCollapsed must be a boolean")}}const G=184,p={narrow:768,wideObjects:1100};function K(e){const{pageType:t,contentWidth:n}=e,a=e.hasObjectCollection===!0;if(!Number.isFinite(n)||n<=0)throw new Error("Applet pane plan needs a positive contentWidth");return n<p.narrow?{pageType:t,navigation:"task-bar",panes:"single",showObjectColumn:!1}:n>=p.wideObjects&&t==="collection"&&a?{pageType:t,navigation:"rail",panes:"list-detail",showObjectColumn:!0}:{pageType:t,navigation:"rail",panes:t==="collection"&&n<p.wideObjects?"stack":"single",showObjectColumn:!1}}const D=o.createContext(null);function pe(){const e=o.useContext(D);if(!e)throw new Error("useWorkspaceLayout must be used inside TwoPaneLayout");return e}const Q=o.createContext(void 0),N="(max-width: 767px)",X={gridTemplateColumns:"210px minmax(0, 1fr)"};function Y(e){return e==="context"?"main":e}function I(e){if(typeof window>"u"||typeof window.matchMedia!="function")return()=>{};const t=window.matchMedia(N);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function U(){return typeof window>"u"||typeof window.matchMedia!="function"?"split":window.matchMedia(N).matches?"stack":"split"}function F(){return"split"}function z(e){const t=o.useSyncExternalStore(I,U,F);return e==="auto"?t:e}const T=`(min-width: ${p.wideObjects+G}px)`;function J(){return o.useSyncExternalStore(e=>{if(typeof window>"u"||typeof window.matchMedia!="function")return()=>{};const t=window.matchMedia(T);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},()=>typeof window>"u"||typeof window.matchMedia!="function"?!0:window.matchMedia(T).matches,()=>!0)}function q(e){const t=o.useSyncExternalStore(I,U,F)==="stack",a=J()?p.wideObjects:t?p.narrow-1:p.narrow,r=K({pageType:e.pageType,contentWidth:a,hasObjectCollection:e.hasObjectCollection}),i=r.panes==="list-detail"?"split":"stack";return{resolvedMode:e.mode==="auto"?i:e.mode,showObjectColumn:r.showObjectColumn}}function Z({resolvedMode:e,history:t,resolvePane:n}){const[a,r]=o.useState("list"),i=o.useRef(null),x=o.useRef(null),k=o.useRef(null),y=o.useRef(null),m=o.useMemo(()=>({list:x,main:k,context:y}),[]),s=o.useCallback((c,f={})=>{const w=n?.(c)??c;r(w),e==="stack"&&(i.current=w,f.fromHistory||t?.push(w))},[t,n,e]),j=o.useCallback(()=>s("list"),[s]),v=o.useCallback(()=>s("main"),[s]),u=o.useCallback(()=>s("context"),[s]);return o.useLayoutEffect(()=>{if(e!=="stack"){i.current=null;return}const c=i.current;c&&(i.current=null,m[c].current?.focus())},[a,m,e]),o.useLayoutEffect(()=>{if(!(e!=="stack"||!t))return t.subscribe(c=>{s(c,{fromHistory:!0})})},[t,s,e]),{activePane:a,paneRefs:m,openList:j,openMain:v,openContext:u}}function he({listHeader:e,list:t,mainHeader:n,main:a,mode:r="auto",history:i,copy:x,className:k,pageType:y="collection",hasObjectCollection:m=!0}){const s=o.useContext(Q),{resolvedMode:j}=q({mode:r,pageType:y,hasObjectCollection:m}),v=z(r),u=s?v:j,c=y==="collection"&&m,{activePane:f,paneRefs:w,openList:C,openMain:A,openContext:S}=Z({resolvedMode:u,history:i,resolvePane:Y}),L=s?.onClose,O=o.useCallback(()=>{A(),L?.()},[A,L]),H=o.useMemo(()=>({mode:u,activePane:f,openList:C,openMain:O,openContext:S}),[f,S,C,O,u]),d=c&&u==="stack",M=!c||(s?u==="stack"&&!s.open:d&&f!=="list"),E=!s&&d&&f!=="main";return l.jsx(D.Provider,{value:H,children:l.jsx("section",{className:g("flex min-h-0 flex-1 flex-col bg-background",k),"data-workspace-layout":"two-pane","data-workspace-mode":u,children:l.jsxs("div",{className:g("grid min-h-0 flex-1",d||!c?"grid-cols-1":null),style:d||!c?void 0:X,"data-workspace-layout-mode":r,"data-workspace-object-column":c&&u==="split"?"shown":"hidden","data-workspace-active-pane":f,children:[l.jsxs("aside",{ref:w.list,className:g("min-h-0 flex-col overflow-hidden bg-layout-list-item @container",M?"hidden":"flex",d?"border-r-0":"border-r border-border"),"data-testid":"workspace-list-pane","data-workspace-pane":"list",hidden:M,tabIndex:d?-1:void 0,children:[l.jsx("header",{className:"h-12 shrink-0 border-b border-border bg-layout-list-header","data-workspace-list-header":"true",children:e}),l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:t})]}),l.jsxs("main",{ref:w.main,className:g("min-h-0 flex-col overflow-hidden bg-layout-content @container",E?"hidden":"flex"),"data-testid":"workspace-main-pane","data-workspace-pane":"main",hidden:E,inert:s?.open&&u==="stack"?!0:void 0,tabIndex:d?-1:void 0,children:[l.jsxs("header",{className:g("h-12 shrink-0 border-b border-border bg-layout-content",s?.headerLeading&&"flex min-w-0 items-center"),"data-workspace-main-header":"true",children:[s?.headerLeading?l.jsx("div",{className:"flex h-full shrink-0 items-center md:hidden","data-workspace-header-leading":!0,children:s.headerLeading}):null,s?.headerLeading?l.jsx("div",{className:"h-full min-w-0 flex-1",children:n}):n]}),l.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[d&&!s?l.jsx("button",{type:"button",className:"inline-flex items-center px-4 py-3 text-sm text-muted-foreground hover:text-foreground",onClick:C,children:x?.backToList??"返回列表"}):null,a]})]})]})})})}const h="/api/admin";async function ee(e={}){try{const t=await fetch(`${h}/status`,{signal:e.signal});if(t.ok)return await t.json()}catch(t){console.error("Failed to get admin status:",t)}return null}async function te(e={}){try{const t=await fetch(`${h}/config`,{signal:e.signal});if(t.ok)return await t.json()}catch(t){console.error("Failed to get admin config:",t)}return null}async function ne(e,t={}){try{const n=e?"?baseUrl="+encodeURIComponent(e):"",a=await fetch(h+"/public-ip"+n,{signal:t.signal});if(a.ok)return await a.json()}catch(n){console.error("Failed to get public ip check:",n)}return null}async function me(e){try{return(await fetch(`${h}/config`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({env:e})})).ok}catch(t){return console.error("Failed to update admin config:",t),!1}}async function we(){try{return(await fetch(`${h}/restart`,{method:"POST"})).ok}catch(e){return console.error("Failed to trigger restart:",e),!1}}async function ae(e={}){try{const t=await fetch("/service/status",{signal:e.signal});if(t.ok){const n=await t.json();if(Array.isArray(n))return n}}catch(t){console.error("Failed to get gateway status:",t)}return null}async function ge(e){try{const t=new URLSearchParams;e?.limit&&t.set("limit",e.limit.toString()),e?.level&&e.level!=="all"&&t.set("level",e.level),e?.source&&e.source!=="all"&&t.set("source",e.source);const n=t.toString(),a=n?`?${n}`:"";let r=await fetch(`/service/logs${a}`);if((r.status===404||r.status===405)&&(r=await fetch(`${h}/logs${a}`)),r.ok){const i=await r.json();return Array.isArray(i)?i:i.logs??[]}}catch(t){console.error("Failed to get logs:",t)}return[]}function oe(e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}/`:""}function re(e,t,n=""){return t?.baseUrl||oe(t?.fqdn)||e.CSS_BASE_URL||n}async function se(e={}){try{const t=await fetch(`${h}/ddns`,{signal:e.signal});if(t.ok)return await t.json()}catch(t){console.error("Failed to get ddns status:",t)}return null}async function ye(e={}){try{const t=await fetch("/provision/status",{signal:e.signal,credentials:"include",headers:{accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return{registered:n.registered===!0,managed:n.managed===!0,nodeId:b(n.nodeId),cloudUrl:b(n.cloudUrl),serviceProviderDomain:b(n.spDomain),publicUrl:b(n.publicUrl)}}catch(t){return console.error("Failed to get provision status:",t),null}}function b(e){return typeof e=="string"&&e.length>0?e:null}async function be(e={}){const[t,n,a,r]=await Promise.all([ae(e),ee(e),te(e),se(e)]),i=await ne(re(a?.env??{},r),e);return{servicesData:t,adminData:n,configData:a,ddnsData:r,publicCheck:i,checkedAt:new Date}}function xe(e){if(!["ArrowDown","ArrowUp","Home","End"].includes(e.key))return;const t=e.currentTarget.closest("[data-list-navigation]")??e.currentTarget.closest("nav");if(!t)return;const n=[...t.querySelectorAll('a[href]:not([aria-disabled="true"])')],a=n.indexOf(e.currentTarget);if(a<0||n.length===0)return;e.preventDefault();const r=e.key==="Home"?0:e.key==="End"?n.length-1:e.key==="ArrowDown"?(a+1)%n.length:(a-1+n.length)%n.length;n[r]?.focus()}const $="rounded-lg transition-colors",W="text-foreground hover:bg-accent/60",_="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function ke(e){return[$,_,e?"bg-accent text-accent-foreground":`text-foreground ${W}`,"relative flex h-[40px] w-[40px] items-center justify-center rounded-lg"].join(" ")}function je(e,t){const n=t?.compact===!0;return[$,_,e?"bg-accent text-accent-foreground":"",n?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",e?"font-medium":`${W} text-foreground`].join(" ")}export{de as D,he as T,Q as W,se as a,je as b,ge as c,te as d,me as e,be as f,ye as g,xe as h,ne as i,ke as j,fe as k,D as l,we as t,pe as u};
@@ -0,0 +1,8 @@
1
+ import{P as U,r as Yt,a as Jt,b as Qt,c as Te,s as Qe,d as Zt,e as Tt}from"./layout-DB3pMyTl.js";class Ue{}class Et extends Ue{constructor(e){super(),this.path=e,this.type="ref"}}class Z extends Ue{constructor(e){super(),this.value=e,this.type="val"}}class N extends Ue{constructor(e,t){super(),this.name=e,this.args=t,this.type="func"}}function Ze(s,e){if(typeof s==typeof e){if(typeof s=="number"&&typeof e=="number"){const t=Number.isNaN(s),n=Number.isNaN(e);if(t||n)return t&&n?0:t?1:-1}return s<e?-1:s>e?1:0}return typeof s=="string"?-1:1}Xt();function Xt(){const s=new WeakMap,e=Symbol();try{if(s.set(e,0),s.get(e)===0)return s}catch{}return new Map}function es(){return Math.random()*(2**31-1)>>>0}const ts=es(),Xe=new WeakMap;function ss(s){ns(s)}let et=1;function ns(s){let e=Xe.get(s);return e===void 0&&(e=et^ts,et++,Xe.set(s,e)),e}function le(){const s=typeof globalThis<"u"?globalThis.crypto:void 0;if(s&&typeof s.randomUUID=="function")return s.randomUUID();if(s&&typeof s.getRandomValues=="function"){const e=s.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[];for(let n=0;n<16;n++)t.push(e[n].toString(16).padStart(2,"0"));return t.slice(0,4).join("")+"-"+t.slice(4,6).join("")+"-"+t.slice(6,8).join("")+"-"+t.slice(8,10).join("")+"-"+t.slice(10,16).join("")}throw new Error("No secure random number generator available: neither crypto.randomUUID nor crypto.getRandomValues is defined in this environment.")}class G extends Error{constructor(e){super(e),this.name="TanStackDBError"}}class tt extends G{constructor(e,t,n){const i=`${e==="insert"?"Insert":"Update"} validation failed: ${t.map(r=>`
2
+ - ${r.message} - path: ${r.path}`).join("")}`;super(n||i),this.name="SchemaValidationError",this.type=e,this.issues=t}}class te extends G{constructor(e){super(e),this.name="CollectionConfigurationError"}}class is extends te{constructor(){super("Collection requires a config")}}class rs extends te{constructor(){super("Collection requires a sync config")}}class os extends te{constructor(){super("Schema must implement the standard-schema interface")}}class st extends te{constructor(){super("Schema validation must be synchronous")}}class re extends G{constructor(e){super(e),this.name="CollectionStateError"}}class as extends re{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}}class cs extends re{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}}class ls extends re{constructor(){super("Collection is in error state")}}class us extends re{constructor(){super("Active subscribers count is negative - this should never happen")}}class q extends G{constructor(e){super(e),this.name="CollectionOperationError"}}class ds extends q{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}}class hs extends q{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 fs extends q{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}}class ps extends q{constructor(e,t,n){const i=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${t}"`;n?.hasCustomGetKey&&n.hasDistinct?super(`${i}. 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(`${i}. 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(i)}}class ys extends q{constructor(){super("The first argument to update is missing")}}class ms extends q{constructor(){super("No keys were passed to update")}}class gs extends q{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}}class Ss extends q{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 bs extends q{constructor(){super("No keys were passed to delete")}}class ws extends q{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}}class Ve extends G{constructor(e){super(e),this.name="MissingHandlerError"}}class vs extends Ve{constructor(){super("Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.")}}class ks extends Ve{constructor(){super("Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.")}}class Cs extends Ve{constructor(){super("Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.")}}class Y extends G{constructor(e){super(e),this.name="TransactionError"}}class Rs extends Y{constructor(){super("mutationFn is required when creating a transaction")}}class Os extends Y{constructor(){super("You can no longer call .mutate() as the transaction is no longer pending")}}class Ts extends Y{constructor(){super("You can no longer call .rollback() as the transaction is already completed")}}class Es extends Y{constructor(){super("You can no longer call .commit() as the transaction is no longer pending")}}class Ee extends Y{constructor(){super("No pending sync transaction to write to")}}class xe extends Y{constructor(){super("The pending sync transaction is already committed, you can't still write to it.")}}class xs extends Y{constructor(){super("No pending sync transaction to commit")}}class Ds extends Y{constructor(){super("The pending sync transaction is already committed, you can't commit it again.")}}class $e extends G{constructor(e){super(e),this.name="QueryCompilationError"}}class Is extends $e{constructor(e){super(`Unknown expression type: ${e}`)}}class Ps extends $e{constructor(){super("Reference path cannot be empty")}}class As extends $e{constructor(e){super(`Unknown function: ${e}`)}}class nt extends G{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 it extends Error{constructor(){super("Sync transaction was aborted before application"),this.name="AbortError"}}class _s extends Error{constructor(){super("Collection preload was abandoned during cleanup"),this.name="AbortError"}}class z extends Error{constructor(){super("Load subset operation was aborted before its result became visible"),this.name="AbortError"}}function F(s,e){return me(s,e,new Map)}function rt(s){const e=Object.keys(s);for(const t of Object.getOwnPropertySymbols(s))Object.prototype.propertyIsEnumerable.call(s,t)&&e.push(t);return e}function me(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 i=Array.from(s.entries()).every(([r,o])=>e.has(r)&&me(o,e.get(r),t));return t.delete(s),i}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),i=Array.from(e);if(n.every(o=>typeof o!="object"))return t.delete(s),n.every(o=>e.has(o));const r=n.length===i.length;return t.delete(s),r}if(e instanceof Set)return!1;if(ArrayBuffer.isView(s)&&ArrayBuffer.isView(e)&&!(s instanceof DataView)&&!(e instanceof DataView)){const n=s,i=e;if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++)if(n[r]!==i[r])return!1;return!0}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)&&!ArrayBuffer.isView(s))return!1;if(j(s)&&j(e)){const n=s[Symbol.toStringTag],i=e[Symbol.toStringTag];return n!==i?!1:typeof s.equals=="function"?s.equals(e):s.toString()===e.toString()}if(j(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((i,r)=>me(i,e[r],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=rt(s),i=rt(e);if(n.length!==i.length)return t.delete(s),!1;const r=n.every(o=>Object.prototype.propertyIsEnumerable.call(e,o)&&me(s[o],e[o],t));return t.delete(s),r}return!1}const Ms=new Set(["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"]);function j(s){if(s==null||typeof s!="object")return!1;const e=s[Symbol.toStringTag];return typeof e=="string"&&Ms.has(e)}const Ce={direction:"asc",nulls:"first",stringSort:"locale"};function Ls(){const s=new WeakMap;let e,t,n,i=0;const r=(o,a)=>{let c=o.get(a);return c===void 0&&(c=++i,o.set(a,c)),c};return o=>{n??=Fs();let a;if(typeof o=="symbol"){const c=Symbol.keyFor(o);c===void 0?(e??=Ks(),a=r(e,o)):(t??=new Map,a=r(t,c))}else a=r(s,o);return["runtimeReference",n,a]}}function Ks(){const s=new WeakMap,e=Symbol();try{if(s.set(e,0),s.get(e)===0)return s}catch{}return new Map}let ot;function at(s){return ot??=Ls(),ot(s)}function Fs(){const s=new Uint32Array(4),e=Reflect.get(globalThis,"crypto");return typeof e?.getRandomValues=="function"?(e.getRandomValues(s),Array.from(s,t=>t.toString(36)).join("-")):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}const De=new WeakMap;let Us=1;function ct(s){if(De.has(s))return De.get(s);const e=Us++;return De.set(s,e),e}function P(s){return typeof s=="number"&&Number.isNaN(s)||s instanceof Date&&Number.isNaN(s.getTime())}const ze=(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;const i=P(s),r=P(e);if(i&&r)return 0;if(i)return 1;if(r)return-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 d=0;d<Math.min(s.length,e.length);d++){const h=ze(s[d],e[d],t);if(h!==0)return h}return s.length-e.length}if(s instanceof Date&&e instanceof Date)return s.getTime()-e.getTime();if(j(s)&&j(e))return It(s,e);const o=typeof s=="symbol",a=typeof e=="symbol";if(o&&a)return s===e?0:at(s)[2]-at(e)[2];if(o)return 1;if(a)return-1;const c=typeof s=="object",u=typeof e=="object";if(c||u){if(c&&u){const d=ct(s),h=ct(e);return d-h}if(c)return 1;if(u)return-1}return s<e?-1:s>e?1:0},Vs=(s,e,t)=>ze(e,s,{...t,nulls:t.nulls==="first"?"last":"first"});function xt(s){return(e,t)=>s.direction==="asc"?ze(e,t,s):Vs(e,t,s)}function we(s){return s instanceof Uint8Array||typeof Buffer<"u"&&s instanceof Buffer}function $s(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 Dt="\0tanstack-db:";function Me(s,e){return`${Dt}${s}:${e}`}function zs(s){let e="";for(let t=0;t<s.byteLength;t++)e+=String.fromCharCode(s[t]);return Me("binary",e)}function js(s){return typeof s=="string"?s.startsWith(Dt)?Me("string",s):s:typeof s!="object"||s===null?s:s instanceof Date?s.getTime():j(s)?Me("temporal",`${s[Symbol.toStringTag]}:${s.toString()}`):we(s)?zs(s):s}const lt=new Map;function It(s,e){const t=s[Symbol.toStringTag],n=e[Symbol.toStringTag];if(t!==n)throw new TypeError(`Cannot order Temporal values of different types: ${t} vs ${n}`);let i=lt.get(t);if(i===void 0){const r=s.constructor.compare;i=typeof r=="function"?r:null,lt.set(t,i)}if(i===null)throw new TypeError(`${t} has no defined ordering`);return i(s,e)}function pe(s,e){return j(s)&&j(e)?It(s,e):s<e?-1:s>e?1:0}function qs(s,e){return s===e?!0:we(s)&&we(e)?$s(s,e):!1}function _(s){return s==null}function ye(s){return we(s)?s:js(s)}function ut(s,e){return P(s)||P(e)?P(s)&&P(e):qs(s,e)}function Ie(s){if(s instanceof Date)return Number.isNaN(s.getTime())?null:s;if(typeof s=="string"||typeof s=="number"){const e=new Date(s);return Number.isNaN(e.getTime())?null:e}return null}function Ns(s,e){return s==="%Y-%m-%d"?e.toISOString().slice(0,10):e.toISOString()}function Ws(s){return s===!0}function Bs(s,e=!1){return je(s,e)}function Pt(s){return je(s,!0)}function je(s,e){switch(s.type){case"val":{const t=s.value;return()=>t}case"ref":return e?Gs(s):Hs(s);case"func":return Ys(s,e);default:throw new Is(s.type)}}function Hs(s){const[e,...t]=s.path;if(!e)throw new Ps;if(e==="$selected"){if(t.length===0)return i=>i.$selected;if(t.length===1){const i=t[0];return r=>r.$selected?.[i]}else return i=>{const r=i.$selected;if(r===void 0)return;let o=r;for(const a of t){if(o==null)return o;o=o[a]}return o}}const n=e;if(t.length===0)return i=>i[n];if(t.length===1){const i=t[0];return r=>r[n]?.[i]}else return i=>{const r=i[n];if(r===void 0)return;let o=r;for(const a of t){if(o==null)return o;o=o[a]}return o}}function Gs(s){const e=s.path;return t=>{let n=t;for(const i of e){if(n==null)return n;n=n[i]}return n}}function Ys(s,e){const t=s.args.map(n=>je(n,e));switch(s.name){case"eq":{const n=t[0],i=t[1];return r=>{const o=ye(n(r)),a=ye(i(r));return _(o)||_(a)?null:ut(o,a)}}case"gt":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:P(o)||P(a)?P(o)&&!P(a):pe(o,a)>0}}case"gte":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:P(o)||P(a)?P(o):pe(o,a)>=0}}case"lt":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:P(o)||P(a)?P(a)&&!P(o):pe(o,a)<0}}case"lte":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:P(o)||P(a)?P(a):pe(o,a)<=0}}case"and":return n=>{let i=!1;for(const r of t){const o=r(n);if(o===!1)return!1;_(o)&&(i=!0)}return i?null:!0};case"or":return n=>{let i=!1;for(const r of t){const o=r(n);if(o===!0)return!0;_(o)&&(i=!0)}return i?null:!1};case"not":{const n=t[0];return i=>{const r=n(i);return _(r)?null:!r}}case"in":{const n=t[0],i=t[1];return r=>{const o=ye(n(r)),a=i(r);return _(o)?null:Array.isArray(a)?a.some(c=>ut(ye(c),o)):!1}}case"like":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:dt(o,a,!1)}}case"ilike":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:dt(o,a,!0)}}case"upper":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"?r.toUpperCase():r}}case"lower":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"?r.toLowerCase():r}}case"length":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"||Array.isArray(r)?r.length:0}}case"concat":return n=>t.map(i=>{const r=i(n);try{return String(r??"")}catch{try{return JSON.stringify(r)||""}catch{return"[object]"}}}).join("");case"coalesce":return n=>{for(const i of t){const r=i(n);if(r!=null)return r}return null};case"caseWhen":{const n=t.length%2===1,i=Math.floor(t.length/2);if(t.length<2)throw new Error("caseWhen() requires at least two arguments");return r=>{for(let o=0;o<i;o++){const a=t[o*2];if(Js(a(r))){const c=t[o*2+1];return c(r)}}return n?t[t.length-1](r):null}}case"add":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)+(a??0)}}case"subtract":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)-(a??0)}}case"multiply":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)*(a??0)}}case"divide":{const n=t[0],i=t[1];return r=>{const o=n(r),c=i(r)??0;return c!==0?(o??0)/c:null}}case"date":{const n=t[0];return i=>{const r=n(i),o=Ie(r);return o?o.toISOString().slice(0,10):null}}case"datetime":{const n=t[0];return i=>{const r=n(i),o=Ie(r);return o?o.toISOString():null}}case"strftime":{const n=t[0],i=t[1];return r=>{const o=n(r);if(typeof o!="string")return null;const a=i(r),c=Ie(a);return c?Ns(o,c):null}}case"isUndefined":{const n=t[0];return i=>n(i)===void 0}case"isNull":{const n=t[0];return i=>n(i)===null}default:throw new As(s.name)}}function Js(s){return s==null||s===!1?!1:s===!0?!0:typeof s=="number"?s!==0&&!Number.isNaN(s):typeof s=="bigint"?s!==0n:!!s}function dt(s,e,t){if(typeof s!="string"||typeof e!="string")return!1;const n=t?s.toLowerCase():s;let r=(t?e.toLowerCase():e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return r=r.replace(/%/g,".*"),r=r.replace(/_/g,"."),new RegExp(`^${r}$`,"s").test(n)}class Qs{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)}take(e,t,n){return this.originalIndex.takeReversed(e,t,n)}takeFromStart(e,t){return this.originalIndex.takeReversedFromEnd(e,t)}supports(e){return this.originalIndex.supports(e)}get supportsRangeOptimization(){return this.originalIndex.supportsRangeOptimization}canOptimizeRangeFor(e){return this.originalIndex.canOptimizeRangeFor?.(e)??!0}get keyCount(){return this.originalIndex.keyCount}}function ht(s,e,t,n,i){const r=s;return{...s,$synced:r.$synced??n(),$origin:r.$origin??i(),$key:r.$key??e,$collectionId:r.$collectionId??t}}const Zs=["$synced","$origin","$key","$collectionId"];function Xs(s){return Zs.includes(s)}function At(s){return s.some(e=>Xs(e))}function Re(s,e,t){if(At(e))return;const n=t??{...Ce,...s.compareOptions};for(const i of s.indexes.values())if(i.matchesField(e)&&i.matchesCompareOptions(n))return i.matchesDirection(n.direction)?i:new Qs(i)}function en(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 i of e)s[t].has(i)&&n.add(i);e=n}return e}function tn(s){const e=new Set;for(const t of s)for(const n of t)e.add(n);return e}function qe(s){return s!=null}function sn(s){return{...Ce,...s.compareOptions}.stringSort==="locale"}function nn(s,e){switch(typeof s){case"number":case"bigint":case"boolean":return!1;case"string":return sn(e);case"symbol":return!0;case"object":return s===null?!1:!(s instanceof Date);default:return!1}}function _t(s,e,t){return!nn(s,t)&&e.supportsRangeOptimization&&(e.canOptimizeRangeFor?.(s)??!0)}function rn(s,e){return Ne(s,e)}function Ne(s,e){if(s.type==="func")switch(s.name){case"eq":case"gt":case"gte":case"lt":case"lte":return an(s,e);case"and":return cn(s,e);case"or":return ln(s,e);case"in":return un(s,e)}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function on(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set};const t=new Map;for(const[n,i]of s.args.entries())if(i.type==="func"&&["gt","gte","lt","lte"].includes(i.name)){const r=i;if(r.args.length===2){const o=r.args[0],a=r.args[1];let c=null,u=null,d=r.name;if(o.type==="ref"&&a.type==="val")c=o,u=a;else if(o.type==="val"&&a.type==="ref")switch(c=a,u=o,d){case"gt":d="lt";break;case"gte":d="lte";break;case"lt":d="gt";break;case"lte":d="gte";break}if(c&&u){const l=c.path.join("."),f=u.value;t.has(l)||t.set(l,[]),t.get(l).push({operation:d,value:f,argIndex:n})}}}for(const[n,i]of t)if(i.length>=2){const r=n.split("."),o=Re(e,r);if(o&&i.some(a=>!_t(a.value,o,e)))continue;if(o&&o.supports("gt")&&o.supports("lt")){const a=xt({...Ce,...e.compareOptions,direction:"asc"});let c,u,d=!1,h=!1,l=!0,f=!0,p=!1;for(const{operation:w,value:C}of i){if(!qe(C)){p=!0;continue}switch(w){case"gt":case"gte":{const v=d?a(C,c):1;v>0?(c=C,d=!0,l=w==="gte"):v===0&&w==="gt"&&(l=!1);break}case"lt":case"lte":{const v=h?a(C,u):-1;v<0?(u=C,h=!0,f=w==="lte"):v===0&&w==="lt"&&(f=!1);break}}}const y={};return d&&(y.from=c,y.fromInclusive=l),h&&(y.to=u,y.toInclusive=f),{canOptimize:!0,matchingKeys:o.rangeQuery(y),isExact:d&&!p,coveredArgIndices:new Set(i.map(w=>w.argIndex))}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set}}function an(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=s.args[0],n=s.args[1];let i=null,r=null,o=s.name;if(t.type==="ref"&&n.type==="val")i=t,r=n;else if(t.type==="val"&&n.type==="ref")switch(i=n,r=t,o){case"gt":o="lt";break;case"gte":o="lte";break;case"lt":o="gt";break;case"lte":o="gte";break}if(i&&r){const a=i.path,c=Re(e,a);if(c){const u=r.value,d=o;if(!c.supports(d))return{canOptimize:!1,matchingKeys:new Set,isExact:!1};if((o==="gt"||o==="gte"||o==="lt"||o==="lte")&&!_t(u,c,e))return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const h=c.lookup(d,u),l=o==="lt"||o==="lte"?!1:qe(u);return{canOptimize:!0,matchingKeys:h,isExact:l}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function cn(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=on(s,e),n=t.canOptimize?t.coveredArgIndices:new Set,i=[];t.canOptimize&&i.push(t);let r=t.canOptimize?t.isExact:!0;for(const[o,a]of s.args.entries()){if(n.has(o))continue;const c=Ne(a,e);c.canOptimize?(i.push(c),c.isExact||(r=!1)):r=!1}if(i.length>0){const o=i.map(c=>c.matchingKeys);return{canOptimize:!0,matchingKeys:en(o),isExact:r}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function ln(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=[];for(const r of s.args){const o=Ne(r,e);if(!o.canOptimize)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};t.push(o)}const n=t.map(r=>r.matchingKeys);return{canOptimize:!0,matchingKeys:tn(n),isExact:t.every(r=>r.isExact)}}function un(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=s.args[0],n=s.args[1];if(t.type==="ref"&&n.type==="val"&&Array.isArray(n.value)){const i=t.path,r=n.value,o=Re(e,i),a=r.every(c=>qe(c));if(o){if(o.supports("in"))return{canOptimize:!0,matchingKeys:o.lookup("in",r),isExact:a};if(o.supports("eq")){const c=new Set;for(const u of r){const d=o.lookup("eq",u);for(const h of d)c.add(h)}return{canOptimize:!0,matchingKeys:c,isExact:a}}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function Mt(s){return s.config.autoIndex==="eager"}function Lt(s,e,t,n,i){if(At(e)||!Mt(t))return;const r=n??{...Ce,...t.compareOptions};if(!Array.from(t.indexes.values()).find(a=>a.matchesField(e)&&a.matchesCompareOptions(r)))try{t.createIndex(a=>{let c=a;for(const u of e)c=c[u];return c},{name:`auto:${e.join(".")}`,options:i?{compareFn:i,compareOptions:r}:{}})}catch(a){console.warn(`${t.id?`[${t.id}] `:""}Failed to create auto-index for field path "${e.join(".")}":`,a)}}function dn(s,e){if(!Mt(e))return;const t=hn(s);for(const{fieldName:n,fieldPath:i}of t)Lt(n,i,e)}function hn(s){const e=[];function t(n){if(n.type!=="func")return;const i=n;if(i.name==="and"){for(const u of i.args)t(u);return}if(!["eq","gt","gte","lt","lte","in"].includes(i.name)||i.args.length<1||i.args[0].type!=="ref")return;const a=i.args[0].path;if(a.length===0)return;const c=a.join("_");e.push({fieldName:c,fieldPath:a})}return t(s),e}function fn(s,e){return pn(s,e.compareOptions)}function pn(s,e){return s.compareOptions.stringSort===void 0?{...e,direction:s.compareOptions.direction,nulls:s.compareOptions.nulls}:s.compareOptions}function yn(s,e={}){const t=n=>{const i=[];for(const[r,o]of s.entries())(n?.(o)??!0)&&i.push({type:"insert",key:r,value:o});return i};if(e.limit!==void 0&&!e.orderBy)throw new Error("limit cannot be used without orderBy");if(e.orderBy){const n=e.where?se(e.where):void 0,i=gn(s,e.orderBy,e.limit,n,e.optimizedOnly);if(i===void 0)return;const r=[];for(const o of i){const a=s.get(o);a!==void 0&&r.push({type:"insert",key:o,value:a})}return r}if(!e.where)return t();try{const n=e.where,i=rn(n,s);if(i.canOptimize){const r=i.isExact?void 0:se(n),o=[];for(const a of i.matchingKeys){const c=s.get(a);c!==void 0&&(r?.(c)??!0)&&o.push({type:"insert",key:a,value:c})}return o}else{if(e.optimizedOnly)return;const r=se(n);return t(r)}}catch(n){console.warn(`${s.id?`[${s.id}] `:""}Error processing where clause, falling back to full scan:`,n);const i=se(e.where);return e.optimizedOnly?void 0:t(i)}}function se(s){const e=Pt(s);return t=>{try{const n=e(t);return Ws(n)}catch{return!1}}}function mn(s,e){const t=se(e.whereExpression);return n=>{const i=[];for(const r of n)if(r.type==="insert")t(r.value)&&i.push(r);else if(r.type==="update"){const o=t(r.value),a=r.previousValue?t(r.previousValue):!1;o&&a?i.push(r):o&&!a?i.push({...r,type:"insert"}):!o&&a&&i.push({...r,type:"delete",value:r.previousValue})}else t(r.value)&&i.push(r);return i.length>0||n.length===0?(s(i),!0):!1}}function gn(s,e,t,n,i){if(e.length===1){const c=e[0],u=c.expression;if(u.type==="ref"){const h=u.path,l=fn(c,s);Lt(h[0],h,s,l);const f=Re(s,h,l);if(f&&f.supports("gt")){const p=y=>{const b=s.get(y);return b===void 0?!1:n?.(b)??!0};return f.takeFromStart(t??f.keyCount,p)}}}if(i)return;const r=[];for(const[c,u]of s.entries())(n?.(u)??!0)&&r.push({key:c,value:u});const o=(c,u)=>{for(const d of e){const h=xt(d.compareOptions),l=ft(c.value,d.expression),f=ft(u.value,d.expression),p=h(l,f);if(p!==0)return p}return 0};r.sort(o);const a=r.map(c=>c.key);return t!==void 0?a.slice(0,t):a}function ft(s,e){if(e.type==="ref"){const t=e;let n=s;for(const i of t.path)n=n?.[i];return n}else return e.type==="val"?e.value:Pt(e)(s)}class pt{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,t){let n=0,i=this.sortedKeys.length;if(!this.comparator){for(;n<i;){const r=Math.floor((n+i)/2),o=this.sortedKeys[r],a=Ze(e,o);if(a<0)i=r;else if(a>0)n=r+1;else return r}return n}for(;n<i;){const r=Math.floor((n+i)/2),o=this.sortedKeys[r],a=this.map.get(o),c=this.comparator(t,a);if(c<0)i=r;else if(c>0)n=r+1;else{const u=Ze(e,o);if(u<0)i=r;else if(u>0)n=r+1;else return r}}return n}set(e,t){if(this.map.has(e)){const i=this.map.get(e),r=this.indexOf(e,i);this.sortedKeys.splice(r,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)}}const ge="__tanstack_db_direct";class Sn{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.hydrationSeedKeys=new Set,this.hydratedKeys=new Set,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.pendingOptimisticUpserts=new Map,this.pendingOptimisticDeletes=new Set,this.pendingOptimisticDirectUpserts=new Set,this.pendingOptimisticDirectDeletes=new Set,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.virtualPropsCache=new WeakMap,this.size=0,this.preSyncVisibleState=new Map,this.preSyncVirtualState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isDrainingSyncTransactions=!1,this.syncSessionGeneration=0,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{if(this.isDrainingSyncTransactions)return;this.isDrainingSyncTransactions=!0;let t=!1,n;try{let i;do i=this.commitNextPendingTransactionBatch(),i.failure&&!t&&(t=!0,n=i.failure.error);while(i.processed)}finally{this.isDrainingSyncTransactions=!1}if(t)throw n},this.config=e,this.transactions=new pt((t,n)=>t.compareCreatedAt(n)),this.syncedData=new pt(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this._events=e.events}isRowSynced(e){return this.isLocalOnly?!0:!this.optimisticUpserts.has(e)&&!this.optimisticDeletes.has(e)}getRowOrigin(e){return this.isLocalOnly||this.optimisticUpserts.has(e)||this.optimisticDeletes.has(e)?"local":this.rowOrigins.get(e)??"remote"}createVirtualPropsSnapshot(e,t){return{$synced:t?.$synced??this.isRowSynced(e),$origin:t?.$origin??this.getRowOrigin(e),$key:t?.$key??e,$collectionId:t?.$collectionId??this.collection.id}}getVirtualPropsSnapshotForState(e,t){if(this.isLocalOnly)return this.createVirtualPropsSnapshot(e,{$synced:!0,$origin:"local"});const n=t?.optimisticUpserts??this.optimisticUpserts,i=t?.optimisticDeletes??this.optimisticDeletes,r=n.has(e)||i.has(e)||t?.completedOptimisticKeys?.has(e)===!0;return this.createVirtualPropsSnapshot(e,{$synced:!r,$origin:r?"local":(t?.rowOrigins??this.rowOrigins).get(e)??"remote"})}snapshotRowOriginsForKeys(e){const t=new Map;for(const n of e){const i=this.rowOrigins.get(n);i!==void 0&&t.set(n,i)}return t}enrichWithVirtualPropsSnapshot(e,t){const n=e,i=n.$synced??t.$synced,r=n.$origin??t.$origin,o=n.$key??t.$key,a=n.$collectionId??t.$collectionId,c=this.virtualPropsCache.get(e);if(c&&c.synced===i&&c.origin===r&&c.key===o&&c.collectionId===a)return c.enriched;const u={...e,$synced:i,$origin:r,$key:o,$collectionId:a};return this.virtualPropsCache.set(e,{synced:i,origin:r,key:o,collectionId:a,enriched:u}),u}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.enrichWithVirtualPropsSnapshot(e,this.createVirtualPropsSnapshot(t))}enrichChangeMessage(e){const{__virtualProps:t}=e,n=t?.value?this.enrichWithVirtualPropsSnapshot(e.value,t.value):this.enrichWithVirtualProps(e.value,e.key),i=e.previousValue?t?.previousValue?this.enrichWithVirtualPropsSnapshot(e.previousValue,t.previousValue):this.enrichWithVirtualProps(e.previousValue,e.key):void 0;return{key:e.key,type:e.type,value:n,previousValue:i,metadata:e.metadata}}getWithVirtualProps(e){const t=this.get(e);if(t!==void 0)return this.enrichWithVirtualProps(t,e)}get(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:i}=this;if(!t.has(e))return n.has(e)?n.get(e):i.get(e)}has(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:i}=this;return t.has(e)?!1:n.has(e)?!0:i.has(e)}*keys(){const{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(const i of e.keys())t.has(i)||(yield i);for(const i of n.keys())!e.has(i)&&!t.has(i)&&(yield i)}*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,i]of this.entries())e(i,n,t++)}map(e){const t=[];let n=0;for(const[i,r]of this.entries())t.push(e(r,i,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),i=this.rowOrigins;for(const h of this.transactions.values()){const l=h.metadata[ge]===!0;if(h.state==="completed"){for(const f of h.mutations)if(this.isThisCollection(f.collection)&&(this.pendingLocalOrigins.add(f.key),!!f.optimistic))switch(f.type){case"insert":case"update":this.pendingOptimisticUpserts.set(f.key,f.modified),this.pendingOptimisticDeletes.delete(f.key),l?(this.pendingOptimisticDirectUpserts.add(f.key),this.pendingOptimisticDirectDeletes.delete(f.key)):(this.pendingOptimisticDirectUpserts.delete(f.key),this.pendingOptimisticDirectDeletes.delete(f.key));break;case"delete":this.pendingOptimisticUpserts.delete(f.key),this.pendingOptimisticDeletes.add(f.key),l?(this.pendingOptimisticDirectUpserts.delete(f.key),this.pendingOptimisticDirectDeletes.add(f.key)):(this.pendingOptimisticDirectUpserts.delete(f.key),this.pendingOptimisticDirectDeletes.delete(f.key));break}}else if(h.state==="failed")for(const f of h.mutations)this.isThisCollection(f.collection)&&(this.pendingLocalOrigins.delete(f.key),f.optimistic&&(this.pendingOptimisticUpserts.delete(f.key),this.pendingOptimisticDeletes.delete(f.key),this.pendingOptimisticDirectUpserts.delete(f.key),this.pendingOptimisticDirectDeletes.delete(f.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();const r=new Set;for(const h of this.pendingSyncedTransactions)for(const l of h.operations)r.add(l.key);const o=[];for(const[h,l]of this.pendingOptimisticUpserts)r.has(h)||this.pendingOptimisticDirectUpserts.has(h)?this.optimisticUpserts.set(h,l):o.push(h);for(const h of o)this.pendingOptimisticUpserts.delete(h),this.pendingLocalOrigins.delete(h);const a=[];for(const h of this.pendingOptimisticDeletes)r.has(h)||this.pendingOptimisticDirectDeletes.has(h)?this.optimisticDeletes.add(h):a.push(h);for(const h of a)this.pendingOptimisticDeletes.delete(h),this.pendingLocalOrigins.delete(h);const c=[];for(const h of this.transactions.values())["completed","failed"].includes(h.state)||c.push(h);for(const h of c)for(const l of h.mutations)if(this.isThisCollection(l.collection)&&(this.pendingLocalChanges.add(l.key),l.optimistic))switch(l.type){case"insert":case"update":this.optimisticUpserts.set(l.key,l.modified),this.optimisticDeletes.delete(l.key);break;case"delete":this.optimisticUpserts.delete(l.key),this.optimisticDeletes.add(l.key);break}this.size=this.calculateSize();const u=[];this.collectOptimisticChanges(t,n,i,u);const d=u.filter(h=>!!(!this.recentlySyncedKeys.has(h.key)||e));if(this.pendingSyncedTransactions.length>0&&!e){const h=new Set;for(const f of this.pendingSyncedTransactions)for(const p of f.operations)h.add(p.key);const l=d.filter(f=>!(f.type==="delete"&&h.has(f.key)&&!c.some(y=>y.mutations.some(b=>this.isThisCollection(b.collection)&&b.key===f.key))));l.length>0&&this.indexes.updateIndexes(l),this.changes.emitEvents(l,e)}else d.length>0&&this.indexes.updateIndexes(d),this.changes.emitEvents(d,e)}calculateSize(){const e=this.syncedData.size,t=Array.from(this.optimisticDeletes).filter(i=>this.syncedData.has(i)&&!this.optimisticUpserts.has(i)).length,n=Array.from(this.optimisticUpserts.keys()).filter(i=>!this.syncedData.has(i)).length;return e-t+n}collectOptimisticChanges(e,t,n,i){const r=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(const o of r){const a=this.get(o),c=this.getPreviousValue(o,e,t),u=this.getVirtualPropsSnapshotForState(o,{rowOrigins:n,optimisticUpserts:e,optimisticDeletes:t}),d=this.getVirtualPropsSnapshotForState(o);c!==void 0&&a===void 0?i.push({type:"delete",key:o,value:c,__virtualProps:{value:u}}):c===void 0&&a!==void 0?i.push({type:"insert",key:o,value:a,__virtualProps:{value:d}}):c!==void 0&&a!==void 0&&c!==a&&i.push({type:"update",key:o,value:a,previousValue:c,__virtualProps:{value:d,previousValue:u}})}}getPreviousValue(e,t,n){if(!n.has(e))return t.has(e)?t.get(e):this.syncedData.get(e)}commitNextPendingTransactionBatch(){const e=this.syncSessionGeneration;let t=!1;for(const c of this.transactions.values())if(c.state==="persisting"){t=!0;break}const{committedSyncedTransactions:n,uncommittedSyncedTransactions:i,hasTruncateSync:r,hasImmediateSync:o,layoutChanged:a}=this.pendingSyncedTransactions.reduce((c,u)=>(u.committed?(c.committedSyncedTransactions.push(u),c.layoutChanged||=u.layoutChanged,u.truncate&&(c.hasTruncateSync=!0),u.immediate&&(c.hasImmediateSync=!0)):c.uncommittedSyncedTransactions.push(u),c),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1,layoutChanged:!1});if(n.length===0)return{processed:!1};if(!t||r||o){const c=a?[...this.keys()]:void 0;this.pendingSyncedTransactions=i;for(const m of n)m.applicationStarted=!0;this.isCommittingSyncTransactions=!0;const u=r?n.find(m=>m.truncate)?.optimisticSnapshot:null;let d,h;const l=new Set;for(const m of n){for(const S of m.operations)l.add(S.key);for(const[S]of m.rowMetadataWrites)l.add(S)}const f=new Set(l);for(const m of this.pendingOptimisticDirectUpserts)f.add(m);for(const m of this.pendingOptimisticDirectDeletes)f.add(m);const p=this.snapshotRowOriginsForKeys(f),y=new Map(this.optimisticUpserts),b=new Set(this.optimisticDeletes),w=new Set(this.pendingOptimisticDirectUpserts),C=new Set(this.pendingOptimisticDirectDeletes);let v=this.preSyncVisibleState;if(v.size===0){v=new Map;for(const m of l){const S=this.get(m);S!==void 0&&v.set(m,S)}}const k=[],D=this.config.sync.rowUpdateMode||"partial",x=new Map;for(const m of this.transactions.values())if(m.state==="completed")for(const S of m.mutations)this.isThisCollection(S.collection)&&S.optimistic&&x.set(S.key,{type:S.type,value:S.modified});for(const m of n){if(m.truncate){const S=new Set([...this.syncedData.keys(),...u?.upserts.keys()||[]]);for(const g of S){if(u?.deletes.has(g))continue;const R=u?.upserts.get(g)||this.syncedData.get(g);R!==void 0&&k.push({type:"delete",key:g,value:R})}d=new Set(this.pendingLocalChanges),h=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState();for(const g of l)v.delete(g);this._events.emit("truncate",{type:"truncate",collection:this.collection})}for(const S of m.operations){const g=S.key,R=(d?.has(g)===!0||h?.has(g)===!0)&&!w.has(g)&&!C.has(g),O=this.isLocalOnly||this.pendingLocalChanges.has(g)||this.pendingLocalOrigins.has(g)||R?"local":"remote";switch(S.type){case"insert":this.syncedData.set(g,S.value),this.rowOrigins.set(g,O),this.pendingLocalChanges.delete(g),this.pendingLocalOrigins.delete(g),this.pendingOptimisticUpserts.delete(g),this.pendingOptimisticDeletes.delete(g),this.pendingOptimisticDirectUpserts.delete(g),this.pendingOptimisticDirectDeletes.delete(g);break;case"update":{if(D==="partial"){const A=Object.assign({},this.syncedData.get(g),S.value);this.syncedData.set(g,A)}else this.syncedData.set(g,S.value);this.rowOrigins.set(g,O),this.pendingLocalChanges.delete(g),this.pendingLocalOrigins.delete(g),this.pendingOptimisticUpserts.delete(g),this.pendingOptimisticDeletes.delete(g),this.pendingOptimisticDirectUpserts.delete(g),this.pendingOptimisticDirectDeletes.delete(g);break}case"delete":this.syncedData.delete(g),this.syncedMetadata.delete(g),this.rowOrigins.delete(g),this.pendingLocalChanges.delete(g),this.pendingLocalOrigins.delete(g),this.pendingOptimisticUpserts.delete(g),this.pendingOptimisticDeletes.delete(g),this.pendingOptimisticDirectUpserts.delete(g),this.pendingOptimisticDirectDeletes.delete(g);break}m.preserveHydrationSeedKeys||(this.hydrationSeedKeys.delete(g),this.hydratedKeys.delete(g))}for(const[S,g]of m.rowMetadataWrites){if(g.type==="delete"){this.syncedMetadata.delete(S);continue}this.syncedMetadata.set(S,g.value)}for(const[S,g]of m.collectionMetadataWrites){if(g.type==="delete"){this.syncedCollectionMetadata.delete(S);continue}this.syncedCollectionMetadata.set(S,g.value)}}if(r){const m=new Set;for(const R of n)for(const O of R.operations)(O.type==="insert"||O.type==="update")&&m.add(O.key);const S=new Map(u.upserts),g=new Set(u.deletes);for(const R of w)l.has(R)&&S.delete(R);for(const R of C)l.has(R)&&g.delete(R);for(const[R,O]of S)if(!g.has(R))if(m.has(R)){let A=!1;for(let $=k.length-1;$>=0;$--){const K=k[$];if(K.key===R&&K.type==="insert"){K.value=O,A=!0;break}}A||k.push({type:"insert",key:R,value:O})}else k.push({type:"insert",key:R,value:O});if(k.length>0&&g.size>0){const R=[];for(const O of k)O.type==="insert"&&g.has(O.key)||R.push(O);k.length=0,k.push(...R)}this.lifecycle.status!=="ready"&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,r&&u){for(const[m,S]of u.upserts)w.has(m)&&l.has(m)||this.optimisticUpserts.set(m,S);for(const m of u.deletes)C.has(m)&&l.has(m)||this.optimisticDeletes.add(m)}for(const m of this.transactions.values())if(!["completed","failed"].includes(m.state)){for(const S of m.mutations)if(this.isThisCollection(S.collection)&&S.optimistic)switch(S.type){case"insert":case"update":this.optimisticUpserts.set(S.key,S.modified),this.optimisticDeletes.delete(S.key);break;case"delete":this.optimisticUpserts.delete(S.key),this.optimisticDeletes.add(S.key);break}}for(const m of this.pendingOptimisticDirectUpserts)if(!l.has(m)){if(l.add(m),!v.has(m)){const S=y.get(m);S!==void 0&&v.set(m,S)}this.pendingOptimisticUpserts.delete(m),this.pendingLocalOrigins.delete(m)}for(const m of this.pendingOptimisticDirectDeletes)l.has(m)||l.add(m),this.pendingOptimisticDeletes.delete(m),this.pendingLocalOrigins.delete(m);this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear();for(const m of l){const S=v.get(m),g=this.get(m),R=this.preSyncVirtualState.get(m)??this.getVirtualPropsSnapshotForState(m,{rowOrigins:p,optimisticUpserts:y,optimisticDeletes:b,completedOptimisticKeys:x}),O=this.getVirtualPropsSnapshotForState(m),A=R.$synced!==O.$synced||R.$origin!==O.$origin,$=S!==void 0?ht(S,m,this.collection.id,()=>R.$synced,()=>R.$origin):void 0,K=x.get(m);let T=!1;K&&(K.type==="delete"&&S!==void 0&&g===void 0&&F(K.value,S)||g!==void 0&&F(K.value,g))&&(T=!0);const L=A&&S!==void 0&&g!==void 0&&F(S,g);if(!(T&&!L))if(S===void 0&&g!==void 0){const J=x.get(m);if(J){const fe=J.value,Oe=ht(fe,m,this.collection.id,()=>R.$synced,()=>R.$origin);k.push({type:"update",key:m,value:g,previousValue:Oe})}else k.push({type:"insert",key:m,value:g})}else S!==void 0&&g===void 0?k.push({type:"delete",key:m,value:$??S}):S!==void 0&&g!==void 0&&(!F(S,g)||L)&&k.push({type:"update",key:m,value:g,previousValue:$??S})}this.size=this.calculateSize(),k.length>0&&this.indexes.updateIndexes(k);let E;try{const m=c!==void 0&&(c.length!==this.size||[...this.keys()].some((S,g)=>S!==c[g]));this.changes.emitEvents(k,!0,m)}catch(m){E={error:m}}this.syncSessionGeneration===e&&(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),Promise.resolve().then(()=>{this.syncSessionGeneration===e&&this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0));for(const m of n)m.applied.resolve();return{processed:!0,failure:E}}return{processed:!1}}cancelPendingSyncedTransaction(e){if(e.applicationStarted)return;const t=this.pendingSyncedTransactions.indexOf(e);if(t===-1)return;this.pendingSyncedTransactions.splice(t,1),e.applied.reject(new it);const n=new Set;for(const i of this.pendingSyncedTransactions)for(const r of i.operations)n.add(r.key);for(const i of e.operations){const r=i.key;n.has(r)||(this.recentlySyncedKeys.delete(r),this.preSyncVisibleState.delete(r),this.preSyncVirtualState.delete(r))}this.pendingSyncedTransactions.length===0?(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.changes.emitEvents([],!0)):this.recomputeOptimisticState(!1)}scheduleTransactionCleanup(e){if(e.state==="completed"){this.transactions.delete(e.id);return}e.isPersisted.promise.then(()=>{this.transactions.delete(e.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;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),this.preSyncVirtualState.set(t,this.getVirtualPropsSnapshotForState(t)))}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncSessionGeneration++;for(const e of this.pendingSyncedTransactions)e.applied.reject(new it);this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingOptimisticUpserts.clear(),this.pendingOptimisticDeletes.clear(),this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.hasReceivedFirstCommit=!1}}function X(s){let e;for(const t of s)try{t()}catch(n){e??={error:n}}if(e)throw e.error}function bn(s){return typeof s=="object"&&s!==null&&typeof s.hasPendingGraphRun=="function"}class wn{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},this.contexts.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:i}){if(typeof e>"u"){i();return}const r=this.getOrCreateContext(e);if(r.jobs.has(t)||r.queue.push(t),r.jobs.set(t,i),n){const o=new Set(n);o.delete(t),r.dependencies.set(t,o)}else r.dependencies.has(t)||r.dependencies.set(t,new Set)}flush(e){const t=this.contexts.get(e);if(!t)return;const{queue:n,jobs:i,dependencies:r}=t;for(;n.length>0;){let o=!1;const a=n.length;for(let c=0;c<a;c++){const u=n.shift(),d=i.get(u);if(!d){r.delete(u);continue}const h=r.get(u);let l=!h;if(h){l=!0;for(const f of h){if(f===u)continue;const p=bn(f)&&f.hasPendingGraphRun(e);if(i.has(f)||p){l=!1;break}}}l?(i.delete(u),r.delete(u),d(),o=!0):n.push(u)}if(!o)throw new Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}clear(e){this.contexts.delete(e),X([...this.clearListeners].map(t=>()=>t(e)))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}}const ue=new wn;let Se,ve;function yt(){return ve}function mt(s){if(Se===void 0)throw s;ve??={error:s}}function gt(s){if(Se!==void 0)return s();const e=Symbol("collection-publication");Se=e,ve=void 0;let t,n;try{t=s(),ue.flush(e),n=yt()}catch(i){try{ue.clear(e)}catch{}const r=yt();throw r?r.error:i}finally{Se=void 0,ve=void 0}if(n)throw n.error;return t}function Kt(){const s=new Map;function e(t){const n=t.join(".");if(s.has(n))return s.get(n);const i=new Proxy({},{get(r,o,a){if(o==="__refProxy")return!0;if(o==="__path")return t;if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(r,o,a);const c=[...t,String(o)];return e(c)},has(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?!0:Reflect.has(r,o)},ownKeys(r){return Reflect.ownKeys(r)},getOwnPropertyDescriptor(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(r,o)}});return s.set(n,i),i}return e([])}function M(s){if(vn(s))return new Et(s.__path);if(s&&typeof s=="object"&&(s.__brand==="ToArrayWrapper"||s.__brand==="ConcatToArrayWrapper"||s.__brand==="CaseWhenWrapper"||s.__brand==="MaterializeWrapper")){const e=s.__brand==="ToArrayWrapper"?"toArray()":s.__brand==="ConcatToArrayWrapper"?"concat(toArray())":s.__brand==="CaseWhenWrapper"?"caseWhen()":"materialize()";throw new Error(`${e} cannot be used inside expressions (e.g., coalesce(), eq(), not()). Use ${e} directly as a select field value instead.`)}return s&&typeof s=="object"&&"type"in s&&(s.type==="func"||s.type==="ref"||s.type==="val"||s.type==="agg")?s:new Z(s)}function vn(s){return s&&typeof s=="object"&&s.__refProxy===!0}function Ft(s,e){return new N("eq",[M(s),M(e)])}function kn(s,e){return new N("gt",[M(s),M(e)])}function Cn(s,e){return new N("gte",[M(s),M(e)])}function Ut(s,e){return new N("lt",[M(s),M(e)])}function Le(s,e,...t){const n=[s,e,...t];return new N("and",n.map(i=>M(i)))}function Vt(s,e,...t){const n=[s,e,...t];return new N("or",n.map(i=>M(i)))}function Rn(s){return new N("not",[M(s)])}function On(s){return new N("isUndefined",[M(s)])}function Tn(s){return new N("isNull",[M(s)])}class $t{constructor(){this.listeners=new Map,this.onceCallbacks=new WeakMap}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Map);const n=this.listeners.get(e),i=t;let r=n.get(i);return r||(r={},n.set(i,r)),()=>{const o=this.listeners.get(e);o?.get(i)===r&&o.delete(i)}}once(e,t){let n=()=>{};const i=r=>{n(),t(r)};return this.onceCallbacks.set(i,t),n=this.on(e,i),n}off(e,t){const n=this.listeners.get(e);if(n)for(const i of n.keys())(i===t||this.onceCallbacks.get(i)===t)&&n.delete(i)}waitFor(e,t){return new Promise((n,i)=>{let r;const o=this.on(e,a=>{r&&(clearTimeout(r),r=void 0),n(a),o()});t&&(r=setTimeout(()=>{r=void 0,o(),i(new Error(`Timeout waiting for event ${String(e)}`))},t))})}emitInner(e,t){this.emitInnerWhile(e,t,()=>!0)}emitInnerWhile(e,t,n){const i=this.listeners.get(e);if(i)for(const[r,o]of[...i]){if(!n())break;if(this.listeners.get(e)?.get(r)===o)try{r(t)}catch(a){queueMicrotask(()=>{throw a})}}}clearListeners(){this.listeners.clear()}}function zt(s){return Vt(Tn(s),On(s))}function En(s,e){const t=zt(s.expression);if(e==null)return s.compareOptions.nulls==="first"?Rn(t):new Z(!1);const i=(s.compareOptions.direction==="asc"?kn:Ut)(s.expression,new Z(e));return s.compareOptions.nulls==="last"?Vt(i,t):i}function xn(s,e){if(e.length!==0){if(s.length!==1||e.length!==1)throw new Error("Only single-column cursors are supported");return En(s[0],e[0])}}function Dn(s,e){const{expression:t}=s[0]??{};if(!t||e.length===0)return;const n=e[0];if(n==null)return zt(t);if(n instanceof Date)return Number.isFinite(n.getTime())?Le(Cn(t,new Z(n)),Ut(t,new Z(new Date(n.getTime()+1)))):void 0;if(typeof n!="object")return Ft(t,new Z(n))}const B=s=>{try{return s instanceof Error?s:new Error(String(s))}catch{return new Error("Unknown error")}};function ne(){let s,e,t=!0;return{promise:new Promise((i,r)=>{s=o=>{t=!1,i(o)},e=o=>{t=!1,r(o)}}),resolve:s,reject:e,isPending:()=>t}}function St(){const s=ne();return s.promise.catch(()=>{}),s}function oe(s){s.abortController?.abort(),s.removeRequestAbortListener?.()}class In extends $t{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.subsetDemands=[],this.primaryFailureDeliveryDepth=0,this.requestedSubsetWhere=new WeakMap,this.sentKeys=new Set,this.publishedRows=new Map,this.stalePublishedRows=new Map,this.limitedSnapshotRowCount=0,this._status="ready",this.statusRevision=0,this.pendingLoadSubsetParticipants=new Set,this.loadSubsetPromiseErrors=new WeakMap,this.truncateReplacementPending=!1,this.unsubscribed=!1,n.onUnsubscribe&&this.on("unsubscribed",n.onUnsubscribe),n.onLoadSubsetError&&this.on("loadSubset:error",n.onLoadSubsetError),n.whereExpression&&dn(n.whereExpression,this.collection);const i=r=>{this.trackPublishedRows(r),this.trackSentKeys(r),t(r)};this.callback=i,this.filteredCallback=n.whereExpression?mn(this.callback,n):r=>(this.callback(r),!0),this.truncateCleanup=this.collection.on("truncate",()=>{this.handleTruncate()}),this.collectionCleanup=this.collection.on("status:cleaned-up",()=>{this.handleCollectionCleanup()}),this.collectionRestartCleanup=this.collection.on("status:change",({status:r})=>{if(r!=="loading"&&r!=="ready")return;const o=this.collection._sync.getLoadSubsetSession(),a=this.truncateReplaySession;this.subsetDemands.some(c=>c.acquisitionState==="detached")&&this.setStatus("loadingSubset"),queueMicrotask(()=>{this.truncateReplaySession===a&&this.restartDetachedDemands(o)})})}get status(){return this._status}get lastError(){return this._lastError}handleCollectionCleanup(){this.discardTruncateReplay(),this.stalePublishedRows=new Map(this.publishedRows),this.pendingLoadSubsetParticipants.clear();for(const e of[...this.subsetDemands])if(e.initialResult?.reject(new z),oe(e.acquisition),e.acquisitionState==="starting"){const t=this.subsetDemands.indexOf(e);t!==-1&&this.subsetDemands.splice(t,1)}else e.acquisitionState="detached",e.acquisition={options:e.requestOptions,loadSubsetSession:e.acquisition.loadSubsetSession};this.setReadyIfIdle()}restartDetachedDemands(e){if(this.unsubscribed||!this.isLoadSubsetSessionCurrent(e))return;if(this.collection.status==="error"||this.collection._sync.syncLoadSubsetFn===null){this.setReadyIfIdle();return}const t=this.subsetDemands.filter(r=>r.acquisitionState==="detached"&&!r.requestOptions.signal?.aborted);if(t.length===0){this.setReadyIfIdle();return}const n=this.createTruncateReplaySession(e,()=>{const r=this.collection.currentStateAsChanges({optimizedOnly:!1});return new Map((r??[]).filter(o=>o.type!=="delete").map(o=>[o.key,o.value]))}),i=n.currentAttempt;this.truncateReplaySession=n,this.setStatus("loadingSubset"),this.truncateReplaySession===n&&this.startTruncateReplayAttempt(n,i,t)}handleTruncate(){const t=this.collection._sync.syncLoadSubsetFn!==null?[...this.subsetDemands]:[];if(t.length===0&&this.stalePublishedRows.size===0){this.resetSnapshotTracking();return}let n=this.truncateReplaySession;n?(n.completion.isPending()||(n.completion=St()),n.pendingSetups++,n.failures.clear(),n.currentAttempt={pendingCount:0,setupComplete:!1}):(n=this.createTruncateReplaySession(this.collection._sync.getLoadSubsetSession(),()=>new Map(this.publishedRows)),this.truncateReplaySession=n);const i=n.currentAttempt;if(this.setStatus("loadingSubset"),this.truncateReplaySession===n){this.options.truncateReplayPublication&&(this.truncateReplacementPending=!0,this.options.truncateReplayPublication.start());for(const r of t)r.acquisition.abortController?.abort();this.resetSnapshotTracking(),queueMicrotask(()=>{if(this.truncateReplaySession===n){if(!this.isLoadSubsetSessionCurrent(n.loadSubsetSession)){this.retireStaleTruncateReplay(n);return}this.startTruncateReplayAttempt(n,i,n.currentAttempt===i?t:[])}})}}startTruncateReplayDemand(e,t,n){const i=()=>this.truncateReplaySession===e&&e.currentAttempt===t,r=()=>i()&&this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.isDemandActive(n),o=h=>{r()&&e.failures.set(n,B(h))};n.initialResult&&e.completion.promise.then(n.initialResult.resolve,n.initialResult.reject);const a=n.acquisition,c=n.acquisitionState==="active";if(n.acquisitionState="detached",c)try{this.releaseAcquisition(a)}catch(h){o(h);return}if(!r()||n.requestOptions.signal?.aborted)return;const u=this.createSubsetAcquisition(n);n.acquisition=u,n.acquisitionState="starting";let d;try{d=this.loadSubset(u.options,r)}catch(h){n.acquisition===u&&(n.acquisitionState="detached"),oe(u),o(h);return}if(!r()){n.acquisition===u&&(n.acquisitionState="detached");try{this.releaseAcquisition(u)}catch(h){o(h)}return}n.acquisitionState="active",this.trackTruncateReplayParticipant(e,t,n,d),this.observeLoadSubsetResult(d,n,u.options,!0,()=>r()&&!u.options.signal?.aborted)}settleTruncateReplay(e,t){try{if(this.truncateReplaySession!==e)return;if(!this.isLoadSubsetSessionCurrent(e.loadSubsetSession)){this.retireStaleTruncateReplay(e);return}e.pending.delete(t)&&t.attempt.pendingCount--,this.checkTruncateReplayComplete(e)}catch(n){queueMicrotask(()=>{throw n})}}trackTruncateReplayParticipant(e,t,n,i){if(this.truncateReplaySession!==e||e.currentAttempt!==t&&t.setupComplete&&t.pendingCount===0||!(i instanceof Promise))return;const r={demand:n,attempt:t};t.pendingCount++,e.pending.add(r),i.then(()=>this.settleTruncateReplay(e,r),o=>{if(this.truncateReplaySession===e&&e.currentAttempt===t&&this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.subsetDemands.includes(n)){const a=this.normalizeLoadSubsetPromiseError(i,o);e.failures.set(n,a)}this.settleTruncateReplay(e,r)})}removeTruncateReplayParticipant(e){const t=this.truncateReplaySession;if(t){t.failures.delete(e);for(const n of t.pending)n.demand===e&&(t.pending.delete(n),n.attempt.pendingCount--)}}checkTruncateReplayComplete(e){if(this.truncateReplaySession!==e||e.pendingSetups>0||e.pending.size>0)return;const t=[...e.failures].find(([n])=>this.subsetDemands.includes(n));try{t?this.abandonTruncateReplay(e,t[1]):this.flushTruncateReplay(e)}finally{this.setReadyIfIdle()}}abandonTruncateReplay(e,t){if(this.truncateReplaySession!==e||(e.completion.reject(t),!e.privateRows))return;const n=e.publicationState;this.loadedInitialState=n.loadedInitialState,this.snapshotSent=n.snapshotSent,this.limitedSnapshotRowCount=n.limitedSnapshotRowCount,this.lastSentKey=n.lastSentKey}flushTruncateReplay(e){if(this.truncateReplaySession!==e)return;this.truncateReplaySession=void 0,this.truncateReplacementPending=!1;const{privateRows:t}=e;for(const n of this.stalePublishedRows.keys())t?.delete(n);this.stalePublishedRows.clear();try{if(t){const n=this.createStateDiff(this.publishedRows,t);n.length>0&&this.filteredCallback(n)}}finally{this.restorePublishedSnapshotTracking(),e.completion.resolve(),this.options.truncateReplayPublication?.succeed()}}restorePublishedSnapshotTracking(){if(this.sentKeys=new Set(this.publishedRows.keys()),!this.orderByIndex)return;this.limitedSnapshotRowCount=this.sentKeys.size;const e=this.orderByIndex.takeFromStart(this.sentKeys.size,t=>this.sentKeys.has(t));this.lastSentKey=e.at(-1)}bufferPrivately(e){const t=this.truncateReplaySession?.privateRows;if(!t)return!1;for(const n of e)n.type==="delete"?t.delete(n.key):t.set(n.key,n.value);return!0}createStateDiff(e,t){const n=[];for(const[i,r]of e){const o=t.get(i);o===void 0?n.push({type:"delete",key:i,value:r}):F(o,r)||n.push({type:"update",key:i,value:o,previousValue:r})}for(const[i,r]of t)e.has(i)||n.push({type:"insert",key:i,value:r});return n}get isBufferingForTruncate(){return this.truncateReplaySession!==void 0}setReadyIfIdle(){const e=this.truncateReplaySession,t=e&&(e.pendingSetups>0||e.pending.size>0);this.pendingLoadSubsetParticipants.size===0&&!t&&this.setStatus("ready")}isLoadSubsetSessionCurrent(e){return e===this.collection._sync.getLoadSubsetSession()}retireStaleTruncateReplay(e){this.truncateReplaySession===e&&(this.discardTruncateReplay(),this.stalePublishedRows.clear())}discardTruncateReplay(){const e=this.truncateReplaySession;e?.completion.isPending()&&e.completion.reject(new z),this.truncateReplaySession=void 0,this.truncateReplacementPending=!1}resetSnapshotTracking(){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0}createTruncateReplaySession(e,t){return{loadSubsetSession:e,publicationState:{loadedInitialState:this.loadedInitialState,snapshotSent:this.snapshotSent,limitedSnapshotRowCount:this.limitedSnapshotRowCount,lastSentKey:this.lastSentKey},privateRows:this.options.truncateReplayPublication?void 0:t(),pending:new Set,pendingSetups:1,currentAttempt:{pendingCount:0,setupComplete:!1},failures:new Map,completion:St()}}startTruncateReplayAttempt(e,t,n){for(const i of n)if(this.subsetDemands.includes(i)&&(this.startTruncateReplayDemand(e,t,i),this.truncateReplaySession!==e||e.currentAttempt!==t))break;t.setupComplete=!0,e.pendingSetups--,this.checkTruncateReplayComplete(e)}get hasPendingTruncateReplacement(){return this.truncateReplacementPending}get pendingTruncateReplacement(){const e=this.truncateReplaySession?.completion;return e?.isPending()?e.promise:void 0}get hasFailedTruncateReplacement(){const e=this.truncateReplaySession?.completion;return this.truncateReplacementPending&&e!==void 0&&!e.isPending()}setOrderByIndex(e){this.orderByIndex=e}setStatus(e){if(this.unsubscribed||this._status===e)return;const t=this._status;this._status=e;const n=++this.statusRevision;if(this.emitInnerWhile("status:change",{type:"status:change",subscription:this,previousStatus:t,status:e},()=>this.statusRevision===n),this.statusRevision!==n)return;const i=`status:${e}`;this.emitInnerWhile(i,{type:i,subscription:this,previousStatus:t,status:e},()=>this.statusRevision===n)}observeLoadSubsetResult(e,t,n,i,r=()=>!0){if(!(e instanceof Promise))return;const o=this.collection._sync.getLoadSubsetSession(),a={demand:t,promise:e};i&&(this.pendingLoadSubsetParticipants.add(a),this.setStatus("loadingSubset"));const c=()=>{i&&(this.pendingLoadSubsetParticipants.delete(a),this.isLoadSubsetSessionCurrent(o)&&this.setReadyIfIdle())};e.then(c,u=>{this.isLoadSubsetSessionCurrent(o)&&r()&&this.recordLoadSubsetError(n,this.normalizeLoadSubsetPromiseError(e,u)),c()})}normalizeLoadSubsetPromiseError(e,t){const n=this.loadSubsetPromiseErrors.get(e);if(n)return n;const i=B(t);return this.loadSubsetPromiseErrors.set(e,i),i}stopDemandStatusParticipants(e){for(const t of this.pendingLoadSubsetParticipants)t.demand===e&&this.pendingLoadSubsetParticipants.delete(t);this.setReadyIfIdle()}loadSubset(e,t=()=>!0){try{return this.collection._sync.loadSubset(e)}catch(n){const i=B(n);throw t()&&this.recordLoadSubsetError(e,i),i}}createSubsetAcquisition(e){const t=new AbortController,n=e.requestOptions.signal;let i;if(n?.aborted)t.abort(n.reason);else if(n){const r=()=>t.abort(n.reason);n.addEventListener("abort",r,{once:!0}),i=()=>n.removeEventListener("abort",r)}return{options:{...e.requestOptions,signal:t.signal},loadSubsetSession:this.collection._sync.getLoadSubsetSession(),abortController:t,removeRequestAbortListener:i}}releaseAcquisition(e,t=this.primaryFailureDeliveryDepth===0){if(!e.releaseAttempted){e.releaseAttempted=!0;try{e.abortController?.abort(),this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.collection._sync.unloadSubset(e.options)}catch(n){throw t?this.recordLoadSubsetError(e.options,B(n),!0):B(n)}finally{e.removeRequestAbortListener?.()}}}startSubsetDemand(e){const t={requestOptions:e,acquisition:{options:e,loadSubsetSession:this.collection._sync.getLoadSubsetSession()},acquisitionState:"starting"};if(this.collection.status==="cleaned-up"||this.collection.config.syncMode==="on-demand"&&(this.collection.status==="error"||this.collection.status!=="idle"&&this.collection._sync.syncLoadSubsetFn===null)){t.acquisitionState="detached",this.subsetDemands.push(t);const c=ne();t.initialResult=c;const u=()=>c.reject(new z);e.signal?.addEventListener("abort",u,{once:!0});const d=()=>{e.signal?.removeEventListener("abort",u),t.initialResult=void 0};return c.promise.then(d,d),{demand:t,result:c.promise,started:!1}}const n=this.createSubsetAcquisition(t);t.acquisition=n;const i=this.truncateReplaySession,r=i?.currentAttempt,o=this.collection._sync.getLoadSubsetSession();this.subsetDemands.push(t);let a;try{a=this.loadSubset(n.options,()=>this.isLoadSubsetSessionCurrent(o)&&this.subsetDemands.includes(t)&&(i===void 0||this.truncateReplaySession===i&&i.currentAttempt===r))}catch(c){const u=this.subsetDemands.indexOf(t);throw u!==-1&&(i&&r&&this.truncateReplaySession===i&&i.currentAttempt===r&&i.failures.set(t,B(c)),this.subsetDemands.splice(u,1)),oe(n),c}if(!this.isLoadSubsetSessionCurrent(o)){const c=this.subsetDemands.indexOf(t);return c!==-1&&this.subsetDemands.splice(c,1),oe(n),{demand:t,result:a,started:!0}}return t.acquisitionState="active",this.subsetDemands.includes(t)?(i&&r&&this.trackTruncateReplayParticipant(i,r,t,a),{demand:t,result:a,started:!0}):(this.releaseAcquisition(n),{demand:t,result:a,started:!0})}isDemandActive(e){return!this.unsubscribed&&this.subsetDemands.includes(e)}recordLoadSubsetError(e,t,n=!1){const i=B(t);if(e.signal?.aborted&&!n)return i;this._lastError=i,this.primaryFailureDeliveryDepth++;try{this.emitInner("loadSubset:error",{type:"loadSubset:error",subscription:this,options:e,error:i})}finally{this.primaryFailureDeliveryDepth--}return i}emitEvents(e){if(this.unsubscribed)return!1;const t=this.filterAndFlipChanges(e);return e.length>0&&t.length===0||this.bufferPrivately(t)?!1:this.filteredCallback(t)}publishSnapshot(e){this.bufferPrivately(e)||this.callback(e)}requestSnapshot(e){if(this.unsubscribed||e?.signal?.aborted||this.loadedInitialState)return!1;const t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if("where"in e){const d=e.where;if(t.where){const h=t.where,l=Le(h,d);t.where=l}else t.where=d}}else this.loadedInitialState=!0;const n={where:t.where,signal:e?.signal,subscription:this,orderBy:e?.orderBy,limit:e?.limit},{demand:i,result:r,started:o}=this.startSubsetDemand(n);if(!this.isDemandActive(i)||(e?.where&&this.requestedSubsetWhere.set(n,e.where),e?.onLoadSubsetResult?.(r,i.acquisition.options,d=>this.releaseDemand(i,d)),!this.isDemandActive(i))||(o&&this.observeLoadSubsetResult(r,i,i.acquisition.options,e?.trackLoadSubsetPromise??!0),!this.isDemandActive(i)))return!1;let a;if(e?.onUnoptimized){if(a=this.collection.currentStateAsChanges({...t,optimizedOnly:!0}),a===void 0){if(e.onUnoptimized(),this.unsubscribed)return!1;a=this.collection.currentStateAsChanges({...t,optimizedOnly:!1})}}else a=this.collection.currentStateAsChanges(t);if(this.unsubscribed||a===void 0)return!1;const c=this.truncateReplaySession?.privateRows??this.publishedRows,u=a.filter(d=>!this.isBufferingForTruncate&&this.stalePublishedRows.has(d.key)||!this.sentKeys.has(d.key)&&!c.has(d.key));for(const d of u)this.sentKeys.add(d.key);return this.snapshotSent=!0,this.publishSnapshot(this.isBufferingForTruncate?u:this.reconcileStalePublishedChanges(u)),!0}releaseSnapshot(e){const t=this.subsetDemands.findIndex(n=>n.requestOptions.where===e||this.requestedSubsetWhere.get(n.requestOptions)===e);t!==-1&&this.releaseDemandAt(t)}releaseDemand(e,t){if(!t){const n=this.subsetDemands.indexOf(e);n!==-1&&this.releaseDemandAt(n);return}try{this.recordLoadSubsetError(e.acquisition.options,t.error,!0)}finally{const n=this.subsetDemands.indexOf(e);n!==-1&&this.releaseDemandAt(n,!1)}}releaseDemandAt(e,t=this.primaryFailureDeliveryDepth===0){const n=this.subsetDemands[e];if(!n)return;const i=this.truncateReplaySession,r=n.acquisition;this.subsetDemands.splice(e,1),n.initialResult?.reject(new z);const o=[()=>this.removeTruncateReplayParticipant(n),...n.acquisitionState==="active"?[()=>this.releaseAcquisition(r,t)]:[],()=>this.retireEmptyReplay(),()=>{i&&this.checkTruncateReplayComplete(i)},()=>this.stopDemandStatusParticipants(n)];X(o)}retireEmptyReplay(){this.subsetDemands.length!==0||!this.truncateReplaySession||(this.discardTruncateReplay(),this.stalePublishedRows=new Map(this.publishedRows),this.restorePublishedSnapshotTracking(),this.options.truncateReplayPublication?.succeed())}readOrderedSnapshot(e){const t=[this.options.whereExpression,e.where,e.cursor?.whereFrom].filter(i=>i!==void 0),n=this.collection.currentStateAsChanges({orderBy:e.orderBy,limit:e.limit,where:t.length>0?t.reduce((i,r)=>Le(i,r)):void 0});return Array.isArray(n)?n:[]}requestLimitedSnapshot({orderBy:e,limit:t,minValues:n,offset:i,trackLoadSubsetPromise:r=!0,onLoadSubsetResult:o}){if(this.unsubscribed)return;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?xn(e,n):void 0,c=n!==void 0&&n.length>0,d=n?.[0],h=this.orderByIndex,l=this.options.whereExpression,f=l?se(l):void 0,p=O=>{if(O!==void 0&&this.sentKeys.has(O))return!1;const A=this.collection.get(O);return A===void 0?!1:f?.(A)??!0};let y=d;const b=[];let w=[];if(c){const{expression:O}=e[0],A=this.collection.currentStateAsChanges({where:Ft(O,new Z(d))});if(A){const $=A.map(T=>T.key).filter(T=>!this.sentKeys.has(T)&&p(T));w.push(...$);const K=h.take(t-w.length,d,p);w.push(...K)}else w=h.take(t,d,p)}else w=h.takeFromStart(t,p);const C=()=>Math.max(t-b.length,0),v=()=>w.length===0,k=e[0].expression,D=k.type==="ref"?Bs(new Et(k.path),!0):null;for(;C()>0&&!v();){for(const O of w){const A=this.collection.get(O);b.push({type:"insert",key:O,value:A}),y=D?D(A):A}w=h.take(C(),y,p)}const x=this.limitedSnapshotRowCount;for(const O of b)this.sentKeys.add(O.key);if(this.publishSnapshot(b),this.unsubscribed)return;this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,x+b.length),b.length>0&&(this.lastSentKey=b[b.length-1].key);let E;if(a&&n){const O=Dn(e,n);O&&(E={whereFrom:a,whereCurrent:O,lastKey:this.lastSentKey})}const m={where:l,limit:t,orderBy:e,cursor:E,offset:i??x,subscription:this},{demand:S,result:g,started:R}=this.startSubsetDemand(m);this.isDemandActive(S)&&(o?.(g,S.acquisition.options,O=>this.releaseDemand(S,O)),this.isDemandActive(S)&&(R&&this.observeLoadSubsetResult(g,S,S.acquisition.options,r),this.isDemandActive(S)))}filterAndFlipChanges(e){if(e=this.reconcileStalePublishedChanges(e),this.loadedInitialState||this.skipFiltering)return e;const t=this.isBufferingForTruncate,n=[];for(const i of e){let r=i;if(this.sentKeys.has(i.key)){if(i.type==="insert")continue;i.type==="delete"&&this.sentKeys.delete(i.key)}else if(i.type==="update")r={...i,type:"insert",previousValue:void 0},this.sentKeys.add(i.key);else if(i.type==="delete"){if(!t)continue}else this.sentKeys.add(i.key);n.push(r)}return n}reconcileStalePublishedChanges(e){if(this.stalePublishedRows.size===0)return e;const t=[];for(const n of e){const i=this.stalePublishedRows.get(n.key);if(i===void 0){t.push(n);continue}this.stalePublishedRows.delete(n.key),n.type==="delete"?t.push({...n,value:i,previousValue:void 0}):F(i,n.value)||t.push({...n,type:"update",previousValue:i})}if(this.collection.config.syncMode!=="on-demand"&&!this.isBufferingForTruncate)for(const[n,i]of this.stalePublishedRows)this.collection.has(n)||(this.stalePublishedRows.delete(n),t.push({type:"delete",key:n,value:i}));return t}trackPublishedRows(e){for(const t of e)t.type==="delete"?this.publishedRows.delete(t.key):this.publishedRows.set(t.key,t.value)}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering)){for(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(){if(this.unsubscribed)return;this.unsubscribed=!0,this.statusRevision++;const e=[this.truncateCleanup,this.collectionCleanup,this.collectionRestartCleanup];this.truncateCleanup=void 0,this.collectionCleanup=void 0,this.collectionRestartCleanup=void 0,X([...e.map(t=>()=>t?.()),()=>{this.discardTruncateReplay(),this.stalePublishedRows.clear();const t=this.subsetDemands.filter(n=>n.acquisitionState==="active").map(n=>n.acquisition);for(const n of this.subsetDemands)n.initialResult?.reject(new z),this.stopDemandStatusParticipants(n),n.acquisitionState==="starting"&&oe(n.acquisition);this.subsetDemands=[],X(t.map(n=>()=>this.releaseAcquisition(n)))},()=>this.emitInner("unsubscribed",{type:"unsubscribed",subscription:this}),()=>this.clearListeners()])}}class Pn{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1,this.publicationDeferralDepth=0,this.discardDeferredPublications=!1,this.deferredStateRevision=0,this.deferredLayoutRevision=0,this.deferredPublications=[],this.layoutChangeListeners=new Set,this.stateRevision=0,this.layoutRevision=0}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){gt(()=>{try{X([...this.changeSubscriptions].map(e=>()=>e.emitEvents([])))}catch(e){mt(e)}})}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,t=!1,n=!1){if(e.length>0&&this.stateRevision++,n&&this.layoutRevision++,this.shouldBatchEvents&&!t){this.batchedEvents.push(...e);return}let i=e;if(t){if(this.batchedEvents.length>0){const r=new Map(this.batchedEvents.map(o=>[o.key,o]));for(const o of e){const a=r.get(o.key);r.set(o.key,a?.type==="delete"&&o.type==="insert"?{...o,type:"update",previousValue:a.value}:o)}i=[...r.values()]}this.batchedEvents=[],this.shouldBatchEvents=!1}if(this.publicationDeferralDepth>0){this.deferredPublications.push({changes:i,layoutChanged:n});return}this.publishEvents(i,n)}deferPublication(){this.publicationDeferralDepth===0&&(this.deferredStateRevision=this.stateRevision,this.deferredLayoutRevision=this.layoutRevision),this.publicationDeferralDepth++;let e=!1;const t=n=>{if(e||(e=!0,this.publicationDeferralDepth===0)||(this.discardDeferredPublications||=n,this.publicationDeferralDepth--,this.publicationDeferralDepth>0))return;const i=this.deferredPublications;if(this.deferredPublications=[],this.discardDeferredPublications){this.discardDeferredPublications=!1,this.stateRevision=this.deferredStateRevision,this.layoutRevision=this.deferredLayoutRevision;return}this.publishEvents(i.flatMap(({changes:r})=>r),i.some(({layoutChanged:r})=>r))};return{publish:()=>t(!1),discard:()=>t(!0)}}publishEvents(e,t){if(e.length===0&&!t)return;const n=e.map(o=>this.enrichChangeWithVirtualProps(o)),i=[...this.layoutChangeListeners],r=[...this.changeSubscriptions];gt(()=>{const o=r.map(a=>()=>a.emitEvents(n));e.length===0&&o.unshift(...i);try{X(o)}catch(a){mt(a)}})}subscribeLayoutChanges(e){return this.layoutChangeListeners.add(e),()=>this.layoutChangeListeners.delete(e)}subscribeChanges(e,t={}){if(t.where&&t.whereExpression)throw new Error("Cannot specify both 'where' and 'whereExpression' options. Use one or the other.");const{where:n,...i}=t;let r=i.whereExpression;if(n){const c=Kt(),u=n(c);r=M(u)}this.addSubscriber();let o;const a={closed:!1};try{o=new In(this.collection,e,{...i,whereExpression:r,onUnsubscribe:()=>{a.closed=!0,this.removeSubscriber(),o&&this.changeSubscriptions.delete(o)}}),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(),a.closed||this.changeSubscriptions.add(o)}catch(c){if(o)try{o.unsubscribe()}catch{}else this.removeSubscriber();throw c}return o}addSubscriber(){const e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer();try{(this.lifecycle.status==="cleaned-up"||this.lifecycle.status==="idle")&&this.sync.startSync()}catch(t){throw this.activeSubscribersCount=e,this.activeSubscribersCount===0&&this.lifecycle.startGCTimer(),t}this.events.emitSubscribersChange(this.activeSubscribersCount,e)}removeSubscriber(){const e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new us;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1,this.deferredPublications=[],this.publicationDeferralDepth=0}}const An=s=>setTimeout(()=>{s({didTimeout:!0,timeRemaining:()=>50})},0),_n=s=>{clearTimeout(s)},Mn=typeof window<"u"&&"requestIdleCallback"in window?(s,e)=>window.requestIdleCallback(s,e):(s,e)=>An(s),Pe=typeof window<"u"&&"cancelIdleCallback"in window?s=>window.cancelIdleCallback(s):_n,jt=class ae{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return ae.instance||(ae.instance=new ae),ae.instance}schedule(e,t,n){const i=Date.now()+t;this.tasks.set(e,{executeAt:i,callback:n}),this.microtaskScheduled||(this.microtaskScheduled=!0,Promise.resolve().then(()=>{this.microtaskScheduled=!1,this.updateTimeout()}))}cancel(e){this.tasks.delete(e)}updateTimeout(){if(this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.tasks.size===0)return;let e=1/0;for(const n of this.tasks.values())n.executeAt<e&&(e=n.executeAt);const t=Math.max(0,e-Date.now());this.timeoutId=setTimeout(()=>this.process(),t)}process(){this.timeoutId=null;const e=Date.now();for(const[t,n]of this.tasks.entries())if(e>=n.executeAt){this.tasks.delete(t);try{n.callback()}catch(i){console.error("Error in CleanupQueue task:",i)}}this.tasks.size>0&&this.updateTimeout()}};jt.instance=null;let Ae=jt;class Ln{constructor(e,t){this.status="idle",this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.statusRevision=0,this.cleaningUp=!1,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:["ready","cleaned-up","idle"],"cleaned-up":["loading","error"]}[e].includes(t))throw new cs(e,t,this.id)}setStatus(e,t=!1){if(e==="ready"&&!t)throw new re(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);const n=++this.statusRevision,i=this.status;this.status=e,this.events.emitStatusChange(e,i,()=>this.statusRevision===n)}validateCollectionUsable(e){switch(this.status){case"error":throw new as(e,this.id);case"cleaned-up":this.sync.startSync();break}}markReady(){const e=this.applyReadyTransition();if(e)throw e.error}markReadyDuringSyncStart(){return this.applyReadyTransition()}applyReadyTransition(){if(this.validateStatusTransition(this.status,"ready"),this.status==="loading"||this.status==="error"){this.syncError=void 0;const e=this.statusRevision+1;if(this.setStatus("ready",!0),this.status!=="ready"||this.statusRevision!==e)return;const t=[];this.hasBeenReady||(this.hasBeenReady=!0,this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0),t.push(...this.onFirstReadyCallbacks),this.onFirstReadyCallbacks=[]),t.push(()=>this.changes.emitEmptyReadyEvent());try{X(t)}catch(n){return{error:n}}}}markError(e){this.validateStatusTransition(this.status,"error"),this.syncError=e,this.setStatus("error")}getSyncError(){return this.syncError}assertCanStartSync(){if(this.cleaningUp)throw new re(`Cannot start collection "${this.id}" during cleanup. Restart after cleanup() completes.`)}startGCTimer(){const e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||Ae.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Ae.getInstance().cancel(this),this.idleCallbackId!==null&&(Pe(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Pe(this.idleCallbackId),this.idleCallbackId=Mn(e=>{this.changes.activeSubscribersCount===0?this.performCleanup(e)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(e){if(this.cleaningUp)return!0;if(!e||e.timeRemaining()>0||e.didTimeout){this.cleaningUp=!0;try{this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),Ae.getInstance().cancel(this),this.hasBeenReady=!1,this.syncError=void 0,this.onFirstReadyCallbacks=[]}finally{this.cleaningUp=!1}return this.setStatus("cleaned-up"),this.changes.activeSubscribersCount===0&&this.events.cleanup(),!0}else return this.scheduleIdleCleanup(),!1}onFirstReady(e){return this.hasBeenReady?(e(),()=>{}):(this.onFirstReadyCallbacks.push(e),()=>{const t=this.onFirstReadyCallbacks.indexOf(e);t!==-1&&this.onFirstReadyCallbacks.splice(t,1)})}cleanup(){this.idleCallbackId!==null&&(Pe(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}const Kn=Symbol("liveQueryInternal");class Fn{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.loadSubsetOperations=new Set,this.syncStartDeferred=!1,this.syncStartRequested=!1,this.deferredLoadSubsets=[],this.syncEpoch=0,this.loadSubsetSession=0,this.config=e,this.id=t,this.syncMode=e.syncMode??"eager"}setDeps(e){this.collection=e.collection,this.state=e.state,this.lifecycle=e.lifecycle,this._events=e.events}markLayoutChange(){this.getActivePendingSyncTransaction().layoutChanged=!0}startSync(){if(this.lifecycle.assertCanStartSync(),this.lifecycle.status!=="idle"&&this.lifecycle.status!=="cleaned-up")return;if(this.syncStartDeferred){this.syncStartRequested=!0;return}const e=++this.syncEpoch,t=()=>e===this.syncEpoch;if(this.lifecycle.setStatus("loading"),!t())return;let n=!0,i;try{const r=Un(this.config.sync.sync({collection:this.collection,begin:o=>{if(!t())return;const a=ne();a.promise.catch(()=>{}),this.state.pendingSyncedTransactions.push({committed:!1,applicationStarted:!1,layoutChanged:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:o?.immediate,applied:a})},write:o=>{if(!t())return;const a=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!a)throw new Ee;if(a.committed)throw new xe;let c;"key"in o?c=o.key:c=this.config.getKey(o.value),this.state.pendingLocalChanges.has(c)&&this.state.pendingLocalOrigins.add(c);let u=o.type;if(o.type==="insert"){const h=this.state.syncedData.has(c),l=a.deletedKeys.has(c),f=a.truncate===!0;if(h&&!l&&!f){const p=this.state.syncedData.get(c);if(p!==void 0&&F(p,o.value)||this.state.hydrationSeedKeys.has(c))u="update";else{const w=this.config.utils?.[Kn];throw new ps(c,this.id,{hasCustomGetKey:w?.hasCustomGetKey??!1,hasJoins:w?.hasJoins??!1,hasDistinct:w?.hasDistinct??!1})}}}const d={...o,type:u,key:c};a.operations.push(d),u==="delete"?(a.deletedKeys.add(c),a.rowMetadataWrites.set(c,{type:"delete"})):u==="insert"?d.metadata!==void 0?a.rowMetadataWrites.set(c,{type:"set",value:d.metadata}):a.rowMetadataWrites.set(c,{type:"delete"}):d.metadata!==void 0&&a.rowMetadataWrites.set(c,{type:"set",value:d.metadata})},commit:o=>{if(!t())return!0;const a=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!a)throw new xs;if(a.committed)throw new Ds;if(o?.aborted)return this.state.cancelPendingSyncedTransaction(a),a.applied.promise;a.committed=!0;const c=()=>{this.state.cancelPendingSyncedTransaction(a)};if(o?.addEventListener("abort",c,{once:!0}),this.state.commitPendingTransactions(),!a.applied.isPending())return o?.removeEventListener("abort",c),!0;const u=a.applied.promise;if(o){const d=()=>{o.removeEventListener("abort",c)};u.then(d,d)}return u},markReady:()=>{t()&&(n?i??=this.lifecycle.markReadyDuringSyncStart():this.lifecycle.markReady())},markError:o=>{t()&&this.lifecycle.markError(o)},truncate:()=>{if(!t())return;const o=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!o)throw new Ee;if(o.committed)throw new xe;o.operations=[],o.deletedKeys.clear(),o.rowMetadataWrites.clear(),o.truncate=!0,o.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi(t)}));if(n=!1,!t()){if(r?.cleanup?.(),i)throw i.error;return}if(this.syncCleanupFn=r?.cleanup??null,this.syncLoadSubsetFn=r?.loadSubset??null,this.syncUnloadSubsetFn=r?.unloadSubset??null,this.syncMode==="on-demand"&&!this.syncLoadSubsetFn)throw new te(`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(r){throw n=!1,t()&&this.lifecycle.markError(r),r}if(i)throw i.error}deferStart(){return this.lifecycle.status!=="idle"&&this.lifecycle.status!=="cleaned-up"?!1:(this.syncStartDeferred=!0,!0)}resumeStart(){if(!this.syncStartDeferred)return;this.syncStartDeferred=!1;const e=this.syncStartRequested||this.deferredLoadSubsets.length>0;this.syncStartRequested=!1;const t=this.deferredLoadSubsets;this.deferredLoadSubsets=[];const n=this.loadSubsetSession;try{e&&this.startSync()}catch(i){for(const{deferred:r}of t)r.reject(i);throw i}for(const{options:i,deferred:r}of t){const o=this.syncLoadSubsetFn;try{if(n!==this.loadSubsetSession||i.signal?.aborted)throw new z;const a=o?.(i)??!0;a instanceof Promise?a.then(c=>r.resolve(c),c=>r.reject(c)):r.resolve(void 0)}catch(a){r.reject(a)}}}getActivePendingSyncTransaction(){const e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new Ee;if(e.committed)throw new xe;return e}createSyncMetadataApi(e){return{row:{get:t=>{if(!e())return;const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],i=n?.rowMetadataWrites.get(t);if(i)return i.type==="delete"?void 0:i.value;if(!n?.truncate)return this.state.syncedMetadata.get(t)},set:(t,n)=>{if(!e())return;this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:"set",value:n})},delete:t=>{if(!e())return;this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:"delete"})}},collection:{get:t=>{if(!e())return;const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(t);return i?i.type==="delete"?void 0:i.value:this.state.syncedCollectionMetadata.get(t)},set:(t,n)=>{if(!e())return;this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:"set",value:n})},delete:t=>{if(!e())return;this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:"delete"})},list:t=>{if(!e())return[];const n=new Map(this.state.syncedCollectionMetadata),i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(i)for(const[r,o]of i.collectionMetadataWrites)o.type==="delete"?n.delete(r):n.set(r,o.value);return Array.from(n.entries()).filter(([r])=>t?r.startsWith(t):!0).map(([r,o])=>({key:r,value:o}))}}}}preload(){try{this.lifecycle.assertCanStartSync()}catch(t){return Promise.reject(t)}if(this.preloadPromise)return this.preloadPromise;this.syncMode==="on-demand"&&console.warn(`${this.id?`[${this.id}] `:""}Calling .preload() on a collection with syncMode "on-demand" is a no-op. In on-demand mode, data is only loaded when queries request it. Instead, create a live query and call .preload() on that to load the specific data you need. See https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync for more details.`);const e=new Promise((t,n)=>{if(this.lifecycle.status==="ready"){t();return}if(this.lifecycle.status==="error"){n(this.getPreloadError());return}let i=!1;const r={active:!1,ready:!1};let o=()=>{},a=()=>{};const c=()=>{if(r.active){r.ready=!0;return}i||(i=!0,o(),a(),this.rejectPreload===u&&(this.rejectPreload=void 0),t())},u=d=>{i||(i=!0,o(),a(),this.rejectPreload===u&&(this.rejectPreload=void 0),n(d))};if(this.rejectPreload=u,a=this.lifecycle.onFirstReady(c),o=this.collection.on("status:error",()=>{r.active||u(this.getPreloadError())}),this.lifecycle.status==="idle"||this.lifecycle.status==="cleaned-up"){r.active=!0;let d;try{this.startSync()}catch(h){d={error:h}}finally{r.active=!1}this.collection.status==="error"?u(this.getPreloadError()):r.ready?c():d&&u(d.error)}});return this.preloadPromise=e,e.then(void 0,()=>{this.preloadPromise===e&&(this.preloadPromise=null)}),e}getPreloadError(){const e=this.lifecycle.getSyncError();return e===void 0?new ls:e}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}beginLoadSubsetOperation(){const e=this.activeLoadSubsetOperation,t={pending:new Set,waiting:!1,completed:!1,hasError:!1};return this.activeLoadSubsetOperation=t,this.loadSubsetOperations.add(t),{wait:()=>this.waitForLoadSubsetOperation(t),cancel:()=>{t.completed=!0,this.loadSubsetOperations.delete(t),this.activeLoadSubsetOperation===t&&(this.activeLoadSubsetOperation=e?.completed?void 0:e)}}}waitForLoadSubsetOperation(e){return e.waiting=!0,e.pending.size===0?(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),e.hasError?Promise.reject(e.error):!0):(e.deferred=ne(),e.deferred.promise)}settleLoadSubsetOperation(e,t,n){e.completed||(e.pending.delete(t),!n.ok&&!e.hasError&&(e.hasError=!0,e.error=n.error),!(!e.waiting||e.pending.size>0)&&queueMicrotask(()=>{e.completed||e.pending.size>0||(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),e.hasError?e.deferred.reject(e.error):e.deferred.resolve())}))}trackLoadSubsetOperationPromise(e){const t=this.activeLoadSubsetOperation;!t||t.pending.has(e)||(t.pending.add(e),e.then(()=>this.settleLoadSubsetOperation(t,e,{ok:!0}),n=>this.settleLoadSubsetOperation(t,e,{ok:!1,error:n})))}trackLoadPromise(e){const t=this.loadSubsetSession,n=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),this.trackLoadSubsetOperationPromise(e),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:"start"});const i=()=>{if(t!==this.loadSubsetSession)return;const r=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),r&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"})};e.then(i,i)}getLoadSubsetSession(){return this.loadSubsetSession}loadSubset(e){if(e.signal?.aborted)return Promise.reject(new z);if(this.syncMode==="eager")return!0;if(this.syncStartDeferred){this.syncStartRequested=!0;const t=ne();return this.deferredLoadSubsets.push({options:e,deferred:t}),this.trackLoadPromise(t.promise),t.promise}if(this.syncLoadSubsetFn){const t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){if(this.syncMode!=="eager"){if(this.syncStartDeferred){this.deferredLoadSubsets=this.deferredLoadSubsets.filter(t=>t.options!==e?!0:(t.deferred.reject(new z),!1));return}this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}}cleanup(){const e=++this.syncEpoch;this.loadSubsetSession++,this.rejectPreload?.(new _s);const t=this.syncCleanupFn;this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null;try{t?.()}catch(r){this.syncEpoch===e&&(this.syncCleanupFn=t),queueMicrotask(()=>{if(r instanceof Error){const o=new nt(this.id,r);throw o.cause=r,o.stack=r.stack,o}else throw new nt(this.id,r)})}this.preloadPromise=null,this.syncStartDeferred=!1,this.syncStartRequested=!1;const n=this.pendingLoadSubsetPromises.size>0;this.pendingLoadSubsetPromises.clear(),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"}),this.activeLoadSubsetOperation=void 0;for(const r of this.loadSubsetOperations)r.completed||(r.completed=!0,r.pending.clear(),r.hasError=!0,r.error=new z,r.deferred?.reject(r.error));this.loadSubsetOperations.clear();const i=this.deferredLoadSubsets;this.deferredLoadSubsets=[];for(const r of i)r.deferred.reject(new z)}}function Un(s){if(typeof s=="function")return{cleanup:s};if(typeof s=="object")return s}const bt=1;function be(s,e){return s===e?0:s<e?-1:1}function Vn(s){return{kind:"constructor",...s.name?{name:s.name}:{}}}function H(s){if(s==null)return s;switch(typeof s){case"string":case"boolean":return s;case"number":return Number.isFinite(s)?s:null;case"bigint":return{__type:"bigint",value:s.toString()};case"function":case"symbol":return;case"undefined":return}if(Array.isArray(s))return s.map(n=>H(n)??null);if(s instanceof Date)return{__type:"date",value:s.toISOString()};if(s instanceof Set)return{__type:"set",values:Array.from(s).map(i=>H(i)??null).sort((i,r)=>be(Q(i),Q(r)))};if(s instanceof Map)return{__type:"map",entries:Array.from(s.entries()).map(([i,r])=>({key:H(i)??null,value:H(r)??null})).sort((i,r)=>be(Q(i.key),Q(r.key)))};if(s instanceof RegExp)return{__type:"regexp",value:s.toString()};const e={},t=Object.entries(s).sort(([n],[i])=>be(n,i));for(const[n,i]of t){const r=H(i);r!==void 0&&(e[n]=r)}return e}function Q(s){return s===null?"null":Array.isArray(s)?`[${s.map(Q).join(",")}]`:typeof s!="object"?JSON.stringify(s):`{${Object.keys(s).sort((n,i)=>be(n,i)).map(n=>`${JSON.stringify(n)}:${Q(s[n])}`).join(",")}}`}function $n(s,e,t,n,i){const r=Vn(n),o=H(e)??null,a=H(i),u=H({signatureVersion:bt,expression:o,options:a??null})??null,d=Q(u);return{signatureVersion:bt,signature:d,indexId:s,name:t,expression:e,resolver:r,...a===void 0?{}:{options:a}}}function Ke(s){if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(t=>Ke(t));const e={};for(const[t,n]of Object.entries(s))e[t]=Ke(n);return e}function zn(s){return JSON.parse(JSON.stringify(s))}class jn{constructor(){this.indexes=new Map,this.indexMetadata=new Map,this.indexCounter=0}setDeps(e){this.state=e.state,this.lifecycle=e.lifecycle,this.defaultIndexType=e.defaultIndexType,this.events=e.events}createIndex(e,t={}){this.lifecycle.validateCollectionUsable("createIndex");const n=++this.indexCounter,i=Kt(),r=e(i),o=M(r),a=t.indexType??this.defaultIndexType;if(!a)throw new te(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection:
3
+ import { BasicIndex } from '@tanstack/db'
4
+ createCollection({ defaultIndexType: BasicIndex, ... })`);const c=new a(n,o,t.name,t.options);c.build(this.state.entries()),this.indexes.set(n,c);const u=$n(n,o,t.name,a,t.options);return this.indexMetadata.set(n,u),this.events.emitIndexAdded(u),c}removeIndex(e){this.lifecycle.validateCollectionUsable("removeIndex");const t=typeof e=="number"?e:e.id,n=this.indexes.get(t);if(!n||typeof e!="number"&&n!==e)return!1;this.indexes.delete(t);const i=this.indexMetadata.get(t);return this.indexMetadata.delete(t),i&&this.events.emitIndexRemoved(i),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,t)=>e.indexId-t.indexId).map(e=>({...e,expression:zn(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:Ke(e.options)}}))}updateIndexes(e){for(const t of this.indexes.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.indexes.clear(),this.indexMetadata.clear()}}const qt=new WeakMap;function qn(s){return s!==null&&typeof s=="object"?qt.get(s)??s:s}const Nn=new Set(["find","findLast","findIndex","findLastIndex","filter","map","flatMap","forEach","some","every","reduce","reduceRight"]),Wn=new Set(["pop","push","shift","unshift","splice","sort","reverse","fill","copyWithin"]),Bn=new Set(["entries","keys","values","forEach"]);function de(s){return s!==null&&typeof s=="object"&&!(s instanceof Date)&&!(s instanceof RegExp)&&!j(s)}function Hn(s,e,t,n){if(Nn.has(s))return function(...i){const r=i[0];if(typeof r!="function")return e.apply(t.copy_,i);const o=(u,d)=>{if(de(u)){const h={tracker:t,prop:String(d)},{proxy:l}=n(u,h);return l}return u},a=function(u,d,h){const l=o(u,d);return r.call(this,l,d,h)};if(s==="reduce"||s==="reduceRight"){const u=function(d,h,l,f){const p=o(h,l);return r.call(this,d,p,l,f)};return e.apply(t.copy_,[u,...i.slice(1)])}const c=e.apply(t.copy_,[a,...i.slice(1)]);if((s==="find"||s==="findLast")&&c&&typeof c=="object"){const u=t.copy_.indexOf(c);if(u!==-1)return o(c,u)}return s==="filter"&&Array.isArray(c)?c.map(u=>{const d=t.copy_.indexOf(u);return d!==-1?o(u,d):u}):c}}function Gn(s,e){return function(){const t=s.copy_;let n=0;return{next(){if(n>=t.length)return{done:!0,value:void 0};const i=t[n];let r=i;if(de(i)){const o={tracker:s,prop:String(n)},{proxy:a}=e(i,o);r=a}return n++,{done:!1,value:r}},[Symbol.iterator](){return this}}}}function wt(s,e,t){return function(...n){const i=s.apply(e.copy_,n);return t(e),i}}function Yn(s,e,t,n,i){if(!(!Bn.has(s)&&e!==Symbol.iterator))return(...r)=>{const o=t.copy_,a=o instanceof Map;if(a&&s==="keys")return o.keys();const c=h=>de(h)?i(h,{tracker:t,prop:"",retainIdentity:!0}).proxy:h;if(s==="forEach"){const h=r[0];if(typeof h!="function")throw new TypeError("forEach callback must be a function");return o.forEach((l,f)=>{const p=c(l);h.call(r[1],p,a?f:p,n)})}const u=o.entries(),d=s==="entries"||a&&e===Symbol.iterator;return{next(){const h=u.next();if(h.done)return h;const[l,f]=h.value,p=c(f);return{done:!1,value:d?[a?l:p,p]:p}},[Symbol.iterator](){return this}}}}function V(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 i=[];return e.set(s,i),s.forEach((r,o)=>{i[o]=V(r,e)}),i}if(ArrayBuffer.isView(s)&&!(s instanceof DataView)){const i=Object.getPrototypeOf(s).constructor,r=new i(s.length);e.set(s,r);for(let o=0;o<s.length;o++)r[o]=s[o];return r}if(s instanceof Map){const i=new Map;return e.set(s,i),s.forEach((r,o)=>{i.set(o,V(r,e))}),i}if(s instanceof Set){const i=new Set;return e.set(s,i),s.forEach(r=>{i.add(V(r,e))}),i}if(j(s))return s;const t={};e.set(s,t);for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&(t[i]=V(s[i],e));const n=Object.getOwnPropertySymbols(s);for(const i of n)t[i]=V(s[i],e);return t}function We(s,e){const t=new Map;function n(l,f){if(t.has(l))return t.get(l);{const p=We(l,f);return t.set(l,p),p}}const i=new Map,r=e?.tracker.valueCopies??new WeakMap,o={valueCopies:r,copy_:e?r.get(s)??s:V(s,r),originalObject:V(s),modified:!1,assigned_:{},parent:e,target:s};function a(l){l.modified||(l.modified=!0),l.parent&&(l.parent.retainIdentity||(l.parent.tracker.copy_[l.parent.prop]=l.copy_,l.parent.tracker.assigned_[l.parent.prop]=!0),a(l.parent.tracker))}function c(l){if(l.copy_ instanceof Map||l.copy_ instanceof Set)return F(Array.from(l.copy_),Array.from(l.originalObject));if(Object.keys(l.assigned_).length===0&&Object.getOwnPropertySymbols(l.assigned_).length===0)return!0;for(const p in l.assigned_)if(l.assigned_[p]===!0){const y=l.copy_[p],b=l.originalObject[p];if(!F(y,b))return!1}else if(l.assigned_[p]===!1)return!1;const f=Object.getOwnPropertySymbols(l.assigned_);for(const p of f)if(l.assigned_[p]===!0){const y=l.copy_[p],b=l.originalObject[p];if(!F(y,b))return!1}else if(l.assigned_[p]===!1)return!1;return!0}function u(l){c(l)&&(l.modified=!1,l.assigned_={},l.parent&&u(l.parent.tracker))}function d(l){if(i.has(l))return i.get(l);const f=new Proxy(l,{get(p,y,b){const w=o.copy_[y]??o.originalObject[y];if(Object.getOwnPropertyDescriptor(p,y)?.get)return w;if(typeof w=="function"){if(Array.isArray(p)){const v=y.toString();if(Wn.has(v))return wt(w,o,a);const k=Hn(v,w,o,n);if(k)return k;if(y===Symbol.iterator)return Gn(o,n)}if(p instanceof Map||p instanceof Set){const v=y.toString(),k=x=>{const E=qn(x);return E!==null&&typeof E=="object"?r.get(E)??E:E};if(v==="has"||v==="delete"||v==="add"||v==="set")return(...x)=>{p instanceof Set?x[0]=k(x[0]):v==="set"&&(x[1]=k(x[1]));const E=w.apply(p,x);return v!=="has"&&a(o),E===p?b:E};if(p instanceof Map&&v==="get")return x=>{const E=p.get(x);return de(E)?n(E,{tracker:o,prop:"",retainIdentity:!0}).proxy:E};if(v==="clear")return wt(w,o,a);const D=Yn(v,y,o,b,n);if(D)return D}return w.bind(p)}if(de(w)){const v={tracker:o,prop:String(y)},{proxy:k}=n(w,v);return i.set(w,k),k}return w},set(p,y,b){const w=o.copy_[y];if(!F(w,b)){const C=o.originalObject[y];F(b,C)?(delete o.assigned_[y.toString()],o.copy_[y]=V(C),c(o)?(o.modified=!1,o.assigned_={},e&&u(e.tracker)):o.modified=!0):(o.copy_[y]=b,o.assigned_[y.toString()]=!0,a(o))}return!0},defineProperty(p,y,b){const w=Reflect.defineProperty(p,y,b);return w&&"value"in b&&(o.copy_[y]=V(b.value),o.assigned_[y.toString()]=!0,a(o)),w},getOwnPropertyDescriptor(p,y){return Reflect.getOwnPropertyDescriptor(p,y)},preventExtensions(p){return Reflect.preventExtensions(p)},isExtensible(p){return Reflect.isExtensible(p)},deleteProperty(p,y){const b=typeof y=="symbol"?y.toString():y;if(b in p){const w=b in o.originalObject,C=Reflect.deleteProperty(p,y);return C&&(w?(o.assigned_[b]=!1,a(o)):(delete o.assigned_[b],Object.keys(o.assigned_).length===0&&Object.getOwnPropertySymbols(o.assigned_).length===0?o.modified=!1:o.modified=!0)),C}return!0}});return i.set(l,f),qt.set(f,o.copy_),f}return{proxy:d(o.copy_),getChanges:()=>{if(!o.modified)return{};if(typeof o.copy_!="object"||Array.isArray(o.copy_)||Object.keys(o.assigned_).length===0)return o.copy_;const l={},f=Object.keys(o.assigned_).some(p=>typeof o.copy_[p]=="object");for(const p in o.copy_){const y=o.copy_[p],b=o.originalObject[p];(o.assigned_[p]===!0||f&&o.copy_[p]!==o.copy_&&!F(y instanceof Set?Array.from(y):y,b instanceof Set?Array.from(b):b))&&p in o.copy_&&(l[p]=o.copy_[p])}return l}}}function Jn(s){const e=s.map(t=>We(t));return{proxies:e.map(t=>t.proxy),getChanges:()=>e.map(t=>t.getChanges())}}function Qn(s,e){const{proxy:t,getChanges:n}=We(s);return e(t),V(n())}function Zn(s,e){const{proxies:t,getChanges:n}=Jn(s);return e(t),V(n())}class Xn{constructor(){this.transactions=[],this.transactionStack=[],this.sequenceNumber=0}createTransaction(e){const t=new ii(e,this,this.sequenceNumber++);return this.transactions.push(t),t}getActiveTransaction(){return this.transactionStack.at(-1)}getActiveTransactionForCollection(){const e=this.getActiveTransaction();if(e)return e;if(this!==ke)return ke.claimActiveTransaction(this)}claimActiveTransaction(e){const t=this.getActiveTransaction();if(!t)return;const n=ce(t);if(n===e)return t;if(n!==this)throw new Error("A transaction created with createTransaction() cannot mutate collections from multiple DbClient instances. Use dbClient.createTransaction() for explicit client scope.");return this.removeTransaction(t),e.transactions.push(t),e.transactionStack.push(t),t.sequenceNumber=e.sequenceNumber++,Be.set(t,e),t}registerTransaction(e){ue.clear(e.id),this.transactionStack.push(e)}unregisterTransaction(e){try{ue.flush(e.id)}finally{this.transactionStack=this.transactionStack.filter(t=>t.id!==e.id)}}removeTransaction(e){const t=this.transactions.findIndex(n=>n.id===e.id);t!==-1&&this.transactions.splice(t,1)}rollbackConflictingTransactions(e,t){for(const n of[...this.transactions])n!==e&&n.state==="pending"&&n.mutations.some(i=>t.has(i.globalKey))&&n.rollback({isSecondaryRollback:!0})}clear(){const e=new Set([...this.transactions.map(t=>t.id),...this.transactionStack.map(t=>t.id)]);for(const t of e)ue.clear(t);this.transactions=[],this.transactionStack=[]}}const ke=new Xn,Be=new WeakMap,Nt=new WeakMap;function ce(s){const e=Be.get(s);if(!e)throw new Error("Transaction is not associated with a TransactionScope.");return e}function ei(s){const e=Nt.get(s);if(!e)throw new Error("Transaction is not associated with an ambient scope.");return e}function ti(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 si(s){return ke.createTransaction(s)}function ni(){return ke.getActiveTransaction()}class ii{constructor(e,t,n){if(typeof e.mutationFn>"u")throw new Rs;this.id=e.id??le(),this.mutationFn=e.mutationFn,this.state="pending",this.mutations=[],this.isPersisted=ne(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=n,this.metadata=e.metadata??{},Be.set(this,t),Nt.set(this,t)}setState(e){this.state=e,(e==="completed"||e==="failed")&&ce(this).removeTransaction(this)}mutate(e){if(this.state!=="pending")throw new Os;const t=ce(this),n=new Set([t,ei(this)]);for(const i of n)i.registerTransaction(this);try{e()}finally{n.add(ce(this));for(const i of n)i.unregisterTransaction(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){const t=new Map;for(const n of this.mutations)t.set(n.globalKey,n);for(const n of e){const i=t.get(n.globalKey);if(i){const r=ti(i,n);r===null?t.delete(n.globalKey):t.set(n.globalKey,r)}else t.set(n.globalKey,n)}this.mutations.length=0;for(const n of t.values())this.mutations.push(n)}rollback(e){const t=e?.isSecondaryRollback??!1;if(this.state==="completed")throw new Ts;if(this.state==="failed")return this;if(this.setState("failed"),!t){const n=new Set(this.mutations.map(i=>i.globalKey));ce(this).rollbackConflictingTransactions(this,n)}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 Es;if(this.setState("persisting"),this.mutations.length===0)return this.setState("completed"),this.isPersisted.resolve(this),this;try{if(await this.mutationFn({transaction:this}),this.state!=="persisting")return this;this.setState("completed"),this.touchCollection(),this.isPersisted.resolve(this)}catch(e){if(this.state!=="persisting")return this;const t=B(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 ri{constructor(e,t){this.insert=(n,i)=>{this.lifecycle.validateCollectionUsable("insert");const r=this.state,o=this.getActiveTransaction();if(!o&&!this.config.onInsert)throw new vs;const a=Array.isArray(n)?n:[n],c=[],u=new Set;if(a.forEach(d=>{const h=this.validateData(d,"insert"),l=this.config.getKey(h);if(this.state.has(l)||u.has(l))throw new fs(l);u.add(l);const f=this.generateGlobalKey(l,d),p={mutationId:le(),original:{},modified:h,changes:Object.fromEntries(Object.keys(d).map(y=>[y,h[y]])),globalKey:f,key:l,metadata:i?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:i?.optimistic??!0,type:"insert",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(p)}),o)return o.applyMutations(c),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;{const d=this.createTransaction({metadata:{[ge]:!0},mutationFn:async h=>await this.config.onInsert({transaction:h.transaction,collection:this.collection})});return d.applyMutations(c),this.markPendingLocalOrigins(c),d.commit().catch(()=>{}),r.transactions.set(d.id,d),r.scheduleTransactionCleanup(d),r.recomputeOptimisticState(!0),d}},this.delete=(n,i)=>{const r=this.state;this.lifecycle.validateCollectionUsable("delete");const o=this.getActiveTransaction();if(!o&&!this.config.onDelete)throw new Cs;if(Array.isArray(n)&&n.length===0)throw new bs;const a=Array.isArray(n)?n:[n],c=[];for(const d of a){if(!this.state.has(d))throw new ws(d);const h=this.generateGlobalKey(d,this.state.get(d)),l={mutationId:le(),original:this.state.get(d),modified:this.state.get(d),changes:this.state.get(d),globalKey:h,key:d,metadata:i?.metadata,syncMetadata:r.syncedMetadata.get(d)||{},optimistic:i?.optimistic??!0,type:"delete",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(l)}if(o)return o.applyMutations(c),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;const u=this.createTransaction({autoCommit:!0,metadata:{[ge]:!0},mutationFn:async d=>this.config.onDelete({transaction:d.transaction,collection:this.collection})});return u.applyMutations(c),this.markPendingLocalOrigins(c),u.commit().catch(()=>{}),r.transactions.set(u.id,u),r.scheduleTransactionCleanup(u),r.recomputeOptimisticState(!0),u},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}setTransactionScope(e){this.transactionScope=e}getActiveTransaction(){return this.transactionScope?this.transactionScope.getActiveTransactionForCollection():ni()}createTransaction(e){return this.transactionScope?this.transactionScope.createTransaction(e):si(e)}ensureStandardSchema(e){if(e&&"~standard"in e)return e;throw new os}validateData(e,t,n){if(!this.config.schema)return e;const i=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=i["~standard"].validate(a);if(c instanceof Promise)throw new st;if("issues"in c&&c.issues){const l=c.issues.map(f=>({message:f.message,path:f.path?.map(p=>String(p))}));throw new tt(t,l)}const u=c.value,d=Object.keys(e);return Object.fromEntries(d.map(l=>[l,u[l]]))}}const r=i["~standard"].validate(e);if(r instanceof Promise)throw new st;if("issues"in r&&r.issues){const o=r.issues.map(a=>({message:a.message,path:a.path?.map(c=>String(c))}));throw new tt(t,o)}return r.value}generateGlobalKey(e,t){if(typeof e!="string"&&typeof e!="number")throw typeof e>"u"?new ds(t):new hs(e,t);return`KEY::${this.id}/${e}`}markPendingLocalOrigins(e){for(const t of e)this.state.pendingLocalOrigins.add(t.key)}update(e,t,n){if(typeof e>"u")throw new ys;const i=this.state;this.lifecycle.validateCollectionUsable("update");const r=this.getActiveTransaction();if(!r&&!this.config.onUpdate)throw new ks;const o=Array.isArray(e),a=o?e:[e];if(o&&a.length===0)throw new ms;const c=typeof t=="function"?t:n,u=typeof t=="function"?{}:t,d=a.map(p=>{const y=this.state.get(p);if(!y)throw new gs(p);return y});let h;o?h=Zn(d,c):h=[Qn(d[0],c)];const l=a.map((p,y)=>{const b=h[y];if(!b||Object.keys(b).length===0)return null;const w=d[y],C=this.validateData(b,"update",p),v=Object.assign({},w,C),k=this.config.getKey(w),D=this.config.getKey(v);if(k!==D)throw new Ss(k,D);const x=this.generateGlobalKey(D,v);return{mutationId:le(),original:w,modified:v,changes:Object.fromEntries(Object.keys(b).map(E=>[E,v[E]])),globalKey:x,key:p,metadata:u.metadata,syncMetadata:i.syncedMetadata.get(p)||{},optimistic:u.optimistic??!0,type:"update",createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(l.length===0){const p=this.createTransaction({mutationFn:async()=>{}});return p.commit().catch(()=>{}),i.scheduleTransactionCleanup(p),p}if(r)return r.applyMutations(l),i.transactions.set(r.id,r),i.scheduleTransactionCleanup(r),i.recomputeOptimisticState(!0),r;const f=this.createTransaction({metadata:{[ge]:!0},mutationFn:async p=>this.config.onUpdate({transaction:p.transaction,collection:this.collection})});return f.applyMutations(l),this.markPendingLocalOrigins(l),f.commit().catch(()=>{}),i.transactions.set(f.id,f),i.scheduleTransactionCleanup(f),i.recomputeOptimisticState(!0),f}}class oi extends $t{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t,n){if(this.emitInnerWhile("status:change",{type:"status:change",collection:this.collection,previousStatus:t,status:e},n),!n())return;const i=`status:${e}`;this.emitInnerWhile(i,{type:i,collection:this.collection,previousStatus:t,status:e},n)}emitSubscribersChange(e,t){this.emit("subscribers:change",{type:"subscribers:change",collection:this.collection,previousSubscriberCount:t,subscriberCount:e})}emitIndexAdded(e){this.emit("index:added",{type:"index:added",collection:this.collection,index:e})}emitIndexRemoved(e){this.emit("index:removed",{type:"index:removed",collection:this.collection,index:e})}cleanup(){this.clearListeners()}}function ai(s){const e=new ci(s);return s.utils?e.utils=s.utils:e.utils={},e}class ci{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(t,n)=>this._mutations.insert(t,n),this.delete=(t,n)=>this._mutations.delete(t,n),!e)throw new is;if(!e.sync)throw new rs;if(e.id?this.id=e.id:this.id=le(),this.config={...e,autoIndex:e.autoIndex??"off"},this.config.autoIndex==="eager"&&!e.defaultIndexType)throw new te(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it:
5
+ import { BasicIndex } from '@tanstack/db'
6
+ createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);ss(this),this._changes=new Pn,this._events=new oi,this._indexes=new jn,this._lifecycle=new Ln(e,this.id),this._mutations=new ri(e,this.id),this._state=new Sn(e),this._sync=new Fn(e,this.id),this.comparisonOpts=li(e),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events,state:this._state}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:e.defaultIndexType,events:this._events}),this._lifecycle.setDeps({changes:this._changes,events:this._events,indexes:this._indexes,state:this._state,sync:this._sync}),this._mutations.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this._changes,indexes:this._indexes,events:this._events}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this._events}),e.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get subscriberCount(){return this._changes.activeSubscribersCount}get _stateRevision(){return this._changes.stateRevision}get _layoutRevision(){return this._changes.layoutRevision}_subscribeLayoutChanges(e){return this._changes.subscribeLayoutChanges(e)}_markLayoutChange(){this._sync.markLayoutChange()}_deferPublication(){return this._changes.deferPublication()}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status==="ready"}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}_setTransactionScope(e){this._mutations.setTransactionScope(e)}_hasHydratedKey(e){return this._state.hydratedKeys.has(e)}_deferSyncStart(){return this._sync.deferStart()}_resumeSyncStart(){this._sync.resumeStart()}preload(){return this._sync.preload()}get(e){return this._state.getWithVirtualProps(e)}has(e){return this._state.has(e)}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){for(const e of this._state.keys()){const t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(const e of this._state.keys()){const t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let t=0;for(const[n,i]of this.entries())e(i,n,t++)}map(e){const t=[];let n=0;for(const[i,r]of this.entries())t.push(e(r,i,n++));return t}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,t={}){return this._indexes.createIndex(e,t)}removeIndex(e){return this._indexes.removeIndex(e)}getIndexMetadata(){return this._indexes.getIndexMetadataSnapshot()}get indexes(){return this._indexes.indexes}validateData(e,t,n){return this._mutations.validateData(e,t,n)}get compareOptions(){return{...this.comparisonOpts}}update(e,t,n){return this._mutations.update(e,t,n)}get state(){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 yn(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 li(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"}}const Wt=/^[a-z][a-z0-9+.-]*:/iu;function He({descriptor:s,table:e,database:t}){if(typeof t.getDialect!="function"||typeof e.getColumns!="function")return c=>c;const n=t.getDialect().getUriResolver(),i=e.getColumns(),r=[...he(s,e).values()].filter(c=>c.descriptor.type==="uri"&&!c.descriptor.secret&&c.column!==void 0),o=new Map,a=new Map;for(const c of Object.values(t.getSchema()??{})){if(!c||typeof c.getType!="function")continue;o.set(c.config.name,c);const u=c.getType();a.set(u,[...a.get(u)??[],c])}return c=>{const u=c,d={...u},h=Ye(s,e,u,{resourceId:String(u.id??"")});for(const l of r){const f=i[l.column];if(!f)continue;const p=b=>typeof b=="string"?n.resolveLink(b,f,{currentTable:e,record:h,tableNameRegistry:o,tableRegistry:a}):b,y=u[l.field];d[l.field]=l.descriptor.array&&Array.isArray(y)?y.map(p):p(y)}return d}}function ui(s){const e=s.getMapping(),t=new Map;for(const[n,i]of Object.entries(e.columns))i.predicate!=="@id"&&t.set(n,i.predicate);return t}function he(s,e){const t=new Map;for(const[i,r]of ui(e))t.set(r,i);const n=new Map;for(const[i,r]of Object.entries(s.fields))n.set(i,{field:i,descriptor:r,column:t.get(r.predicate)});return n}function di(s){return Jt(s.storage.resourceIdPattern)}function hi(s,e){const t=e.getType();if(s.class!==t)throw new U("mapping_class_mismatch",`descriptor ${s.uri} declares class ${s.class} but table ${e.config.name} reads ${t}`)}function Ge(s){return new Set(Object.entries(s.fields).filter(([,e])=>e.secret===!0).map(([e])=>e))}function Bt(s){const e=Ge(s);return Object.entries(s.fields).filter(([t])=>!e.has(t)).sort(([,t],[,n])=>t.predicate<n.predicate?-1:t.predicate>n.predicate?1:0).map(([t])=>t)}function fi(s){return typeof s=="object"&&s!==null&&typeof s.termType=="string"&&typeof s.value=="string"}function pi(s){const e=s.datatype;if(e)return typeof e=="string"?e:e.value}function vt(s,e){if(e==null||e==="")return;const t=fi(e)?e:void 0,n=t?t.value:e,i=t?pi(t):void 0;switch(s.type){case"uri":return t&&t.termType!=="NamedNode",String(n);case"string":case"text":return String(n);case"number":{if(typeof n=="number")return n;const r=Number(n);return Number.isFinite(r)?r:void 0}case"boolean":return typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:!!n;case"timestamp":{const r=n instanceof Date?n:new Date(String(n));return Number.isNaN(r.getTime())?void 0:r}case"json":{if(!t)return e;if(i&&!/#json(Array)?$/u.test(i)&&n==="")return;try{return JSON.parse(String(n))}catch{return n}}default:return n}}function yi(s,e){if(s.array){if(e==null)return;const n=(Array.isArray(e)?e:[e]).map(i=>vt(s,i)).filter(i=>i!==void 0);return n.length>0?n:void 0}return vt(s,e)}function mi(s,e,t){const n=he(s,e),i=di(s),r=Ge(s),o=[];for(const a of t){const c=Yt(s,a);if(c===void 0)continue;const u={id:c};i!=="id"&&(u[i]=c);const d=a["@id"]??a.uri??a.subject;typeof d=="string"&&(u["@id"]=d);for(const h of n.values()){if(r.has(h.field)||h.column===void 0)continue;const l=yi(h.descriptor,a[h.column]);l!==void 0&&(u[h.field]=l)}o.push(u)}return o}function Ye(s,e,t,n){const i=he(s,e),r={id:n.resourceId};for(const[o,a]of Object.entries(t)){if(o==="id"||o==="@id")continue;const c=i.get(o);!c||c.column===void 0||n.includeField&&!n.includeField(o)||(r[c.column]=a)}return r}function Je(s){return s.array===!0&&s.type==="uri"}function Fe(s,e){return(Array.isArray(s)?s:[s]).filter(t=>typeof t=="string"&&t.length>0).map(t=>Wt.test(t)?t:new URL(t,e).toString())}function kt(s,e,t,n){const i={...t},r=Ye(s,e,t,{resourceId:n.resourceId}),o=he(s,e),a=new Set([e]);for(const d of Object.values(n.database.schema??{}))d&&typeof d=="object"&&"config"in d&&"columns"in d&&a.add(d);const c=new Map,u=new Map;for(const d of a){c.set(d.config.name,d);const h=d.getType();u.set(h,[...u.get(h)??[],d])}for(const[d,h]of o){const l=i[d];if(h.descriptor.type!=="uri"||l===void 0||l===null)continue;if(h.descriptor.array){i[d]=Fe(l,n.document);continue}if(!h.column||typeof l!="string"||!l||Wt.test(l))continue;const f=n.database.getDialect().getUriResolver();i[d]=f.resolveLink(l,e.columns[h.column],{baseUri:n.podUrl,tableRegistry:u,tableNameRegistry:c,currentTable:e,record:r})}return i}async function gi(s,e){return typeof s.isInitialized!="function"||s.isInitialized()||await e.init?.(s),await e.select().from(s).execute()}async function Si(s,e={}){return{etag:void 0,subjects:(await gi(s.table,s.database)).filter(n=>Qt(s.descriptor,s.document,s.podUrl,n))}}function bi(s){const t=s.getDialect?.()?.config?.session?.fetch;return typeof t=="function"?t:void 0}const wi=new Set;function ie(s){const e=s,t={};for(const[n,i]of Object.entries(e))n.startsWith("$")||(t[n]=i);return t}function ee(s){if(s instanceof Date)return s.toISOString();if(Array.isArray(s))return s.map(e=>ee(e));if(s&&typeof s=="object"){if(s instanceof Set)return[...s].map(t=>ee(t));const e=Object.entries(s).filter(([,t])=>t!==void 0).sort(([t],[n])=>t<n?-1:t>n?1:0);return Object.fromEntries(e.map(([t,n])=>[t,ee(n)]))}return s}function Ht(s,e){const t=ie(s),n={};t.id!==void 0&&(n.id=ee(t.id));for(const i of e)t[i]!==void 0&&(n[i]=ee(t[i]));return JSON.stringify(n)}function vi(s,e){return s===void 0||e===void 0?s===e:JSON.stringify(ee(s))===JSON.stringify(ee(e))}function ki(s,e,t=wi){if(s===void 0)return!1;const n=ie(s),i=ie(e);for(const[r,o]of Object.entries(i))if(!(r==="@id"||o===void 0)&&!t.has(r)&&!vi(n[r],o))return!1;return!0}function Ci(s){const e=new Set(s.presentKeys),t=[],n=[],i=[],r=o=>{const a=s.knownHash(o);if(a!==void 0)return a;const c=s.presentRow?.(o);return c===void 0?void 0:s.hashOf(c)};for(const[o,a]of s.next){if(s.pendingKeys.has(o)){e.has(o)&&r(o)!==s.hashOf(a)&&n.push({key:o,row:a});continue}if(!e.has(o)){t.push({key:o,row:a});continue}r(o)!==s.hashOf(a)&&n.push({key:o,row:a})}for(const o of e){if(s.next.has(o)||s.pendingKeys.has(o))continue;const a=s.presentRow?.(o);a!==void 0&&i.push({key:o,row:a})}return{inserts:t,updates:n,deletes:i}}function Ri(){let s;return{promise:new Promise(t=>{s=()=>t()}),resolve:s}}function Oi(s){const e=new Set,t=new Map,n=[],i=a=>{e.delete(a),t.delete(a)};return{keys:e,entries:t,conflicts:n,register:a=>{i(a.key);const c=Ri(),u={...a,settled:!1,error:void 0,settledPromise:c.promise,resolveSettled:c.resolve};return t.set(a.key,u),e.add(a.key),u},clear:i,settle:(a,c)=>{a.settled||(a.error=c,a.settled=!0,a.resolveSettled())},isConfirmed:a=>t.get(a)?.settled===!0&&t.get(a)?.error===void 0,recordConflict:a=>{n.push(a),s?.(a)}}}function Ct(s,e,t){s.recordConflict({key:e.key,server:t,local:e.localRow??e.intent??t,at:Date.now()}),s.settle(e,new U("write_conflict",`row ${e.key} was changed by someone else; server wins`))}function Ti(s,e,t,n=Ei,i){const r=i?He(i):o=>o;for(const o of s.entries.values()){if(o.settled)continue;const a=e.get(o.key);if(o.intent===void 0){if(a===void 0){s.settle(o);continue}o.beforeHash!==void 0&&t(a)!==o.beforeHash&&Ct(s,o,a);continue}if(ki(a&&r(a),r(o.intent),n)){s.settle(o);continue}if(a!==void 0&&t(a)!==o.beforeHash){Ct(s,o,a);continue}a===void 0&&o.beforeHash!==void 0&&s.settle(o,new U("write_conflict",`row ${o.key} disappeared before the write was confirmed; server wins`))}}const Ei=new Set;async function xi(s,e,t){const n=s.descriptor.fields[e];if(!n||!Je(n))throw new U("write_field_not_uri_array",`field ${e} is not array+uri; it must go through the ORM`);const i=Zt(s.document),r=Fe(t.previous,i),o=Fe(t.next,i),a=h=>h.map(l=>`<${t.subjectIri}> <${n.predicate}> <${l}> .`).join(`
7
+ `),c=[r.length>0?`DELETE DATA { ${a(r)} }`:void 0,o.length>0?`INSERT DATA { ${a(o)} }`:void 0].filter(h=>h!==void 0);if(c.length===0)return;const u=s.authenticatedFetch??bi(s.database);if(!u)throw new U("write_field_no_fetch","array+uri fields need an authenticated fetch (SolidAuthSession.fetch); none available");const d=await u(i,{method:"PATCH",headers:{"content-type":"application/sparql-update"},body:c.join(`;
8
+ `)});if(!d.ok)throw new U("write_field_rejected",`SPARQL PATCH for ${e} failed with HTTP ${d.status}`)}function Di(s){const{descriptor:e,table:t,pending:n}=s,i=Bt(e),r=He(s),o=h=>Ht(r(h),i),a=new Set(Object.entries(e.fields).filter(([,h])=>Je(h)).map(([h])=>h)),c=he(e,t),u=h=>c.get(h)?.column,d=async(h,l)=>{try{await l()}catch(f){throw n.clear(h),f instanceof Error?f:new U("write_failed",String(f),{cause:f})}try{await s.confirm(h)}finally{n.clear(h)}};return{onInsert:async({transaction:h})=>{for(const l of h.mutations){const f=String(l.key),p=Te(e,s.document,s.podUrl,f),y=Qe(e,s.document,f),b=kt(e,t,l.modified,{database:s.database,podUrl:s.podUrl,document:s.document,resourceId:p});Object.assign(l.modified,b),n.register({key:f,intent:b,localRow:b,beforeHash:void 0}),await d(f,async()=>{const w=Ye(e,t,b,{resourceId:p,includeField:C=>!a.has(C)});await s.database.insert(t).values(w).execute(),await Rt(s,b,y,void 0,b)})}},onUpdate:async({transaction:h})=>{for(const l of h.mutations){const f=String(l.key),p=l.original,y=l.changes,b=Te(e,s.document,s.podUrl,f),w=Qe(e,s.document,f),C=kt(e,t,l.modified,{database:s.database,podUrl:s.podUrl,document:s.document,resourceId:b});Object.assign(l.modified,C);const v=p&&Object.keys(p).length>0?o(p):void 0;n.register({key:f,intent:C,localRow:C,beforeHash:v}),await d(f,async()=>{const k={};for(const D of Object.keys(y)){if(a.has(D))continue;const x=u(D);x!==void 0&&(k[x]=C[D])}if(Object.keys(k).length>0&&!await s.database.updateById(t,b,k))throw new U("write_rejected",`drizzle-solid did not update ${b}`);await Rt(s,y,w,p,C)})}},onDelete:async({transaction:h})=>{for(const l of h.mutations){const f=String(l.key),p=l.original,y=Te(e,s.document,s.podUrl,f);n.register({key:f,intent:void 0,localRow:p,beforeHash:p&&Object.keys(p).length>0?o(p):void 0}),await d(f,async()=>{await s.database.deleteById(t,y)})}}}}async function Rt(s,e,t,n,i){for(const[r,o]of Object.entries(s.descriptor.fields))Je(o)&&r in e&&await xi(s,r,{subjectIri:t,previous:n?.[r],next:i?.[r]})}const _e={available:!1,unsubscribe:()=>{}};function Ii(s,e,t){if(!s||typeof s.watch!="function")return _e;try{const n=s.watch(e,t);if(typeof n!="function")return _e;let i=!0;return{available:!0,unsubscribe:()=>{i&&(i=!1,n())}}}catch{return _e}}const Pi=75,Ai=2;function _i(s){return new Promise(e=>{setTimeout(e,s)})}function Mi(s){const{descriptor:e,table:t,database:n,document:i,podUrl:r,pending:o}=s,a=s.coalesceMs??Pi,c=s.confirmRetries??Ai,u=Bt(e),d=Ge(e),h=He(s),l=T=>Ht(h(T),u);let f,p,y=!1,b=!1,w=!1,C="initializing",v,k=[],D,x=!1,E=!1,m;async function S(){if(f)return f;const T=s.collection();if(!T)throw new U("sync_not_started","collection has not started syncing yet");if(await T.preload(),!f)throw new U("sync_not_started","collection sync did not start");return f}function g(){E||v!==void 0||(v=setTimeout(()=>{v=void 0,R().catch(()=>{C="degraded"})},a))}function R(){if(D)return x=!0,D;const T=(async()=>{try{do x=!1,await O();while(x&&!E)}finally{D=void 0}})();return D=T,T}async function O(){const T=await S();if(E)return;let L;try{L=await Si({descriptor:e,table:t,database:n,document:i,podUrl:r},{ifNoneMatch:m})}catch(I){C="degraded",!b&&!w&&(w=!0,T.markError(I));return}L.etag!==void 0&&(m=L.etag);const J=mi(e,t,L.subjects),fe=new Map(J.map(I=>[String(I.id),I])),Oe=[...T.collection.keys()].map(I=>String(I)),Gt=I=>T.metadata?.row.get(I)?.hash,W=Ci({next:fe,presentKeys:Oe,pendingKeys:o.keys,knownHash:Gt,hashOf:l,presentRow:I=>T.collection.get(I)});if(W.inserts.length+W.updates.length+W.deletes.length>0){T.begin({immediate:!0});for(const I of W.inserts)T.write({type:"insert",value:ie(I.row)});for(const I of W.updates)T.write({type:"update",value:ie(I.row)});for(const I of W.deletes)T.write({type:"delete",key:I.key,value:ie(I.row)});for(const I of[...W.inserts,...W.updates])T.metadata?.row.set(I.key,{hash:l(I.row)});await T.commit()}b||(b=!0,w=!1,T.markReady()),Ti(o,fe,l,d,s),C=y?"live":"unavailable"}async function A(T){const L=o.entries.get(T);if(L)for(let J=0;;J+=1){if(await R(),L.settled){if(L.error)throw L.error;return}if(J>=c)throw new U("write_unconfirmed",`write to ${T} was not visible in the document after ${c+1} reads`);await _i(a)}}const $=T=>E?()=>{}:(f=T,p=Ii(s.feed,i,()=>{if(!b){k.push({topic:i});return}g()}),y=p.available,R().then(()=>{if(E)return;const L=k;k=[],L.length>0&&g()}).catch(()=>{C="degraded"}),()=>{K()});function K(){E||(E=!0,v!==void 0&&(clearTimeout(v),v=void 0),p?.unsubscribe(),p=void 0,k=[])}return{sync:$,refresh:()=>R(),confirmPending:A,state:()=>C,dispose:K,truncate:()=>{!f||E||(f.begin({immediate:!0}),f.truncate(),Promise.resolve(f.commit()).catch(()=>{}))}}}function Li(s,e){hi(s,e.table);const t=Tt(s,{podUrl:e.podUrl,document:e.document,scope:e.scope}),n=Oi(e.onConflict);let i;const r=Mi({descriptor:s,table:e.table,database:e.database,podUrl:e.podUrl,document:t,feed:e.feed,coalesceMs:e.coalesceMs,confirmRetries:e.confirmRetries,pending:n,collection:()=>i}),o=Di({descriptor:s,table:e.table,database:e.database,podUrl:e.podUrl,document:t,pending:n,confirm:c=>r.confirmPending(c)}),a=ai({id:`pod-collection:${s.uri}:${t}`,getKey:c=>c.id,sync:{sync:r.sync,rowUpdateMode:"full"},startSync:!0,onInsert:o.onInsert,onUpdate:o.onUpdate,onDelete:o.onDelete});return i=a,Object.assign(a,{tableDocument:t,pendingKeys:n.keys,conflicts:n.conflicts,refresh:()=>r.refresh(),syncState:()=>r.state(),dispose:()=>r.dispose(),truncateForTest:()=>r.truncate()})}function Ot(s){const e=s;if(typeof e.syncState!="function"||typeof e.dispose!="function")throw new U("collection_not_from_define","collection was not created by definePodCollection()");return e}function Ui(s){const e=new Map,t=new Set;let n;const i=()=>{for(const a of[...t])a()},r=(a,c)=>`${a.uri}\0${c}`,o=(a,c)=>{const u=Tt(a,{podUrl:s.podUrl,document:c.document,scope:c.scope}),d=r(a,u),h=e.get(d);if(h)return h;const l=Li(a,{...c,database:s.database,podUrl:s.podUrl,feed:s.feed});return e.set(d,l),l.preload().then(i,i),l};return{define:o,async load(a,c){return o(a,c)},syncState(a){return Ot(a).syncState()},subscribeSyncState(a){return t.add(a),t.size===1&&typeof s.feed?.subscribeState=="function"&&(n=s.feed.subscribeState(i)),()=>{t.delete(a),t.size===0&&(n?.(),n=void 0)}},dispose(){for(const a of e.values())Ot(a).dispose();e.clear(),n?.(),n=void 0,i()}}}export{Ui as createPodCollectionsCapability};
@@ -1 +1 @@
1
- import{r as c,j as $t}from"./dashboard-Or0gnkou.js";import{r as bt,g as J,b as Gt,c as Y,s as ct,d as yt,A as Wt}from"./account-session-DlcKNG7k.js";const Xt="Cloud storage is not ready. Please wait for Xpod to reconnect and try again.",Et=new WeakMap;function it(){typeof window<"u"&&Et.delete(window)}function Jt(t){typeof window<"u"&&Et.set(window,t)}function Yt(t){try{sessionStorage.setItem("provisionCode",t)}catch{}}async function gn(t){const n=kt(t.accountIndex);if(!n)return;const e=ut(t);let o;try{o=await e(n,{headers:{accept:"application/json"},credentials:"omit"})}catch{return}if(!o.ok)return;const f=(await o.json().catch(()=>{}))?.controls?.account?.clientCredentials;if(typeof f!="string"||!f)return;const l=await bt(f,e,n);if(!l)return;const w=new URL(l,n);return w.origin===new URL(n).origin&&w.pathname.startsWith("/.account/")&&!w.username&&!w.password&&!w.hash?{collection:l,webId:t.webId}:void 0}function ut(t){const n=kt(t.accountIndex);return async(e,o)=>{if(t.assertCurrent?.(),!n)throw new Error("Invalid session Account authority");const s=new Headers(e instanceof Request?e.headers:void 0);new Headers(o?.headers).forEach((z,y)=>s.set(y,z)),/^CSS-Account-Token(?:\s|$)/iu.test(s.get("authorization")??"")&&s.delete("authorization");const f={...o,headers:s,credentials:"omit",redirect:"error"},l=new URL(e instanceof Request?e.url:String(e));if(l.origin!==new URL(n).origin||!l.pathname.startsWith("/.account/")||l.username||l.password||l.hash)throw new Error("Session Account request leaves the trusted authority");const w=new Request(e,f),p=e instanceof Request?await t.fetch(w):await t.fetch(w.url,f);try{t.assertCurrent?.()}catch(z){throw p.body?.cancel().catch(()=>{}),z}return p}}function kt(t){try{const n=new URL(t);return!["http:","https:"].includes(n.protocol)||n.username||n.password||n.pathname!=="/.account/"||n.search||n.hash?void 0:n.href}catch{return}}const B="/.account/";function Vt(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}async function mt(t=fetch){if(typeof window>"u")return B;if(!Qt(window.location.hostname)){const o=window.__XPOD__?.idpIndex;if(o!==void 0){try{const s=new URL(o,window.location.origin);if(typeof o=="string"&&o.trim()&&["http:","https:"].includes(s.protocol)&&s.pathname===B&&!s.username&&!s.password&&!s.search&&!s.hash)return it(),s.href}catch{}throw new Error("Server bootstrap did not expose a valid Account index")}}const n=await t(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(n.status===404)return it(),new URL(B,window.location.origin).href;if(!n.ok)throw new Error(`Local provisioning status request failed (${n.status})`);let e;try{e=await n.json()}catch{throw new Error("Local provisioning status response was not valid JSON")}if(!Vt(e)||typeof e.managed!="boolean")throw new Error("Local provisioning status response was not valid");if(e.managed===!1)return it(),new URL(B,window.location.origin).href;if(typeof e.oidcIssuer=="string")try{const o=new URL(e.oidcIssuer);if(["http:","https:"].includes(o.protocol)&&!o.username&&!o.password)return Kt(t),typeof e.provisionCode=="string"&&Yt(e.provisionCode),new URL(B,o).href}catch{}throw new Error("Local provisioning status did not expose a valid OIDC issuer")}function Kt(t){const n=new URL("/provision/status",window.location.origin);Jt(async()=>{const e=await t(n,{credentials:"include",headers:{accept:"application/json"}}),o=e.ok?await e.json().catch(()=>{}):void 0;if(o?.managed!==!0||o?.registered!==!0||typeof o?.provisionCode!="string")throw new Error(Xt);return o.provisionCode})}function Qt(t){return t==="localhost"||t==="::1"||t==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(t)}const Zt="/.account/",L="Xpod 登录服务暂时不可用,请稍后重试。",at=[250,750,1500],tn=300,Ct=3e3;function nn(){if(typeof window>"u")return!1;const t=window.location.pathname;return t==="/.account"||t.startsWith("/.account/")}function en(t){const n=t?.account;if(!n)return;const e={...typeof n.id=="string"?{id:n.id}:{},...typeof n.username=="string"?{username:n.username}:{},...typeof n.displayName=="string"?{displayName:n.displayName}:{}};return Object.keys(e).length>0?e:void 0}function At(t){return t?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function vt(t){return t===502||t===503||t===504}function Rt(t){return t?{status:"error",mode:"login",message:L}:{status:"initializing"}}function It(t){return new Promise(n=>setTimeout(n,t))}function yn({children:t}){const[n,e]=c.useState(),[o,s]=c.useState(null),[f,l]=c.useState(!0),[w,p]=c.useState(null),[z,y]=c.useState(!1),[tt,h]=c.useState({status:"initializing"}),T=c.useRef(0),v=c.useRef(!0),P=c.useRef(0),b=c.useRef(void 0),j=c.useRef(null),O=c.useRef(!1),E=c.useRef(void 0),_=c.useRef(void 0),dt=c.useRef(void 0),[Nt,Pt]=c.useState(0),nt=c.useRef(void 0),et=c.useRef(0),q=c.useRef(0),G=c.useRef(!1),F=c.useCallback(()=>{const r=j.current?.account;return r?.logout?JSON.stringify([b.current,r.id,r.logout,r.clientCredentials]):void 0},[]),R=c.useCallback(()=>{et.current+=1,G.current=!0},[]),g=c.useCallback((r,i,u)=>{const a=F(),d=nt.current,k=_.current;j.current=r,nt.current=i,_.current=u,(a!==F()||d!==i||k!==u)&&R(),G.current=!F()},[F,R]),rt=c.useCallback(()=>{const r=F(),i=et.current,u=J(),a=_.current;let d=!!r&&u===nt.current&&!G.current&&q.current===0;return()=>{if(a)try{if(a!==E.current||a!==_.current)throw new Error("Stale Account source");a.assertCurrent()}catch{d=!1}if(!d||!v.current||G.current||q.current>0||i!==et.current||r!==F()||u!==J())throw d=!1,new Error("Account 登录状态已改变,请重新打开客户端凭据操作。")}},[F]),jt=c.useCallback(r=>{const i=()=>{j.current?.account?.logout&&!_.current||(P.current+=1,(_.current||!j.current?.account?.logout&&E.current)&&(g(null),s(null),O.current=!1,h({status:"initializing"}),l(!0)),Pt(u=>u+1))};return E.current=r,i(),()=>{E.current===r&&(E.current=void 0,i())}},[g]),Ft=c.useCallback(async(r,i)=>{const u=b.current,a=new URL(r instanceof Request?r.url:String(r),u);if(!u||a.origin!==new URL(u).origin||!a.pathname.startsWith("/.account/")||a.username||a.password)throw new Error("Account request outside current authority");const d=rt(),k=_.current;d();const S=await(k?ut({accountIndex:u,fetch:k.fetch,assertCurrent:d}):fetch)(r instanceof Request?r:a.href,{...i,redirect:"error"});try{d()}catch(C){throw S.body?.cancel().catch(()=>{}),C}return S},[rt]),Mt=tt.status==="authenticated",Dt=f||tt.status==="submitting",W=c.useCallback(r=>{(Gt(r)||b.current&&b.current!==r)&&(P.current+=1,T.current+=1,O.current=!1,g(null),s(null),y(!1),h({status:"initializing"})),b.current=r,e(r)},[g]),X=c.useCallback(async()=>{l(!0),p(null),h(r=>r.status==="authenticated"?r:{status:"initializing"});try{const r=await mt();return v.current?(W(r),r):void 0}catch{if(!v.current)return;g(null),s(null),y(!1),p(L),h({status:"error",mode:"login",message:L}),l(!1);return}},[W,g]);c.useEffect(()=>{let r=!0;return mt().then(i=>{r&&v.current&&W(i)}).catch(()=>{!r||!v.current||(g(null),s(null),y(!1),p(L),h({status:"error",mode:"login",message:L}),l(!1))}),()=>{r=!1}},[W,g]),c.useEffect(()=>(v.current=!0,()=>{v.current=!1,R(),P.current+=1}),[R]);const m=c.useCallback(r=>v.current&&r===P.current,[]),ht=c.useCallback(async()=>{const r=new AbortController,i=setTimeout(()=>r.abort(),Ct);try{const u=b.current;if(!u)return!1;const a=await fetch(Y(new URL("oidc/consent/",u)),{headers:ct(void 0,u),credentials:"include",signal:r.signal});return a.ok?!!(await a.json()).client:!1}catch{return!1}finally{clearTimeout(i)}},[]),ot=c.useCallback(async({exposeTransientError:r,generation:i,confirmUnauthenticated:u})=>{const a=b.current;if(!a)return"stale";const d=J(),k=()=>d===J()?!0:(R(),!1);try{const I=await fetch(Y(a),{headers:ct(void 0,a),credentials:"include"});if(!m(i))return"stale";if(!k())return"transient-error";if(I.ok){const S=await I.json();if(!m(i))return"stale";if(!k())return"transient-error";if(!S?.controls||typeof S.controls!="object"||Array.isArray(S.controls))throw new Error("Invalid CSS Account controls response");let C=S.controls,wt;const A=E.current;if(!C.account?.logout&&A&&A!==dt.current&&q.current===0&&new URL(".account/",A.issuer).href===new URL(a).href){h(M=>M.status==="authenticated"?M:{status:"initializing"}),A.assertCurrent();const N=await ut({accountIndex:a,fetch:A.fetch,assertCurrent:()=>A.assertCurrent()})(Y(a),{headers:{accept:"application/json"},signal:AbortSignal.timeout(Ct)});if(!m(i)||A!==E.current)return"stale";if(A.assertCurrent(),!k())return"transient-error";if(N.ok){const M=await N.json();if(!m(i)||A!==E.current)return"stale";if(A.assertCurrent(),!k())return"transient-error";if(!M?.controls||typeof M.controls!="object"||Array.isArray(M.controls))throw new Error("Invalid CSS Account controls response");C=M.controls,C.account?.logout&&(wt=A)}else if(N.status!==401&&N.status!==403){if(vt(N.status)||N.status===408||N.status===429||N.status===500)throw new Error("Transient CSS Account controls response");return T.current+=1,y(!1),R(),p(L),h({status:"error",mode:"login",message:L}),"terminal-error"}}const Ht=++T.current;y(!1),g(C,d,wt),s(C),p(null);const pt=At(C);return O.current=pt.status==="anonymous",h(pt),C.account?.logout&&nn()&&ht().then(gt=>{m(i)&&Ht===T.current&&y(gt)}),"ok"}else{if(I.status===401||I.status===403)return u?(T.current+=1,yt(),O.current=!0,y(!1),g({}),s({}),h({status:"anonymous",mode:"login"}),p(null),"ok"):"unauthenticated";if(T.current+=1,y(!1),vt(I.status))return p(null),h(C=>C.status==="authenticated"?C:Rt(r)),"transient-error";R();const S=`Failed to load account controls (Status: ${I.status})`;return p(S),h({status:"error",mode:"login",message:S}),"terminal-error"}}catch{return m(i)?(T.current+=1,y(!1),p(null),h(I=>I.status==="authenticated"?I:Rt(r)),"transient-error"):"stale"}},[g,ht,m,R]),D=c.useCallback(async()=>{const r=++P.current;for(let i=0;i<=at.length;i+=1){const u=i===at.length,a=await ot({exposeTransientError:u,generation:r});if(a==="unauthenticated")return!m(r)||(await It(tn),!m(r))?"stale":ot({exposeTransientError:!0,generation:r,confirmUnauthenticated:!0});if(a!=="transient-error")return a;if(!m(r)||!u&&(h(d=>d.status==="authenticated"?d:{status:"initializing"}),await It(at[i]),!m(r)))return"stale"}return"transient-error"},[ot,m]);c.useEffect(()=>{if(!n)return;let r=!0;return(async()=>(await D(),r&&v.current&&l(!1)))(),()=>{r=!1}},[D,n,Nt]);const st=c.useCallback(async()=>{const r=await X();if(r&&r===n){const i=await D();if(v.current&&l(!1),i==="ok")return At(j.current)}return{status:"error",mode:"login",message:L}},[D,n,X]),zt=c.useCallback(async()=>{await st()},[st]),qt=c.useCallback(async()=>{q.current+=1,dt.current=E.current;try{R(),P.current+=1,T.current+=1,(_.current||!j.current?.account?.logout)&&(O.current=!1,(b.current??await X())&&await D());const r=b.current,i=j.current?.account?.logout,u=await bt(i,fetch,r);let a=!u&&(!!i||!O.current);if(u)try{const d=await fetch(Y(u),{method:"POST",headers:ct(void 0,r),credentials:"include"});a=!d.ok&&d.status!==401&&d.status!==403}catch{a=!0}if(a){h({status:"error",mode:"login",message:L});return}P.current+=1,T.current+=1,O.current=!0,l(!1),yt(),y(!1),g({}),s({}),p(null),h({status:"anonymous",mode:"login"})}finally{q.current-=1}},[g,D,X,R]),Bt=c.useMemo(()=>en(o),[o]);return $t.jsx(Wt.Provider,{value:{controls:o,isInitializing:f,initError:w,idpIndex:n??Zt,isLoggedIn:Mt,isAnonymous:()=>O.current,bindAccountCapability:rt,authenticating:Dt,hasOidcPending:z,refetchControls:st,registerAccountSession:jt,accountFetch:Ft,retry:zt,logout:qt,accountState:tt,identity:Bt},children:t})}const St=600*1e3,H=2048,x="xpod.safe-continuation.consent.v2",V="xpod.safe-continuation.management.v2",rn=/^\/\.account\/interaction\/([^/?#]+)$/u,on=/^\/\.account\/(?:interaction\/[^/?#]+\/)?account\/([^/?#]+)\//u;function K(){if(!(typeof window>"u"))try{return window.location.origin}catch{return}}function Lt(){if(!(typeof window>"u"))try{return window.sessionStorage}catch{return}}function lt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Q(t){return typeof t=="string"&&t.length>0&&t.length<=H}function $(t){return Q(t)&&t===t.trim()}function Tt(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function xt(t){return Q(t)&&rn.test(t)}function sn(t){if(typeof t!="string"||!t||t.length>H)return;const n=cn(t);if(n)return n;if(/^[^/?#:]+$/u.test(t)&&t===t.trim())return t}function cn(t){if(typeof t!="string"||!t||t.length>H)return;let n;try{n=new URL(t,K()??"http://localhost")}catch{return}if(!["http:","https:"].includes(n.protocol)||n.username||n.password)return;const e=on.exec(n.pathname);return e?e[1]:void 0}function mn(t,n){const e=t?.account,o=[n?.id,e?.id,e?.logout,e?.clientCredentials,e?.bindings,e?.pod].map(sn).filter(l=>!!l);if(o.length===0)return;const[s,...f]=o;return f.every(l=>l===s)?s:void 0}function an(t,n=K()){if(!n||typeof t!="string"||!t||t.length>H)return!1;let e;try{e=new URL(t,n)}catch{return!1}return e.origin===n&&!e.username&&!e.password&&e.pathname.startsWith("/.account/")}function Ut(t,n,e=K()){if(!e||!xt(t)||typeof n!="string"||!n||n.length>H)return!1;let o;try{o=new URL(n,e)}catch{return!1}return o.origin===e&&!o.username&&!o.password&&o.pathname===`${t}/oidc/consent/`&&o.search===""&&o.hash===""}function un(t){const n=Lt();if(!n)return null;try{return n.getItem(t)}catch{return null}}function Z(t){const n=un(t);if(n===null)return;let e;try{e=JSON.parse(n)}catch{return}return lt(e)?e:void 0}function U(t){const n=Lt();if(n)try{n.removeItem(t)}catch{}}function Ot(t){const{createdAt:n,expiresAt:e}=t;if(!Tt(n)||!Tt(e))return!1;const o=Date.now();if(n>o)return!1;const s=e-n;return s<=0||s>St||e>n+St?!1:e>o}function _t(t,n){return t.accountId===n.accountId&&t.interaction===n.interaction&&t.returnTo===n.returnTo&&t.createdAt===n.createdAt&&t.expiresAt===n.expiresAt}function ft(t){if(!t||t.kind!=="consent")return null;const{accountId:n,interaction:e,returnTo:o}=t;return!$(n)||!xt(e)||!Q(o)||!Ot(t)||!Ut(e,o)?null:{kind:"consent",accountId:n,interaction:e,returnTo:o,createdAt:t.createdAt,expiresAt:t.expiresAt}}function ln(t){if(!t||t.kind!=="management")return null;const{accountId:n,returnTo:e}=t;return!$(n)||!Q(e)||!Ot(t)||!an(e)?null:{kind:"management",accountId:n,returnTo:e,createdAt:t.createdAt,expiresAt:t.expiresAt}}function fn(t){const n=t?.accountId;if(!$(n))return U(V),null;const e=ln(Z(V));return!e||e.accountId!==n?(U(V),null):e}function Cn(t){const n=fn(t);return U(V),n}function dn(t){const n=t?.accountId;if(!$(n))return U(x),null;const e=ft(Z(x));return!e||e.accountId!==n?(U(x),null):e}function An(t,n,e={}){const o=n?.accountId;if(!$(o))return U(x),null;const s=ft(Z(x));if(!s||s.accountId!==o||!_t(s,t))return U(x),null;try{e.assertCurrent?.()}catch{return null}return U(x),s}async function hn(t,n={}){const e=n.origin??K();if(!e||!Ut(t.interaction,t.returnTo,e))return!1;const o=n.fetch??(typeof fetch=="function"?fetch:void 0);if(!o)return!1;const s=new URL(t.returnTo,e).href;let f;try{n.assertCurrent?.(),f=await o(s,{method:"GET",credentials:"include",redirect:"manual",headers:{accept:"application/json",...n.headers??{}}})}catch{return!1}try{n.assertCurrent?.()}catch{return!1}if(f.redirected===!0||typeof f.status=="number"&&f.status>=300&&f.status<400||!f.ok||typeof f.url=="string"&&f.url&&f.url!==s)return!1;const l=await f.json().catch(()=>{});if(!lt(l))return!1;const w=l.client;return lt(w)&&(typeof w.client_id=="string"||typeof w.client_name=="string")}async function vn(t,n={}){const e=dn(t);if(!e)return null;const o=await hn(e,n),s=ft(Z(x));if(!o||!s||s.accountId!==t.accountId||!_t(s,e))return U(x),null;try{n.assertCurrent?.()}catch{return null}return s}export{yn as A,vn as a,fn as b,hn as c,An as d,Cn as e,ut as f,gn as g,mn as r};
1
+ import{r as c,j as $t}from"./dashboard-vmne1ZE0.js";import{r as bt,g as J,b as Gt,c as Y,s as ct,d as yt,A as Wt}from"./account-session-rRAOF7nF.js";const Xt="Cloud storage is not ready. Please wait for Xpod to reconnect and try again.",Et=new WeakMap;function it(){typeof window<"u"&&Et.delete(window)}function Jt(t){typeof window<"u"&&Et.set(window,t)}function Yt(t){try{sessionStorage.setItem("provisionCode",t)}catch{}}async function gn(t){const n=kt(t.accountIndex);if(!n)return;const e=ut(t);let o;try{o=await e(n,{headers:{accept:"application/json"},credentials:"omit"})}catch{return}if(!o.ok)return;const f=(await o.json().catch(()=>{}))?.controls?.account?.clientCredentials;if(typeof f!="string"||!f)return;const l=await bt(f,e,n);if(!l)return;const w=new URL(l,n);return w.origin===new URL(n).origin&&w.pathname.startsWith("/.account/")&&!w.username&&!w.password&&!w.hash?{collection:l,webId:t.webId}:void 0}function ut(t){const n=kt(t.accountIndex);return async(e,o)=>{if(t.assertCurrent?.(),!n)throw new Error("Invalid session Account authority");const s=new Headers(e instanceof Request?e.headers:void 0);new Headers(o?.headers).forEach((z,y)=>s.set(y,z)),/^CSS-Account-Token(?:\s|$)/iu.test(s.get("authorization")??"")&&s.delete("authorization");const f={...o,headers:s,credentials:"omit",redirect:"error"},l=new URL(e instanceof Request?e.url:String(e));if(l.origin!==new URL(n).origin||!l.pathname.startsWith("/.account/")||l.username||l.password||l.hash)throw new Error("Session Account request leaves the trusted authority");const w=new Request(e,f),p=e instanceof Request?await t.fetch(w):await t.fetch(w.url,f);try{t.assertCurrent?.()}catch(z){throw p.body?.cancel().catch(()=>{}),z}return p}}function kt(t){try{const n=new URL(t);return!["http:","https:"].includes(n.protocol)||n.username||n.password||n.pathname!=="/.account/"||n.search||n.hash?void 0:n.href}catch{return}}const B="/.account/";function Vt(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}async function mt(t=fetch){if(typeof window>"u")return B;if(!Qt(window.location.hostname)){const o=window.__XPOD__?.idpIndex;if(o!==void 0){try{const s=new URL(o,window.location.origin);if(typeof o=="string"&&o.trim()&&["http:","https:"].includes(s.protocol)&&s.pathname===B&&!s.username&&!s.password&&!s.search&&!s.hash)return it(),s.href}catch{}throw new Error("Server bootstrap did not expose a valid Account index")}}const n=await t(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(n.status===404)return it(),new URL(B,window.location.origin).href;if(!n.ok)throw new Error(`Local provisioning status request failed (${n.status})`);let e;try{e=await n.json()}catch{throw new Error("Local provisioning status response was not valid JSON")}if(!Vt(e)||typeof e.managed!="boolean")throw new Error("Local provisioning status response was not valid");if(e.managed===!1)return it(),new URL(B,window.location.origin).href;if(typeof e.oidcIssuer=="string")try{const o=new URL(e.oidcIssuer);if(["http:","https:"].includes(o.protocol)&&!o.username&&!o.password)return Kt(t),typeof e.provisionCode=="string"&&Yt(e.provisionCode),new URL(B,o).href}catch{}throw new Error("Local provisioning status did not expose a valid OIDC issuer")}function Kt(t){const n=new URL("/provision/status",window.location.origin);Jt(async()=>{const e=await t(n,{credentials:"include",headers:{accept:"application/json"}}),o=e.ok?await e.json().catch(()=>{}):void 0;if(o?.managed!==!0||o?.registered!==!0||typeof o?.provisionCode!="string")throw new Error(Xt);return o.provisionCode})}function Qt(t){return t==="localhost"||t==="::1"||t==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(t)}const Zt="/.account/",L="Xpod 登录服务暂时不可用,请稍后重试。",at=[250,750,1500],tn=300,Ct=3e3;function nn(){if(typeof window>"u")return!1;const t=window.location.pathname;return t==="/.account"||t.startsWith("/.account/")}function en(t){const n=t?.account;if(!n)return;const e={...typeof n.id=="string"?{id:n.id}:{},...typeof n.username=="string"?{username:n.username}:{},...typeof n.displayName=="string"?{displayName:n.displayName}:{}};return Object.keys(e).length>0?e:void 0}function At(t){return t?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function vt(t){return t===502||t===503||t===504}function Rt(t){return t?{status:"error",mode:"login",message:L}:{status:"initializing"}}function It(t){return new Promise(n=>setTimeout(n,t))}function yn({children:t}){const[n,e]=c.useState(),[o,s]=c.useState(null),[f,l]=c.useState(!0),[w,p]=c.useState(null),[z,y]=c.useState(!1),[tt,h]=c.useState({status:"initializing"}),T=c.useRef(0),v=c.useRef(!0),P=c.useRef(0),b=c.useRef(void 0),j=c.useRef(null),O=c.useRef(!1),E=c.useRef(void 0),_=c.useRef(void 0),dt=c.useRef(void 0),[Nt,Pt]=c.useState(0),nt=c.useRef(void 0),et=c.useRef(0),q=c.useRef(0),G=c.useRef(!1),F=c.useCallback(()=>{const r=j.current?.account;return r?.logout?JSON.stringify([b.current,r.id,r.logout,r.clientCredentials]):void 0},[]),R=c.useCallback(()=>{et.current+=1,G.current=!0},[]),g=c.useCallback((r,i,u)=>{const a=F(),d=nt.current,k=_.current;j.current=r,nt.current=i,_.current=u,(a!==F()||d!==i||k!==u)&&R(),G.current=!F()},[F,R]),rt=c.useCallback(()=>{const r=F(),i=et.current,u=J(),a=_.current;let d=!!r&&u===nt.current&&!G.current&&q.current===0;return()=>{if(a)try{if(a!==E.current||a!==_.current)throw new Error("Stale Account source");a.assertCurrent()}catch{d=!1}if(!d||!v.current||G.current||q.current>0||i!==et.current||r!==F()||u!==J())throw d=!1,new Error("Account 登录状态已改变,请重新打开客户端凭据操作。")}},[F]),jt=c.useCallback(r=>{const i=()=>{j.current?.account?.logout&&!_.current||(P.current+=1,(_.current||!j.current?.account?.logout&&E.current)&&(g(null),s(null),O.current=!1,h({status:"initializing"}),l(!0)),Pt(u=>u+1))};return E.current=r,i(),()=>{E.current===r&&(E.current=void 0,i())}},[g]),Ft=c.useCallback(async(r,i)=>{const u=b.current,a=new URL(r instanceof Request?r.url:String(r),u);if(!u||a.origin!==new URL(u).origin||!a.pathname.startsWith("/.account/")||a.username||a.password)throw new Error("Account request outside current authority");const d=rt(),k=_.current;d();const S=await(k?ut({accountIndex:u,fetch:k.fetch,assertCurrent:d}):fetch)(r instanceof Request?r:a.href,{...i,redirect:"error"});try{d()}catch(C){throw S.body?.cancel().catch(()=>{}),C}return S},[rt]),Mt=tt.status==="authenticated",Dt=f||tt.status==="submitting",W=c.useCallback(r=>{(Gt(r)||b.current&&b.current!==r)&&(P.current+=1,T.current+=1,O.current=!1,g(null),s(null),y(!1),h({status:"initializing"})),b.current=r,e(r)},[g]),X=c.useCallback(async()=>{l(!0),p(null),h(r=>r.status==="authenticated"?r:{status:"initializing"});try{const r=await mt();return v.current?(W(r),r):void 0}catch{if(!v.current)return;g(null),s(null),y(!1),p(L),h({status:"error",mode:"login",message:L}),l(!1);return}},[W,g]);c.useEffect(()=>{let r=!0;return mt().then(i=>{r&&v.current&&W(i)}).catch(()=>{!r||!v.current||(g(null),s(null),y(!1),p(L),h({status:"error",mode:"login",message:L}),l(!1))}),()=>{r=!1}},[W,g]),c.useEffect(()=>(v.current=!0,()=>{v.current=!1,R(),P.current+=1}),[R]);const m=c.useCallback(r=>v.current&&r===P.current,[]),ht=c.useCallback(async()=>{const r=new AbortController,i=setTimeout(()=>r.abort(),Ct);try{const u=b.current;if(!u)return!1;const a=await fetch(Y(new URL("oidc/consent/",u)),{headers:ct(void 0,u),credentials:"include",signal:r.signal});return a.ok?!!(await a.json()).client:!1}catch{return!1}finally{clearTimeout(i)}},[]),ot=c.useCallback(async({exposeTransientError:r,generation:i,confirmUnauthenticated:u})=>{const a=b.current;if(!a)return"stale";const d=J(),k=()=>d===J()?!0:(R(),!1);try{const I=await fetch(Y(a),{headers:ct(void 0,a),credentials:"include"});if(!m(i))return"stale";if(!k())return"transient-error";if(I.ok){const S=await I.json();if(!m(i))return"stale";if(!k())return"transient-error";if(!S?.controls||typeof S.controls!="object"||Array.isArray(S.controls))throw new Error("Invalid CSS Account controls response");let C=S.controls,wt;const A=E.current;if(!C.account?.logout&&A&&A!==dt.current&&q.current===0&&new URL(".account/",A.issuer).href===new URL(a).href){h(M=>M.status==="authenticated"?M:{status:"initializing"}),A.assertCurrent();const N=await ut({accountIndex:a,fetch:A.fetch,assertCurrent:()=>A.assertCurrent()})(Y(a),{headers:{accept:"application/json"},signal:AbortSignal.timeout(Ct)});if(!m(i)||A!==E.current)return"stale";if(A.assertCurrent(),!k())return"transient-error";if(N.ok){const M=await N.json();if(!m(i)||A!==E.current)return"stale";if(A.assertCurrent(),!k())return"transient-error";if(!M?.controls||typeof M.controls!="object"||Array.isArray(M.controls))throw new Error("Invalid CSS Account controls response");C=M.controls,C.account?.logout&&(wt=A)}else if(N.status!==401&&N.status!==403){if(vt(N.status)||N.status===408||N.status===429||N.status===500)throw new Error("Transient CSS Account controls response");return T.current+=1,y(!1),R(),p(L),h({status:"error",mode:"login",message:L}),"terminal-error"}}const Ht=++T.current;y(!1),g(C,d,wt),s(C),p(null);const pt=At(C);return O.current=pt.status==="anonymous",h(pt),C.account?.logout&&nn()&&ht().then(gt=>{m(i)&&Ht===T.current&&y(gt)}),"ok"}else{if(I.status===401||I.status===403)return u?(T.current+=1,yt(),O.current=!0,y(!1),g({}),s({}),h({status:"anonymous",mode:"login"}),p(null),"ok"):"unauthenticated";if(T.current+=1,y(!1),vt(I.status))return p(null),h(C=>C.status==="authenticated"?C:Rt(r)),"transient-error";R();const S=`Failed to load account controls (Status: ${I.status})`;return p(S),h({status:"error",mode:"login",message:S}),"terminal-error"}}catch{return m(i)?(T.current+=1,y(!1),p(null),h(I=>I.status==="authenticated"?I:Rt(r)),"transient-error"):"stale"}},[g,ht,m,R]),D=c.useCallback(async()=>{const r=++P.current;for(let i=0;i<=at.length;i+=1){const u=i===at.length,a=await ot({exposeTransientError:u,generation:r});if(a==="unauthenticated")return!m(r)||(await It(tn),!m(r))?"stale":ot({exposeTransientError:!0,generation:r,confirmUnauthenticated:!0});if(a!=="transient-error")return a;if(!m(r)||!u&&(h(d=>d.status==="authenticated"?d:{status:"initializing"}),await It(at[i]),!m(r)))return"stale"}return"transient-error"},[ot,m]);c.useEffect(()=>{if(!n)return;let r=!0;return(async()=>(await D(),r&&v.current&&l(!1)))(),()=>{r=!1}},[D,n,Nt]);const st=c.useCallback(async()=>{const r=await X();if(r&&r===n){const i=await D();if(v.current&&l(!1),i==="ok")return At(j.current)}return{status:"error",mode:"login",message:L}},[D,n,X]),zt=c.useCallback(async()=>{await st()},[st]),qt=c.useCallback(async()=>{q.current+=1,dt.current=E.current;try{R(),P.current+=1,T.current+=1,(_.current||!j.current?.account?.logout)&&(O.current=!1,(b.current??await X())&&await D());const r=b.current,i=j.current?.account?.logout,u=await bt(i,fetch,r);let a=!u&&(!!i||!O.current);if(u)try{const d=await fetch(Y(u),{method:"POST",headers:ct(void 0,r),credentials:"include"});a=!d.ok&&d.status!==401&&d.status!==403}catch{a=!0}if(a){h({status:"error",mode:"login",message:L});return}P.current+=1,T.current+=1,O.current=!0,l(!1),yt(),y(!1),g({}),s({}),p(null),h({status:"anonymous",mode:"login"})}finally{q.current-=1}},[g,D,X,R]),Bt=c.useMemo(()=>en(o),[o]);return $t.jsx(Wt.Provider,{value:{controls:o,isInitializing:f,initError:w,idpIndex:n??Zt,isLoggedIn:Mt,isAnonymous:()=>O.current,bindAccountCapability:rt,authenticating:Dt,hasOidcPending:z,refetchControls:st,registerAccountSession:jt,accountFetch:Ft,retry:zt,logout:qt,accountState:tt,identity:Bt},children:t})}const St=600*1e3,H=2048,x="xpod.safe-continuation.consent.v2",V="xpod.safe-continuation.management.v2",rn=/^\/\.account\/interaction\/([^/?#]+)$/u,on=/^\/\.account\/(?:interaction\/[^/?#]+\/)?account\/([^/?#]+)\//u;function K(){if(!(typeof window>"u"))try{return window.location.origin}catch{return}}function Lt(){if(!(typeof window>"u"))try{return window.sessionStorage}catch{return}}function lt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Q(t){return typeof t=="string"&&t.length>0&&t.length<=H}function $(t){return Q(t)&&t===t.trim()}function Tt(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function xt(t){return Q(t)&&rn.test(t)}function sn(t){if(typeof t!="string"||!t||t.length>H)return;const n=cn(t);if(n)return n;if(/^[^/?#:]+$/u.test(t)&&t===t.trim())return t}function cn(t){if(typeof t!="string"||!t||t.length>H)return;let n;try{n=new URL(t,K()??"http://localhost")}catch{return}if(!["http:","https:"].includes(n.protocol)||n.username||n.password)return;const e=on.exec(n.pathname);return e?e[1]:void 0}function mn(t,n){const e=t?.account,o=[n?.id,e?.id,e?.logout,e?.clientCredentials,e?.bindings,e?.pod].map(sn).filter(l=>!!l);if(o.length===0)return;const[s,...f]=o;return f.every(l=>l===s)?s:void 0}function an(t,n=K()){if(!n||typeof t!="string"||!t||t.length>H)return!1;let e;try{e=new URL(t,n)}catch{return!1}return e.origin===n&&!e.username&&!e.password&&e.pathname.startsWith("/.account/")}function Ut(t,n,e=K()){if(!e||!xt(t)||typeof n!="string"||!n||n.length>H)return!1;let o;try{o=new URL(n,e)}catch{return!1}return o.origin===e&&!o.username&&!o.password&&o.pathname===`${t}/oidc/consent/`&&o.search===""&&o.hash===""}function un(t){const n=Lt();if(!n)return null;try{return n.getItem(t)}catch{return null}}function Z(t){const n=un(t);if(n===null)return;let e;try{e=JSON.parse(n)}catch{return}return lt(e)?e:void 0}function U(t){const n=Lt();if(n)try{n.removeItem(t)}catch{}}function Ot(t){const{createdAt:n,expiresAt:e}=t;if(!Tt(n)||!Tt(e))return!1;const o=Date.now();if(n>o)return!1;const s=e-n;return s<=0||s>St||e>n+St?!1:e>o}function _t(t,n){return t.accountId===n.accountId&&t.interaction===n.interaction&&t.returnTo===n.returnTo&&t.createdAt===n.createdAt&&t.expiresAt===n.expiresAt}function ft(t){if(!t||t.kind!=="consent")return null;const{accountId:n,interaction:e,returnTo:o}=t;return!$(n)||!xt(e)||!Q(o)||!Ot(t)||!Ut(e,o)?null:{kind:"consent",accountId:n,interaction:e,returnTo:o,createdAt:t.createdAt,expiresAt:t.expiresAt}}function ln(t){if(!t||t.kind!=="management")return null;const{accountId:n,returnTo:e}=t;return!$(n)||!Q(e)||!Ot(t)||!an(e)?null:{kind:"management",accountId:n,returnTo:e,createdAt:t.createdAt,expiresAt:t.expiresAt}}function fn(t){const n=t?.accountId;if(!$(n))return U(V),null;const e=ln(Z(V));return!e||e.accountId!==n?(U(V),null):e}function Cn(t){const n=fn(t);return U(V),n}function dn(t){const n=t?.accountId;if(!$(n))return U(x),null;const e=ft(Z(x));return!e||e.accountId!==n?(U(x),null):e}function An(t,n,e={}){const o=n?.accountId;if(!$(o))return U(x),null;const s=ft(Z(x));if(!s||s.accountId!==o||!_t(s,t))return U(x),null;try{e.assertCurrent?.()}catch{return null}return U(x),s}async function hn(t,n={}){const e=n.origin??K();if(!e||!Ut(t.interaction,t.returnTo,e))return!1;const o=n.fetch??(typeof fetch=="function"?fetch:void 0);if(!o)return!1;const s=new URL(t.returnTo,e).href;let f;try{n.assertCurrent?.(),f=await o(s,{method:"GET",credentials:"include",redirect:"manual",headers:{accept:"application/json",...n.headers??{}}})}catch{return!1}try{n.assertCurrent?.()}catch{return!1}if(f.redirected===!0||typeof f.status=="number"&&f.status>=300&&f.status<400||!f.ok||typeof f.url=="string"&&f.url&&f.url!==s)return!1;const l=await f.json().catch(()=>{});if(!lt(l))return!1;const w=l.client;return lt(w)&&(typeof w.client_id=="string"||typeof w.client_name=="string")}async function vn(t,n={}){const e=dn(t);if(!e)return null;const o=await hn(e,n),s=ft(Z(x));if(!o||!s||s.accountId!==t.accountId||!_t(s,e))return U(x),null;try{n.assertCurrent?.()}catch{return null}return s}export{yn as A,vn as a,fn as b,hn as c,An as d,Cn as e,ut as f,gn as g,mn as r};
@@ -1 +1 @@
1
- import{j as e}from"./dashboard-Or0gnkou.js";import{c as n,a as m,i as c}from"./button-wslF55uZ.js";const u=m(`inline-flex items-center rounded-lg border px-2.5 py-0.5 text-xs font-semibold transition-all duration-200 ${c}`,{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow-sm shadow-primary/20 hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow-sm shadow-destructive/20 hover:bg-destructive/90",outline:"border-border/40 text-foreground bg-muted/30 backdrop-blur-sm",pending:"border border-dashed border-muted-foreground bg-transparent text-muted-foreground shadow-none hover:bg-transparent"}},defaultVariants:{variant:"default"}});function b({className:r,variant:a,...s}){return e.jsx("div",{className:n(u({variant:a}),r),...s})}function f({title:r,description:a,actions:s,level:d=2,titleClassName:o,className:i,...l}){const t=n("text-sm leading-normal text-foreground",o);return e.jsxs("div",{...l,className:n("flex flex-wrap items-start justify-between gap-3",i),children:[e.jsxs("div",{className:"min-w-0",children:[d===3?e.jsx("h3",{className:t,children:r}):d===4?e.jsx("h4",{className:t,children:r}):e.jsx("h2",{className:t,children:r}),a?e.jsx("p",{className:"mt-1 text-xs leading-normal text-muted-foreground",children:a}):null]}),s?e.jsx("div",{className:"flex min-w-0 max-w-full flex-wrap items-center gap-2",children:s}):null]})}export{b as B,f as S};
1
+ import{j as e}from"./dashboard-vmne1ZE0.js";import{c as n,a as m,i as c}from"./button-WVnQUNG-.js";const u=m(`inline-flex items-center rounded-lg border px-2.5 py-0.5 text-xs font-semibold transition-all duration-200 ${c}`,{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow-sm shadow-primary/20 hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow-sm shadow-destructive/20 hover:bg-destructive/90",outline:"border-border/40 text-foreground bg-muted/30 backdrop-blur-sm",pending:"border border-dashed border-muted-foreground bg-transparent text-muted-foreground shadow-none hover:bg-transparent"}},defaultVariants:{variant:"default"}});function b({className:r,variant:a,...s}){return e.jsx("div",{className:n(u({variant:a}),r),...s})}function f({title:r,description:a,actions:s,level:d=2,titleClassName:o,className:i,...l}){const t=n("text-sm leading-normal text-foreground",o);return e.jsxs("div",{...l,className:n("flex flex-wrap items-start justify-between gap-3",i),children:[e.jsxs("div",{className:"min-w-0",children:[d===3?e.jsx("h3",{className:t,children:r}):d===4?e.jsx("h4",{className:t,children:r}):e.jsx("h2",{className:t,children:r}),a?e.jsx("p",{className:"mt-1 text-xs leading-normal text-muted-foreground",children:a}):null]}),s?e.jsx("div",{className:"flex min-w-0 max-w-full flex-wrap items-center gap-2",children:s}):null]})}export{b as B,f as S};
@@ -1 +1 @@
1
- import{r as o,j as r}from"./dashboard-Or0gnkou.js";import{c as D,P,a as F,u as $}from"./PodDeletionAuthorizationPanel-BJk_8rJq.js";import{u as M,c as j,i as W}from"./button-wslF55uZ.js";import{G as X}from"./xpod-remembered-login-BUF9fin1.js";var J=Object.defineProperty,w=(n,e)=>J(n,"name",{value:e,configurable:!0}),E="Switch",[K,de]=D(E),[Q,y]=K(E);function U(n){const{__scopeSwitch:e,checked:s,children:c,defaultChecked:a,disabled:t,form:i,name:l,onCheckedChange:d,required:h,value:S="on",internal_do_not_use_render:m}=n,[f,b]=$({prop:s,defaultProp:a??!1,onChange:d,caller:E}),[g,C]=o.useState(null),[x,v]=o.useState(null),R=o.useRef(!1),[u,p]=o.useReducer(k=>k+1,0),I=g?!!i||!!g.closest("form"):!0,_={checked:f,setChecked:b,disabled:t,control:g,setControl:C,name:l,form:i,value:S,hasConsumerStoppedPropagationRef:R,userInteractionCount:u,onUserInteraction:p,required:h,defaultChecked:a,isFormControl:I,bubbleInput:x,setBubbleInput:v};return r.jsx(Q,{scope:e,..._,children:H(m)?m(_):c})}w(U,"SwitchProvider");var V="SwitchTrigger",Y=o.forwardRef(w(function({__scopeSwitch:e,onClick:s,...c},a){const{control:t,form:i,value:l,disabled:d,checked:h,required:S,setControl:m,setChecked:f,hasConsumerStoppedPropagationRef:b,onUserInteraction:g,isFormControl:C,bubbleInput:x}=y(V,e),v=M(a,m),R=o.useRef(h);return o.useEffect(()=>{const u=i?t?.ownerDocument.getElementById(i):t?.form;if(u instanceof HTMLFormElement){const p=w(()=>f(R.current),"reset");return u.addEventListener("reset",p),()=>u.removeEventListener("reset",p)}},[t,i,f]),r.jsx(P.button,{type:"button",role:"switch","aria-checked":h,"aria-required":S,"data-state":N(h),"data-disabled":d?"":void 0,disabled:d,value:l,...c,ref:v,onClick:F(s,u=>{g(),f(p=>!p),x&&C&&(b.current=u.isPropagationStopped(),b.current||u.stopPropagation())})})},"SwitchTrigger")),q=o.forwardRef(w(function(e,s){const{__scopeSwitch:c,name:a,checked:t,defaultChecked:i,required:l,disabled:d,value:h,onCheckedChange:S,form:m,...f}=e;return r.jsx(U,{__scopeSwitch:c,checked:t,defaultChecked:i,disabled:d,required:l,onCheckedChange:S,name:a,form:m,value:h,internal_do_not_use_render:({isFormControl:b})=>r.jsxs(r.Fragment,{children:[r.jsx(Y,{...f,ref:s,__scopeSwitch:c}),b&&r.jsx(re,{__scopeSwitch:c})]})})},"Switch")),Z="SwitchThumb",ee=o.forwardRef(w(function(e,s){const{__scopeSwitch:c,...a}=e,t=y(Z,c);return r.jsx(P.span,{"data-state":N(t.checked),"data-disabled":t.disabled?"":void 0,...a,ref:s})},"SwitchThumb")),te="SwitchBubbleInput",re=o.forwardRef(w(function({__scopeSwitch:e,onClick:s,...c},a){const{control:t,hasConsumerStoppedPropagationRef:i,userInteractionCount:l,checked:d,defaultChecked:h,required:S,disabled:m,name:f,value:b,form:g,bubbleInput:C,setBubbleInput:x}=y(te,e),v=M(a,x),R=X(t),u=o.useRef(!1),p=o.useRef(d),I=o.useRef(l);o.useEffect(()=>{const k=C;if(!k)return;const A=window.HTMLInputElement.prototype,T=Object.getOwnPropertyDescriptor(A,"checked").set,B=l!==I.current;I.current=l;const G=p.current!==d;p.current=d;const O=!(B&&i.current);if(G&&T){u.current=!B;const z=new Event("click",{bubbles:O});T.call(k,d),k.dispatchEvent(z),u.current=!1}},[C,d,i,l]);const _=o.useRef(d);return r.jsx(P.input,{type:"checkbox","aria-hidden":!0,defaultChecked:h??_.current,required:S,disabled:m,name:f,value:b,form:g,...c,tabIndex:-1,ref:v,onClick:F(s,k=>{u.current&&k.stopPropagation()}),style:{...c.style,...R,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function H(n){return typeof n=="function"}w(H,"isFunction");function N(n){return n?"checked":"unchecked"}w(N,"getState");const L=o.forwardRef(({className:n,...e},s)=>r.jsx(q,{className:j("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full","border-2 border-transparent","transition-all duration-200",W,"disabled:cursor-not-allowed disabled:opacity-50","data-[state=checked]:bg-primary","data-[state=unchecked]:bg-muted/50",n),...e,ref:s,children:r.jsx(ee,{className:j("pointer-events-none block h-5 w-5 rounded-full bg-background","shadow-md ring-0","transition-transform duration-200","data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));L.displayName=q.displayName;function ne({label:n,description:e,control:s,className:c,...a}){const t=o.useId(),i=e?`${t}-description`:void 0;return r.jsxs("div",{className:j("flex min-h-16 items-center justify-between gap-3 border-b border-border",c),...a,children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("label",{htmlFor:t,className:"text-sm leading-normal text-foreground",children:n}),e?r.jsx("p",{id:i,className:"mt-1 text-xs leading-normal text-muted-foreground",children:e}):null]}),r.jsx("div",{className:"shrink-0",children:s({id:t,"aria-describedby":i})})]})}function ue({checked:n,onCheckedChange:e,disabled:s,...c}){return r.jsx(ne,{...c,control:({id:a,"aria-describedby":t})=>r.jsx(L,{id:a,checked:n,onCheckedChange:e,disabled:s,"aria-describedby":t})})}export{ne as S,ue as a};
1
+ import{r as o,j as r}from"./dashboard-vmne1ZE0.js";import{c as D,P,a as F,u as $}from"./PodDeletionAuthorizationPanel-C22bhZeD.js";import{u as M,c as j,i as W}from"./button-WVnQUNG-.js";import{G as X}from"./xpod-remembered-login-nv1g1sfC.js";var J=Object.defineProperty,w=(n,e)=>J(n,"name",{value:e,configurable:!0}),E="Switch",[K,de]=D(E),[Q,y]=K(E);function U(n){const{__scopeSwitch:e,checked:s,children:c,defaultChecked:a,disabled:t,form:i,name:l,onCheckedChange:d,required:h,value:S="on",internal_do_not_use_render:m}=n,[f,b]=$({prop:s,defaultProp:a??!1,onChange:d,caller:E}),[g,C]=o.useState(null),[x,v]=o.useState(null),R=o.useRef(!1),[u,p]=o.useReducer(k=>k+1,0),I=g?!!i||!!g.closest("form"):!0,_={checked:f,setChecked:b,disabled:t,control:g,setControl:C,name:l,form:i,value:S,hasConsumerStoppedPropagationRef:R,userInteractionCount:u,onUserInteraction:p,required:h,defaultChecked:a,isFormControl:I,bubbleInput:x,setBubbleInput:v};return r.jsx(Q,{scope:e,..._,children:H(m)?m(_):c})}w(U,"SwitchProvider");var V="SwitchTrigger",Y=o.forwardRef(w(function({__scopeSwitch:e,onClick:s,...c},a){const{control:t,form:i,value:l,disabled:d,checked:h,required:S,setControl:m,setChecked:f,hasConsumerStoppedPropagationRef:b,onUserInteraction:g,isFormControl:C,bubbleInput:x}=y(V,e),v=M(a,m),R=o.useRef(h);return o.useEffect(()=>{const u=i?t?.ownerDocument.getElementById(i):t?.form;if(u instanceof HTMLFormElement){const p=w(()=>f(R.current),"reset");return u.addEventListener("reset",p),()=>u.removeEventListener("reset",p)}},[t,i,f]),r.jsx(P.button,{type:"button",role:"switch","aria-checked":h,"aria-required":S,"data-state":N(h),"data-disabled":d?"":void 0,disabled:d,value:l,...c,ref:v,onClick:F(s,u=>{g(),f(p=>!p),x&&C&&(b.current=u.isPropagationStopped(),b.current||u.stopPropagation())})})},"SwitchTrigger")),q=o.forwardRef(w(function(e,s){const{__scopeSwitch:c,name:a,checked:t,defaultChecked:i,required:l,disabled:d,value:h,onCheckedChange:S,form:m,...f}=e;return r.jsx(U,{__scopeSwitch:c,checked:t,defaultChecked:i,disabled:d,required:l,onCheckedChange:S,name:a,form:m,value:h,internal_do_not_use_render:({isFormControl:b})=>r.jsxs(r.Fragment,{children:[r.jsx(Y,{...f,ref:s,__scopeSwitch:c}),b&&r.jsx(re,{__scopeSwitch:c})]})})},"Switch")),Z="SwitchThumb",ee=o.forwardRef(w(function(e,s){const{__scopeSwitch:c,...a}=e,t=y(Z,c);return r.jsx(P.span,{"data-state":N(t.checked),"data-disabled":t.disabled?"":void 0,...a,ref:s})},"SwitchThumb")),te="SwitchBubbleInput",re=o.forwardRef(w(function({__scopeSwitch:e,onClick:s,...c},a){const{control:t,hasConsumerStoppedPropagationRef:i,userInteractionCount:l,checked:d,defaultChecked:h,required:S,disabled:m,name:f,value:b,form:g,bubbleInput:C,setBubbleInput:x}=y(te,e),v=M(a,x),R=X(t),u=o.useRef(!1),p=o.useRef(d),I=o.useRef(l);o.useEffect(()=>{const k=C;if(!k)return;const A=window.HTMLInputElement.prototype,T=Object.getOwnPropertyDescriptor(A,"checked").set,B=l!==I.current;I.current=l;const G=p.current!==d;p.current=d;const O=!(B&&i.current);if(G&&T){u.current=!B;const z=new Event("click",{bubbles:O});T.call(k,d),k.dispatchEvent(z),u.current=!1}},[C,d,i,l]);const _=o.useRef(d);return r.jsx(P.input,{type:"checkbox","aria-hidden":!0,defaultChecked:h??_.current,required:S,disabled:m,name:f,value:b,form:g,...c,tabIndex:-1,ref:v,onClick:F(s,k=>{u.current&&k.stopPropagation()}),style:{...c.style,...R,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function H(n){return typeof n=="function"}w(H,"isFunction");function N(n){return n?"checked":"unchecked"}w(N,"getState");const L=o.forwardRef(({className:n,...e},s)=>r.jsx(q,{className:j("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full","border-2 border-transparent","transition-all duration-200",W,"disabled:cursor-not-allowed disabled:opacity-50","data-[state=checked]:bg-primary","data-[state=unchecked]:bg-muted/50",n),...e,ref:s,children:r.jsx(ee,{className:j("pointer-events-none block h-5 w-5 rounded-full bg-background","shadow-md ring-0","transition-transform duration-200","data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));L.displayName=q.displayName;function ne({label:n,description:e,control:s,className:c,...a}){const t=o.useId(),i=e?`${t}-description`:void 0;return r.jsxs("div",{className:j("flex min-h-16 items-center justify-between gap-3 border-b border-border",c),...a,children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("label",{htmlFor:t,className:"text-sm leading-normal text-foreground",children:n}),e?r.jsx("p",{id:i,className:"mt-1 text-xs leading-normal text-muted-foreground",children:e}):null]}),r.jsx("div",{className:"shrink-0",children:s({id:t,"aria-describedby":i})})]})}function ue({checked:n,onCheckedChange:e,disabled:s,...c}){return r.jsx(ne,{...c,control:({id:a,"aria-describedby":t})=>r.jsx(L,{id:a,checked:n,onCheckedChange:e,disabled:s,"aria-describedby":t})})}export{ne as S,ue as a};