@undefineds.co/xpod 0.4.33 → 0.4.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/http/SubgraphSparqlHttpHandler.d.ts +32 -0
- package/dist/http/SubgraphSparqlHttpHandler.js +448 -1
- package/dist/http/SubgraphSparqlHttpHandler.jsonld +36 -0
- package/dist/storage/rdf/QleverSparqlEngine.d.ts +15 -0
- package/dist/storage/rdf/QleverSparqlEngine.js +40 -0
- package/dist/storage/rdf/QleverSparqlEngine.jsonld +8 -0
- package/dist/storage/rdf/RdfAccessScope.d.ts +12 -0
- package/dist/storage/rdf/RdfAccessScope.js +63 -3
- package/dist/storage/rdf/RdfQuerySparqlEngine.d.ts +7 -0
- package/dist/storage/rdf/RdfQuerySparqlEngine.js +30 -0
- package/dist/storage/rdf/RdfQuerySparqlEngine.jsonld +8 -0
- package/dist/storage/rdf/index.d.ts +1 -1
- package/dist/storage/rdf/index.js +6 -2
- package/dist/storage/sparql/SubgraphQueryEngine.d.ts +5 -0
- package/dist/storage/sparql/SubgraphQueryEngine.js +9 -0
- package/dist/storage/sparql/SubgraphQueryEngine.jsonld +16 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiBuiltinProvidersSection.d.ts +32 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiBuiltinProvidersSection.js +8 -0
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +35 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.d.ts +9 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +32 -6
- package/node_modules/@undefineds.co/ai-connections/dist/index.d.ts +1 -0
- package/node_modules/@undefineds.co/ai-connections/dist/index.js +1 -0
- package/node_modules/@undefineds.co/ai-connections/package.json +2 -2
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/ai-connections-client.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/normalize.d.ts +16 -1
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/normalize.js +80 -2
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/request.js +19 -1
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/types.d.ts +31 -0
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/build-provenance.json +4 -4
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/index.json +15 -15
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/javascript/provider-catalog/index.json +2 -2
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/javascript/service-access-resources/index.json +2 -2
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/source/package.json +1 -1
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/source-inventory.json +11 -11
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/provider-catalog-inputs.json +1 -1
- package/node_modules/@undefineds.co/ai-connections-runtime/dist/service-access-resources-inputs.json +1 -1
- package/node_modules/@undefineds.co/ai-connections-runtime/package.json +1 -1
- package/node_modules/@undefineds.co/extension-host-contracts/dist/materials/build-provenance.json +1 -1
- package/node_modules/@undefineds.co/extension-host-contracts/dist/materials/index.json +3 -3
- package/node_modules/@undefineds.co/extension-host-contracts/dist/materials/source-inventory.json +1 -1
- package/node_modules/@undefineds.co/xpod-afs/dist/licenses/cli-producer-original-binding.json +1 -1
- package/node_modules/@undefineds.co/xpod-cli/dist/producer-materials/index.json +1 -1
- package/package.json +4 -4
- package/static/dashboard/assets/{AccountAuthBoundary-D2peXpst.js → AccountAuthBoundary-DXBGmvsI.js} +1 -1
- package/static/dashboard/assets/{DesktopOidcCallback-DXWArav6.js → DesktopOidcCallback-p24MYq1P.js} +1 -1
- package/static/dashboard/assets/{DevicePages-BULFk95K.js → DevicePages-DbvhTnse.js} +1 -1
- package/static/dashboard/assets/ModelsPage-UMDnRyLA.js +12 -0
- package/static/dashboard/assets/{PaneListHeader-BSfEbecP.js → PaneListHeader-DkEH0TT_.js} +1 -1
- package/static/dashboard/assets/{PodDeletionAuthorizationPanel-CH-Sx18g.js → PodDeletionAuthorizationPanel-CzrI8Pgw.js} +3 -3
- package/static/dashboard/assets/{PodPage-BMpejIra.js → PodPage-TaiWqMBx.js} +1 -1
- package/static/dashboard/assets/{SystemSettingsPage-H_Jj6WfF.js → SystemSettingsPage-D4gQjDt1.js} +1 -1
- package/static/dashboard/assets/{TasksPage-CTDxlQra.js → TasksPage-CmkiMYil.js} +1 -1
- package/static/dashboard/assets/{WebDesktopEntry-Ch7-0C9a.js → WebDesktopEntry-D9kEfhbz.js} +1 -1
- package/static/dashboard/assets/{XpodAiConnectionsPodStore-ggRE9fmE.js → XpodAiConnectionsPodStore-orY8vQFl.js} +2 -2
- package/static/dashboard/assets/{XpodShellApp-Bwf9UmeJ.js → XpodShellApp-DR65DMOb.js} +4 -4
- package/static/dashboard/assets/{account-session-CVzooxS2.js → account-session-BZ2ttIdq.js} +1 -1
- package/static/dashboard/assets/{button-DGh2QVt2.js → button-_rwfCMMH.js} +1 -1
- package/static/dashboard/assets/{collection-runtime-DwV_9rt2.js → collection-runtime-C74icLtf.js} +1 -1
- package/static/dashboard/assets/{createLucideIcon-yLhAxnfL.js → createLucideIcon-DrgScGhc.js} +1 -1
- package/static/dashboard/assets/{dashboard-xbXlitKr.js → dashboard--DWjqkYt.js} +2 -2
- package/static/dashboard/assets/{index-CMigfjqD.js → index-D6dB-UNq.js} +1 -1
- package/static/dashboard/assets/{index-BSiKqEdo.js → index-dx5sc4rE.js} +1 -1
- package/static/dashboard/assets/{label-CrDv_y1q.js → label-D02Jpvm9.js} +1 -1
- package/static/dashboard/assets/{list-BJM0nqti.js → list-DpFAisnq.js} +1 -1
- package/static/dashboard/assets/{nav-item-style-CQbGyYLb.js → nav-item-style-B1-0JkON.js} +1 -1
- package/static/dashboard/assets/{safe-continuation-ZTBQTFWB.js → safe-continuation-DUTIOFe5.js} +1 -1
- package/static/dashboard/assets/{section-header-CWHRWGXl.js → section-header-CtBnllbG.js} +1 -1
- package/static/dashboard/assets/{setting-row-qWtxYGK1.js → setting-row-D_JPuHAJ.js} +1 -1
- package/static/dashboard/assets/{xpod-remembered-login-DPMxurVN.js → xpod-remembered-login-CtmMI8xG.js} +3 -3
- package/static/dashboard/dashboard.html +1 -1
- package/static/settings/assets/{AccountAuthBoundary-4Ywjpb8o.js → AccountAuthBoundary-njIhHpLf.js} +1 -1
- package/static/settings/assets/{DesktopOidcCallback-CAmwMT_J.js → DesktopOidcCallback-BjjNwTxc.js} +1 -1
- package/static/settings/assets/{DevicePages-DvuHyfHo.js → DevicePages-FFJMu_zL.js} +1 -1
- package/static/settings/assets/ModelsPage-6567dZKQ.js +12 -0
- package/static/settings/assets/{PaneListHeader-CuFgIbhe.js → PaneListHeader-CuPah5aC.js} +1 -1
- package/static/settings/assets/{PodDeletionAuthorizationPanel-DdNgDHH5.js → PodDeletionAuthorizationPanel-aJCKasGz.js} +3 -3
- package/static/settings/assets/{PodPage-DnWCNGTO.js → PodPage-BA0DQ3AB.js} +1 -1
- package/static/settings/assets/{SystemSettingsPage-k9P_wQcl.js → SystemSettingsPage-BNPH4VWf.js} +1 -1
- package/static/settings/assets/{TasksPage-Dk7gUH3J.js → TasksPage-B5m82wjD.js} +1 -1
- package/static/settings/assets/{WebDesktopEntry-DJwPVVnU.js → WebDesktopEntry-DgwwIUhg.js} +1 -1
- package/static/settings/assets/{XpodAiConnectionsPodStore-BtJQiJsx.js → XpodAiConnectionsPodStore-BJm-rFPs.js} +2 -2
- package/static/settings/assets/{XpodShellApp-B47vEQJp.js → XpodShellApp-BwvekJJR.js} +4 -4
- package/static/settings/assets/{XpodThemeProvider-Ciuwo_yl.js → XpodThemeProvider-DyX0rUID.js} +2 -2
- package/static/settings/assets/{account-session-CMc10iEj.js → account-session-D6vibAra.js} +1 -1
- package/static/settings/assets/auth-callback-DXxmF0-p.js +1 -0
- package/static/settings/assets/{button-D1dGKY1f.js → button-CV4KJ59A.js} +1 -1
- package/static/settings/assets/{collection-runtime-hK37-47o.js → collection-runtime-CARp4Cii.js} +1 -1
- package/static/settings/assets/{createLucideIcon-nEiQH43b.js → createLucideIcon-BIwq0vQx.js} +1 -1
- package/static/settings/assets/{index-DNdvma6J.js → index-D-LgcKAb.js} +1 -1
- package/static/settings/assets/{label-C3EGk_2E.js → label-CFTl2bC_.js} +1 -1
- package/static/settings/assets/{list-BensBGZp.js → list-D2aO7Nu-.js} +1 -1
- package/static/settings/assets/{nav-item-style-BOKCPNz8.js → nav-item-style-BKpK5_1m.js} +1 -1
- package/static/settings/assets/{safe-continuation-BPwW6jdq.js → safe-continuation-DRRY_t4F.js} +1 -1
- package/static/settings/assets/{section-header-DOSj5RvJ.js → section-header-COECjyL5.js} +1 -1
- package/static/settings/assets/{setting-row-C9k4cGNM.js → setting-row-cGgL78vR.js} +1 -1
- package/static/settings/assets/{settings-DtP5C8hi.js → settings-Bvrm5N-k.js} +1 -1
- package/static/settings/assets/{xpod-remembered-login-DKFG-zi3.js → xpod-remembered-login-YAmn8ZiP.js} +3 -3
- package/static/settings/auth-callback.html +2 -2
- package/static/settings/settings.html +2 -2
- package/static/dashboard/assets/ModelsPage-xvsVzhGZ.js +0 -12
- package/static/settings/assets/ModelsPage-BDXqetwk.js +0 -12
- package/static/settings/assets/auth-callback-fcOBaX2w.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{c as createLucideIcon$1}from"./createLucideIcon-yLhAxnfL.js";import{r as reactExports,j as jsxRuntimeExports,h as useXpodAuthWindowSurface,i as getXpodAuthSurfaceHost,_ as __vitePreload,k as getDefaultExportFromCjs,l as getAugmentedNamespace}from"./dashboard-xbXlitKr.js";import{c as cn,B as Button,u as useComposedRefs,g as createSlottable,d as controlFocusClass}from"./button-DGh2QVt2.js";import{c as createContextScope,P as Primitive,w as useCallbackRef,y as useLayoutEffect2,f as Card,r as createLucideIcon,t as reactDomExports,z as Presence,A as DismissableLayer,B as useId,u as useControllableState,a as composeEventHandlers,E as Portal$1,I as Input}from"./PodDeletionAuthorizationPanel-CH-Sx18g.js";import{X as XpodMark,f as resolveSolidLocalRouteUrl,h as createSolidLocalRouteFetch,p as probeSolidLocalRouteStatus}from"./account-session-CVzooxS2.js";import{QueryEngine}from"@comunica/query-sparql-solid";var __defProp$5=Object.defineProperty,__name$4=(r,e)=>__defProp$5(r,"name",{value:e,configurable:!0}),AVATAR_NAME="Avatar",[createAvatarContext,createAvatarScope]=createContextScope(AVATAR_NAME),STATIC_IMAGE_COUNT_STATE=[0,()=>{}],[AvatarProvider,useAvatarContext]=createAvatarContext(AVATAR_NAME),Avatar$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,...i}=e,[s,o]=reactExports.useState("idle"),[a,d]=useImageCount();return jsxRuntimeExports.jsx(AvatarProvider,{scope:n,imageLoadingStatus:s,setImageLoadingStatus:o,imageCount:a,setImageCount:d,children:jsxRuntimeExports.jsx(Primitive.span,{...i,ref:t})})},"Avatar")),IMAGE_NAME="AvatarImage",AvatarImage$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,src:i,onLoadingStatusChange:s,...o}=e,a=useAvatarContext(IMAGE_NAME,n);a.setImageCount;const d=useImageLoadingStatus(i,{referrerPolicy:o.referrerPolicy,crossOrigin:o.crossOrigin,loadingStatus:a.imageLoadingStatus,setLoadingStatus:a.setImageLoadingStatus}),l=useCallbackRef(p=>{s?.(p)}),h=reactExports.useRef(d);return useLayoutEffect2(()=>{const p=h.current;h.current=d,d!==p&&l(d)},[d,l]),d==="loaded"?jsxRuntimeExports.jsx(Primitive.img,{...o,ref:t,src:i}):null},"AvatarImage")),FALLBACK_NAME="AvatarFallback",AvatarFallback$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,delayMs:i,...s}=e,o=useAvatarContext(FALLBACK_NAME,n),[a,d]=reactExports.useState(i===void 0);return reactExports.useEffect(()=>{if(i!==void 0){const l=window.setTimeout(()=>d(!0),i);return()=>window.clearTimeout(l)}},[i]),a&&o.imageLoadingStatus!=="loaded"?jsxRuntimeExports.jsx(Primitive.span,{...s,ref:t}):null},"AvatarFallback"));function useImageLoadingStatus(r,{loadingStatus:e,setLoadingStatus:t,referrerPolicy:n,crossOrigin:i}){return useLayoutEffect2(()=>{if(!r){t("error");return}const s=new window.Image,o=__name$4(d=>{const l=d.currentTarget;t(getImageLoadingStatus(l))},"handleLoad"),a=__name$4(()=>t("error"),"handleError");return s.addEventListener("load",o),s.addEventListener("error",a),n&&(s.referrerPolicy=n),s.crossOrigin=i??null,s.src=r,t(getImageLoadingStatus(s)),()=>{s.removeEventListener("load",o),s.removeEventListener("error",a),t("idle")}},[r,i,n,t]),e}__name$4(useImageLoadingStatus,"useImageLoadingStatus");function getImageLoadingStatus(r){return r.complete?r.naturalWidth>0?"loaded":"error":"loading"}__name$4(getImageLoadingStatus,"getImageLoadingStatus");function useImageCount(){return STATIC_IMAGE_COUNT_STATE}__name$4(useImageCount,"useImageCount");function useUpdateImageCount(r){}__name$4(useUpdateImageCount,"useUpdateImageCount");const Avatar=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(Avatar$1,{ref:t,className:cn("relative flex shrink-0 overflow-hidden",r),...e}));Avatar.displayName=Avatar$1.displayName;const AvatarImage=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(AvatarImage$1,{ref:t,className:cn("h-full w-full object-cover",r),...e}));AvatarImage.displayName=AvatarImage$1.displayName;const AvatarFallback=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(AvatarFallback$1,{ref:t,className:cn("flex h-full w-full items-center justify-center bg-muted text-lg font-semibold",r),...e}));AvatarFallback.displayName=AvatarFallback$1.displayName;function AuthSurfaceBody({children:r,className:e}){return jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-body",className:cn("min-h-0",e),children:r})}const FOCUSABLE_SELECTOR=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function getFocusable(r){return Array.from(r.querySelectorAll(FOCUSABLE_SELECTOR)).filter(e=>e.getAttribute("aria-hidden")!=="true")}function AuthSurface({mode:r,title:e,children:t,presentation:n="standard",host:i="document",lead:s,onClose:o,closeLabel:a,closeOnEscape:d=!0,className:l,contentClassName:h}){const p=reactExports.useRef(null),g=reactExports.useRef(null),S=reactExports.useId();reactExports.useLayoutEffect(()=>{if(r!=="modal"||typeof document>"u")return;g.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const I=p.current;if(I){const C=getFocusable(I);(n==="compact"?I:C[0]??I).focus()}return()=>{g.current?.focus(),g.current=null}},[r,n]),reactExports.useLayoutEffect(()=>{if(r!=="modal"||typeof document>"u")return;const I=C=>{if(C.key==="Escape"){d&&o&&(C.preventDefault(),o());return}if(C.key!=="Tab")return;const O=p.current;if(!O)return;const P=getFocusable(O);if(P.length===0){C.preventDefault(),O.focus();return}const D=document.activeElement,Y=P.indexOf(D),re=C.shiftKey?Y<=0?P.length-1:Y-1:Y===P.length-1?0:Y+1;C.preventDefault(),P[re].focus()};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[d,r,o]);const y=r==="modal"?{role:"dialog","aria-modal":!0,"aria-labelledby":S}:{role:"region","aria-labelledby":S},v=n==="compact",E=i==="window",w=v?"flex min-h-0 flex-1 flex-col overflow-y-auto":"max-h-[min(80vh,48rem)] overflow-y-auto",T=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[v?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h1",{id:S,className:"sr-only",children:e}),r==="modal"&&o&&a?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":a,className:"absolute right-2 top-2 z-[var(--layer-sticky)]",children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}):jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border/60 p-4",children:[jsxRuntimeExports.jsx("h1",{id:S,className:"text-lg font-semibold text-foreground",children:e}),r==="modal"&&o&&a?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":a,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}),s?jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-lead",className:cn(v?"shrink-0 px-5 pt-7 has-[[data-presentation=compact]]:pt-5":"border-b border-border/60 p-4"),children:s}):null,jsxRuntimeExports.jsx(AuthSurfaceBody,{className:cn(w,h),children:t})]});return jsxRuntimeExports.jsx("div",{"data-testid":`auth-surface-${r}`,"data-auth-surface-mode":r,"data-auth-surface-presentation":v?"compact":void 0,"data-auth-surface-host":E?"window":void 0,className:cn(E?"fixed inset-0 z-[var(--layer-modal)] flex items-stretch justify-stretch overflow-hidden bg-card p-0":r==="modal"?cn("fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center p-4","bg-background"):r==="page"?"flex min-h-[100dvh] w-full items-center justify-center bg-background p-4":"flex min-h-0 w-full items-center justify-center p-4",l),children:E?jsxRuntimeExports.jsx("div",{ref:p,...y,"data-auth-surface-frame":"window",tabIndex:-1,className:"relative flex h-full min-h-0 w-full flex-col overflow-hidden bg-card text-card-foreground focus:outline-none",children:T}):v?jsxRuntimeExports.jsx("div",{ref:p,...y,"data-auth-surface-frame":"compact",tabIndex:-1,style:{outline:"none"},className:"flex h-[400px] w-[280px] max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] min-w-0 flex-col overflow-y-auto overscroll-contain focus:outline-none",children:T}):jsxRuntimeExports.jsx(Card,{ref:p,...y,tabIndex:-1,style:{outline:"none"},className:cn("relative flex min-h-0 w-full flex-col border-border bg-card text-card-foreground focus:outline-none",r==="embedded"?"max-w-none shadow-none":"max-w-lg"),children:T})})}const __iconNode$7=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Check=createLucideIcon("check",__iconNode$7);const __iconNode$6=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Cloud=createLucideIcon("cloud",__iconNode$6);const __iconNode$5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Info=createLucideIcon("info",__iconNode$5);const __iconNode$4=[["path",{d:"M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z",key:"1pdavp"}],["path",{d:"M20.054 15.987H3.946",key:"14rxg9"}]],Laptop=createLucideIcon("laptop",__iconNode$4);const __iconNode$3=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle$1=createLucideIcon("loader-circle",__iconNode$3);const __iconNode$2=[["path",{d:"M5 12h14",key:"1ays0h"}]],Minus=createLucideIcon("minus",__iconNode$2),sides=["top","right","bottom","left"],min=Math.min,max=Math.max,round=Math.round,floor=Math.floor,createCoords=r=>({x:r,y:r}),oppositeSideMap={left:"right",right:"left",bottom:"top",top:"bottom"};function clamp(r,e,t){return max(r,min(e,t))}function evaluate(r,e){return typeof r=="function"?r(e):r}function getSide(r){return r.split("-")[0]}function getAlignment(r){return r.split("-")[1]}function getOppositeAxis(r){return r==="x"?"y":"x"}function getAxisLength(r){return r==="y"?"height":"width"}function getSideAxis(r){const e=r[0];return e==="t"||e==="b"?"y":"x"}function getAlignmentAxis(r){return getOppositeAxis(getSideAxis(r))}function getAlignmentSides(r,e,t){t===void 0&&(t=!1);const n=getAlignment(r),i=getAlignmentAxis(r),s=getAxisLength(i);let o=i==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=getOppositePlacement(o)),[o,getOppositePlacement(o)]}function getExpandedPlacements(r){const e=getOppositePlacement(r);return[getOppositeAlignmentPlacement(r),e,getOppositeAlignmentPlacement(e)]}function getOppositeAlignmentPlacement(r){return r.includes("start")?r.replace("start","end"):r.replace("end","start")}const lrPlacement=["left","right"],rlPlacement=["right","left"],tbPlacement=["top","bottom"],btPlacement=["bottom","top"];function getSideList(r,e,t){switch(r){case"top":case"bottom":return t?e?rlPlacement:lrPlacement:e?lrPlacement:rlPlacement;case"left":case"right":return e?tbPlacement:btPlacement;default:return[]}}function getOppositeAxisPlacements(r,e,t,n){const i=getAlignment(r);let s=getSideList(getSide(r),t==="start",n);return i&&(s=s.map(o=>o+"-"+i),e&&(s=s.concat(s.map(getOppositeAlignmentPlacement)))),s}function getOppositePlacement(r){const e=getSide(r);return oppositeSideMap[e]+r.slice(e.length)}function expandPaddingObject(r){var e,t,n,i;return{top:(e=r.top)!=null?e:0,right:(t=r.right)!=null?t:0,bottom:(n=r.bottom)!=null?n:0,left:(i=r.left)!=null?i:0}}function getPaddingObject(r){return typeof r!="number"?expandPaddingObject(r):{top:r,right:r,bottom:r,left:r}}function rectToClientRect(r){const{x:e,y:t,width:n,height:i}=r;return{width:n,height:i,top:t,left:e,right:e+n,bottom:t+i,x:e,y:t}}function computeCoordsFromPlacement(r,e,t){let{reference:n,floating:i}=r;const s=getSideAxis(e),o=getAlignmentAxis(e),a=getAxisLength(o),d=getSide(e),l=s==="y",h=n.x+n.width/2-i.width/2,p=n.y+n.height/2-i.height/2,g=n[a]/2-i[a]/2;let S;switch(d){case"top":S={x:h,y:n.y-i.height};break;case"bottom":S={x:h,y:n.y+n.height};break;case"right":S={x:n.x+n.width,y:p};break;case"left":S={x:n.x-i.width,y:p};break;default:S={x:n.x,y:n.y}}const y=getAlignment(e);return y&&(S[o]+=g*(y==="end"?1:-1)*(t&&l?-1:1)),S}async function detectOverflow(r,e){var t;e===void 0&&(e={});const{x:n,y:i,platform:s,rects:o,elements:a,strategy:d}=r,{boundary:l="clippingAncestors",rootBoundary:h="viewport",elementContext:p="floating",altBoundary:g=!1,padding:S=0}=evaluate(e,r),y=getPaddingObject(S),E=a[g?p==="floating"?"reference":"floating":p],w=rectToClientRect(await s.getClippingRect({element:(t=await(s.isElement==null?void 0:s.isElement(E)))==null||t?E:E.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:l,rootBoundary:h,strategy:d})),T=p==="floating"?{x:n,y:i,width:o.floating.width,height:o.floating.height}:o.reference,I=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),C=await(s.isElement==null?void 0:s.isElement(I))&&await(s.getScale==null?void 0:s.getScale(I))||{x:1,y:1},O=rectToClientRect(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:T,offsetParent:I,strategy:d}):T);return{top:(w.top-O.top+y.top)/C.y,bottom:(O.bottom-w.bottom+y.bottom)/C.y,left:(w.left-O.left+y.left)/C.x,right:(O.right-w.right+y.right)/C.x}}const MAX_RESET_COUNT=50,computePosition$1=async(r,e,t)=>{const{placement:n="bottom",strategy:i="absolute",middleware:s=[],platform:o}=t,a=o.detectOverflow?o:{...o,detectOverflow},d=await(o.isRTL==null?void 0:o.isRTL(e));let l=await o.getElementRects({reference:r,floating:e,strategy:i}),{x:h,y:p}=computeCoordsFromPlacement(l,n,d),g=n,S=0;const y={};for(let v=0;v<s.length;v++){const E=s[v];if(!E)continue;const{name:w,fn:T}=E,{x:I,y:C,data:O,reset:P}=await T({x:h,y:p,initialPlacement:n,placement:g,strategy:i,middlewareData:y,rects:l,platform:a,elements:{reference:r,floating:e}});h=I??h,p=C??p,y[w]={...y[w],...O},P&&S<MAX_RESET_COUNT&&(S++,typeof P=="object"&&(P.placement&&(g=P.placement),P.rects&&(l=P.rects===!0?await o.getElementRects({reference:r,floating:e,strategy:i}):P.rects),{x:h,y:p}=computeCoordsFromPlacement(l,g,d)),v=-1)}return{x:h,y:p,placement:g,strategy:i,middlewareData:y}},arrow$3=r=>({name:"arrow",options:r,async fn(e){const{x:t,y:n,placement:i,rects:s,platform:o,elements:a,middlewareData:d}=e,{element:l,padding:h=0}=evaluate(r,e)||{};if(l==null)return{};const p=getPaddingObject(h),g={x:t,y:n},S=getAlignmentAxis(i),y=getAxisLength(S),v=await o.getDimensions(l),E=S==="y",w=E?"top":"left",T=E?"bottom":"right",I=E?"clientHeight":"clientWidth",C=s.reference[y]+s.reference[S]-g[S]-s.floating[y],O=g[S]-s.reference[S],P=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l));let D=P?P[I]:0;(!D||!await(o.isElement==null?void 0:o.isElement(P)))&&(D=a.floating[I]||s.floating[y]);const Y=C/2-O/2,re=D/2-v[y]/2-1,$=min(p[w],re),te=min(p[T],re),be=D-v[y]-te,fe=D/2-v[y]/2+Y,Pe=clamp($,fe,be),Ue=!d.arrow&&getAlignment(i)!=null&&fe!==Pe&&s.reference[y]/2-(fe<$?$:te)-v[y]/2<0,ke=Ue?fe<$?fe-$:fe-be:0;return{[S]:g[S]+ke,data:{[S]:Pe,centerOffset:fe-Pe-ke,...Ue&&{alignmentOffset:ke}},reset:Ue}}}),flip$2=function(r){return r===void 0&&(r={}),{name:"flip",options:r,async fn(e){var t,n;const{placement:i,middlewareData:s,rects:o,initialPlacement:a,platform:d,elements:l}=e,{mainAxis:h=!0,crossAxis:p=!0,fallbackPlacements:g,fallbackStrategy:S="bestFit",fallbackAxisSideDirection:y="none",flipAlignment:v=!0,...E}=evaluate(r,e);if((t=s.arrow)!=null&&t.alignmentOffset)return{};const w=getSide(i),T=getSideAxis(a),I=getSide(a)===a,C=await(d.isRTL==null?void 0:d.isRTL(l.floating)),O=g||(I||!v?[getOppositePlacement(a)]:getExpandedPlacements(a)),P=y!=="none";!g&&P&&O.push(...getOppositeAxisPlacements(a,v,y,C));const D=[a,...O],Y=await d.detectOverflow(e,E),re=[];let $=((n=s.flip)==null?void 0:n.overflows)||[];if(h&&re.push(Y[w]),p){const Pe=getAlignmentSides(i,o,C);re.push(Y[Pe[0]],Y[Pe[1]])}if($=[...$,{placement:i,overflows:re}],!re.every(Pe=>Pe<=0)){var te,be;const Pe=(((te=s.flip)==null?void 0:te.index)||0)+1,Ue=D[Pe];if(Ue&&(!(p==="alignment"?T!==getSideAxis(Ue):!1)||$.every(Ae=>getSideAxis(Ae.placement)===T?Ae.overflows[0]>0:!0)))return{data:{index:Pe,overflows:$},reset:{placement:Ue}};let ke=(be=$.filter(Ge=>Ge.overflows[0]<=0).sort((Ge,Ae)=>Ge.overflows[1]-Ae.overflows[1])[0])==null?void 0:be.placement;if(!ke)switch(S){case"bestFit":{var fe;const Ge=(fe=$.filter(Ae=>{if(P){const we=getSideAxis(Ae.placement);return we===T||we==="y"}return!0}).map(Ae=>[Ae.placement,Ae.overflows.filter(we=>we>0).reduce((we,ie)=>we+ie,0)]).sort((Ae,we)=>Ae[1]-we[1])[0])==null?void 0:fe[0];Ge&&(ke=Ge);break}case"initialPlacement":ke=a;break}if(i!==ke)return{reset:{placement:ke}}}return{}}}};function getSideOffsets(r,e){return{top:r.top-e.height,right:r.right-e.width,bottom:r.bottom-e.height,left:r.left-e.width}}function isAnySideFullyClipped(r){return sides.some(e=>r[e]>=0)}const hide$2=function(r){return r===void 0&&(r={}),{name:"hide",options:r,async fn(e){const{rects:t,platform:n}=e,{strategy:i="referenceHidden",...s}=evaluate(r,e);switch(i){case"referenceHidden":{const o=await n.detectOverflow(e,{...s,elementContext:"reference"}),a=getSideOffsets(o,t.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:isAnySideFullyClipped(a)}}}case"escaped":{const o=await n.detectOverflow(e,{...s,altBoundary:!0}),a=getSideOffsets(o,t.floating);return{data:{escapedOffsets:a,escaped:isAnySideFullyClipped(a)}}}default:return{}}}}},originSides=new Set(["left","top"]);async function convertValueToCoords(r,e){const{placement:t,platform:n,elements:i}=r,s=await(n.isRTL==null?void 0:n.isRTL(i.floating)),o=getSide(t),a=getAlignment(t),d=getSideAxis(t)==="y",l=originSides.has(o)?-1:1,h=s&&d?-1:1,p=evaluate(e,r);let{mainAxis:g,crossAxis:S,alignmentAxis:y}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return a&&typeof y=="number"&&(S=a==="end"?y*-1:y),d?{x:S*h,y:g*l}:{x:g*l,y:S*h}}const offset$2=function(r){return r===void 0&&(r=0),{name:"offset",options:r,async fn(e){var t,n;const{x:i,y:s,placement:o,middlewareData:a}=e,d=await convertValueToCoords(e,r);return o===((t=a.offset)==null?void 0:t.placement)&&(n=a.arrow)!=null&&n.alignmentOffset?{}:{x:i+d.x,y:s+d.y,data:{...d,placement:o}}}}},shift$2=function(r){return r===void 0&&(r={}),{name:"shift",options:r,async fn(e){const{x:t,y:n,placement:i,platform:s}=e,{mainAxis:o=!0,crossAxis:a=!1,limiter:d={fn:T=>{let{x:I,y:C}=T;return{x:I,y:C}}},...l}=evaluate(r,e),h={x:t,y:n},p=await s.detectOverflow(e,l),g=getSideAxis(i),S=getOppositeAxis(g);let y=h[S],v=h[g];const E=(T,I)=>clamp(I+p[T==="y"?"top":"left"],I,I-p[T==="y"?"bottom":"right"]);o&&(y=E(S,y)),a&&(v=E(g,v));const w=d.fn({...e,[S]:y,[g]:v});return{...w,data:{x:w.x-t,y:w.y-n,enabled:{[S]:o,[g]:a}}}}}},limitShift$2=function(r){return r===void 0&&(r={}),{options:r,fn(e){var t,n;const{x:i,y:s,placement:o,rects:a,middlewareData:d}=e,{offset:l=0,mainAxis:h=!0,crossAxis:p=!0}=evaluate(r,e),g={x:i,y:s},S=getSideAxis(o),y=getOppositeAxis(S);let v=g[y],E=g[S];const w=evaluate(l,e),T=typeof w=="number"?{mainAxis:w,crossAxis:0}:{mainAxis:(t=w.mainAxis)!=null?t:0,crossAxis:(n=w.crossAxis)!=null?n:0};if(h){const O=y==="y"?"height":"width",P=a.reference[y]-a.floating[O]+T.mainAxis,D=a.reference[y]+a.reference[O]-T.mainAxis;v<P?v=P:v>D&&(v=D)}if(p){var I,C;const O=y==="y"?"width":"height",P=originSides.has(getSide(o)),D=a.reference[S]-a.floating[O]+(P&&((I=d.offset)==null?void 0:I[S])||0)+(P?0:T.crossAxis),Y=a.reference[S]+a.reference[O]+(P?0:((C=d.offset)==null?void 0:C[S])||0)-(P?T.crossAxis:0);E<D?E=D:E>Y&&(E=Y)}return{[y]:v,[S]:E}}}},size$2=function(r){return r===void 0&&(r={}),{name:"size",options:r,async fn(e){const{placement:t,rects:n,platform:i,elements:s}=e,{apply:o=()=>{},...a}=evaluate(r,e),d=await i.detectOverflow(e,a),l=getSide(t),h=getAlignment(t),p=getSideAxis(t)==="y",{width:g,height:S}=n.floating;let y,v;l==="top"||l==="bottom"?(y=l,v=h===(await(i.isRTL==null?void 0:i.isRTL(s.floating))?"start":"end")?"left":"right"):(v=l,y=h==="end"?"top":"bottom");const E=S-d.top-d.bottom,w=g-d.left-d.right,T=min(S-d[y],E),I=min(g-d[v],w),C=e.middlewareData.shift,O=!C;let P=T,D=I;C!=null&&C.enabled.x&&(D=w),C!=null&&C.enabled.y&&(P=E),O&&!h&&(p?D=g-2*max(d.left,d.right):P=S-2*max(d.top,d.bottom)),await o({...e,availableWidth:D,availableHeight:P});const Y=await i.getDimensions(s.floating);return g!==Y.width||S!==Y.height?{reset:{rects:!0}}:{}}}};function hasWindow(){return typeof window<"u"}function getNodeName(r){return isNode(r)?(r.nodeName||"").toLowerCase():"#document"}function getWindow(r){var e;return(r==null||(e=r.ownerDocument)==null?void 0:e.defaultView)||window}function getDocumentElement(r){var e;return(e=(isNode(r)?r.ownerDocument:r.document)||window.document)==null?void 0:e.documentElement}function isNode(r){return hasWindow()?r instanceof Node||r instanceof getWindow(r).Node:!1}function isElement(r){return hasWindow()?r instanceof Element||r instanceof getWindow(r).Element:!1}function isHTMLElement(r){return hasWindow()?r instanceof HTMLElement||r instanceof getWindow(r).HTMLElement:!1}function isShadowRoot(r){return!hasWindow()||typeof ShadowRoot>"u"?!1:r instanceof ShadowRoot||r instanceof getWindow(r).ShadowRoot}function isOverflowElement(r){const{overflow:e,overflowX:t,overflowY:n,display:i}=getComputedStyle$1(r);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&i!=="inline"&&i!=="contents"}function isTableElement(r){return/^(table|td|th)$/.test(getNodeName(r))}function isTopLayer(r){try{if(r.matches(":popover-open"))return!0}catch{}try{return r.matches(":modal")}catch{return!1}}const willChangeRe=/transform|translate|scale|rotate|perspective|filter/,containRe=/paint|layout|strict|content/,isNotNone=r=>!!r&&r!=="none";let isWebKitValue;function isContainingBlock(r){const e=isElement(r)?getComputedStyle$1(r):r;return isNotNone(e.transform)||isNotNone(e.translate)||isNotNone(e.scale)||isNotNone(e.rotate)||isNotNone(e.perspective)||!isWebKit()&&(isNotNone(e.backdropFilter)||isNotNone(e.filter))||willChangeRe.test(e.willChange||"")||containRe.test(e.contain||"")}function getContainingBlock(r){let e=getParentNode(r);for(;isHTMLElement(e)&&!isLastTraversableNode(e);){if(isContainingBlock(e))return e;if(isTopLayer(e))return null;e=getParentNode(e)}return null}function isWebKit(){return isWebKitValue==null&&(isWebKitValue=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),isWebKitValue}function isLastTraversableNode(r){return/^(html|body|#document)$/.test(getNodeName(r))}function getComputedStyle$1(r){return getWindow(r).getComputedStyle(r)}function getNodeScroll(r){return isElement(r)?{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}:{scrollLeft:r.scrollX,scrollTop:r.scrollY}}function getParentNode(r){if(getNodeName(r)==="html")return r;const e=r.assignedSlot||r.parentNode||isShadowRoot(r)&&r.host||getDocumentElement(r);return isShadowRoot(e)?e.host:e}function getNearestOverflowAncestor(r){const e=getParentNode(r);return isLastTraversableNode(e)?(r.ownerDocument||r).body:isHTMLElement(e)&&isOverflowElement(e)?e:getNearestOverflowAncestor(e)}function getOverflowAncestors(r,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const i=getNearestOverflowAncestor(r),s=i===((n=r.ownerDocument)==null?void 0:n.body),o=getWindow(i);if(s){const a=getFrameElement(o);return e.concat(o,o.visualViewport||[],isOverflowElement(i)?i:[],a&&t?getOverflowAncestors(a):[])}else return e.concat(i,getOverflowAncestors(i,[],t))}function getFrameElement(r){return r.parent&&Object.getPrototypeOf(r.parent)?r.frameElement:null}function getCssDimensions(r){const e=getComputedStyle$1(r);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=isHTMLElement(r),s=i?r.offsetWidth:t,o=i?r.offsetHeight:n,a=round(t)!==s||round(n)!==o;return a&&(t=s,n=o),{width:t,height:n,$:a}}function unwrapElement(r){return isElement(r)?r:r.contextElement}function getScale(r){const e=unwrapElement(r);if(!isHTMLElement(e))return createCoords(1);const t=e.getBoundingClientRect(),{width:n,height:i,$:s}=getCssDimensions(e);let o=(s?round(t.width):t.width)/n,a=(s?round(t.height):t.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const noOffsets=createCoords(0);function getVisualOffsets(r){const e=getWindow(r);return!isWebKit()||!e.visualViewport?noOffsets:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function shouldAddVisualOffsets(r,e,t){return e===void 0&&(e=!1),!!t&&e&&t===getWindow(r)}function getBoundingClientRect(r,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const i=r.getBoundingClientRect(),s=unwrapElement(r);let o=createCoords(1);e&&(n?isElement(n)&&(o=getScale(n)):o=getScale(r));const a=shouldAddVisualOffsets(s,t,n)?getVisualOffsets(s):createCoords(0);let d=(i.left+a.x)/o.x,l=(i.top+a.y)/o.y,h=i.width/o.x,p=i.height/o.y;if(s&&n){const g=getWindow(s),S=isElement(n)?getWindow(n):n;let y=g,v=getFrameElement(y);for(;v&&S!==y;){const E=getScale(v),w=v.getBoundingClientRect(),T=getComputedStyle$1(v),I=w.left+(v.clientLeft+parseFloat(T.paddingLeft))*E.x,C=w.top+(v.clientTop+parseFloat(T.paddingTop))*E.y;d*=E.x,l*=E.y,h*=E.x,p*=E.y,d+=I,l+=C,y=getWindow(v),v=getFrameElement(y)}}return rectToClientRect({width:h,height:p,x:d,y:l})}function getWindowScrollBarX(r,e){const t=getNodeScroll(r).scrollLeft;return e?e.left+t:getBoundingClientRect(getDocumentElement(r)).left+t}function getHTMLOffset(r,e){const t=r.getBoundingClientRect(),n=t.left+e.scrollLeft-getWindowScrollBarX(r,t),i=t.top+e.scrollTop;return{x:n,y:i}}function convertOffsetParentRelativeRectToViewportRelativeRect(r){let{elements:e,rect:t,offsetParent:n,strategy:i}=r;const s=i==="fixed",o=getDocumentElement(n),a=e?isTopLayer(e.floating):!1;if(n===o||a&&s)return t;let d={scrollLeft:0,scrollTop:0},l=createCoords(1);const h=createCoords(0),p=isHTMLElement(n);if((p||!s)&&((getNodeName(n)!=="body"||isOverflowElement(o))&&(d=getNodeScroll(n)),p)){const S=getBoundingClientRect(n);l=getScale(n),h.x=S.x+n.clientLeft,h.y=S.y+n.clientTop}const g=o&&!p&&!s?getHTMLOffset(o,d):createCoords(0);return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-d.scrollLeft*l.x+h.x+g.x,y:t.y*l.y-d.scrollTop*l.y+h.y+g.y}}function getClientRects(r){return r.getClientRects?Array.from(r.getClientRects()):[]}function getDocumentRect(r){const e=getNodeScroll(r),t=r.ownerDocument.body,n=max(r.scrollWidth,r.clientWidth,t.scrollWidth,t.clientWidth),i=max(r.scrollHeight,r.clientHeight,t.scrollHeight,t.clientHeight);let s=-e.scrollLeft+getWindowScrollBarX(r);const o=-e.scrollTop;return getComputedStyle$1(t).direction==="rtl"&&(s+=max(r.clientWidth,t.clientWidth)-n),{width:n,height:i,x:s,y:o}}const SCROLLBAR_MAX=25;function getViewportRect(r,e,t){t===void 0&&(t="viewport");const n=t==="layoutViewport",i=getWindow(r),s=getDocumentElement(r),o=i.visualViewport;let a=s.clientWidth,d=s.clientHeight,l=0,h=0;if(o){const g=!isWebKit()||e==="fixed";n?g||(l=-o.offsetLeft,h=-o.offsetTop):(a=o.width,d=o.height,g&&(l=o.offsetLeft,h=o.offsetTop))}if(getWindowScrollBarX(s)<=0){const g=s.ownerDocument,S=g.body,y=getComputedStyle(S),v=g.compatMode==="CSS1Compat"&&parseFloat(y.marginLeft)+parseFloat(y.marginRight)||0,E=Math.abs(s.clientWidth-S.clientWidth-v),w=getComputedStyle(s).scrollbarGutter==="stable both-edges"?E/2:E;w<=SCROLLBAR_MAX&&(a-=w)}return{width:a,height:d,x:l,y:h}}function getInnerBoundingClientRect(r,e){const t=getBoundingClientRect(r,!0,e==="fixed"),n=t.top+r.clientTop,i=t.left+r.clientLeft,s=getScale(r),o=r.clientWidth*s.x,a=r.clientHeight*s.y,d=i*s.x,l=n*s.y;return{width:o,height:a,x:d,y:l}}function getClientRectFromClippingAncestor(r,e,t){let n;if(e==="viewport"||e==="layoutViewport")n=getViewportRect(r,t,e);else if(e==="document")n=getDocumentRect(getDocumentElement(r));else if(isElement(e))n=getInnerBoundingClientRect(e,t);else{const i=getVisualOffsets(r);n={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return rectToClientRect(n)}function getClippingElementAncestors(r,e){const t=e.get(r);if(t)return t;let n=getOverflowAncestors(r,[],!1).filter(a=>isElement(a)&&getNodeName(a)!=="body"),i=null;const s=getComputedStyle$1(r).position==="fixed";let o=s?getParentNode(r):r;for(;isElement(o)&&!isLastTraversableNode(o);){const a=getComputedStyle$1(o),d=isContainingBlock(o),l=i?i.position:s?"fixed":"";!d&&(l==="fixed"||l==="absolute"&&a.position==="static")?n=n.filter(p=>p!==o):i=a,o=getParentNode(o)}return e.set(r,n),n}function getClippingRect(r){let{element:e,boundary:t,rootBoundary:n,strategy:i}=r;const o=[...t==="clippingAncestors"?isTopLayer(e)?[]:getClippingElementAncestors(e,this._c):[].concat(t),n],a=getClientRectFromClippingAncestor(e,o[0],i);let d=a.top,l=a.right,h=a.bottom,p=a.left;for(let g=1;g<o.length;g++){const S=getClientRectFromClippingAncestor(e,o[g],i);d=max(S.top,d),l=min(S.right,l),h=min(S.bottom,h),p=max(S.left,p)}return{width:l-p,height:h-d,x:p,y:d}}function getDimensions(r){const{width:e,height:t}=getCssDimensions(r);return{width:e,height:t}}function getRectRelativeToOffsetParent(r,e,t){const n=isHTMLElement(e),i=getDocumentElement(e),s=t==="fixed",o=getBoundingClientRect(r,!0,s,e);let a={scrollLeft:0,scrollTop:0};const d=createCoords(0);if((n||!s)&&((getNodeName(e)!=="body"||isOverflowElement(i))&&(a=getNodeScroll(e)),n)){const g=getBoundingClientRect(e,!0,s,e);d.x=g.x+e.clientLeft,d.y=g.y+e.clientTop}!n&&i&&(d.x=getWindowScrollBarX(i));const l=i&&!n&&!s?getHTMLOffset(i,a):createCoords(0),h=o.left+a.scrollLeft-d.x-l.x,p=o.top+a.scrollTop-d.y-l.y;return{x:h,y:p,width:o.width,height:o.height}}function isStaticPositioned(r){return getComputedStyle$1(r).position==="static"}function getTrueOffsetParent(r,e){if(!isHTMLElement(r)||getComputedStyle$1(r).position==="fixed")return null;if(e)return e(r);let t=r.offsetParent;return getDocumentElement(r)===t&&(t=t.ownerDocument.body),t}function getOffsetParent(r,e){const t=getWindow(r);if(isTopLayer(r))return t;if(!isHTMLElement(r)){let i=getParentNode(r);for(;i&&!isLastTraversableNode(i);){if(isElement(i)&&!isStaticPositioned(i))return i;i=getParentNode(i)}return t}let n=getTrueOffsetParent(r,e);for(;n&&isTableElement(n)&&isStaticPositioned(n);)n=getTrueOffsetParent(n,e);return n&&isLastTraversableNode(n)&&isStaticPositioned(n)&&!isContainingBlock(n)?t:n||getContainingBlock(r)||t}const getElementRects=async function(r){const e=this.getOffsetParent||getOffsetParent,t=this.getDimensions,n=await t(r.floating);return{reference:getRectRelativeToOffsetParent(r.reference,await e(r.floating),r.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function isRTL(r){return getComputedStyle$1(r).direction==="rtl"}const platform={convertOffsetParentRelativeRectToViewportRelativeRect,getDocumentElement,getClippingRect,getOffsetParent,getElementRects,getClientRects,getDimensions,getScale,isElement,isRTL};function rectsAreEqual(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function observeMove(r,e,t){let n=null,i;const s=getDocumentElement(r);function o(){var h;clearTimeout(i),(h=n)==null||h.disconnect(),n=null}function a(h,p){h===void 0&&(h=!1),p===void 0&&(p=1),o();const g=r.getBoundingClientRect(),{left:S,top:y,width:v,height:E}=g;if(h||e(),!v||!E)return;const w=floor(y),T=floor(s.clientWidth-(S+v)),I=floor(s.clientHeight-(y+E)),C=floor(S),P={rootMargin:-w+"px "+-T+"px "+-I+"px "+-C+"px",threshold:max(0,min(1,p))||1};let D=!0;function Y(re){const $=re[0].intersectionRatio;if(!rectsAreEqual(g,r.getBoundingClientRect()))return a();if($!==p){if(!D)return a();$?a(!1,$):i=setTimeout(()=>{a(!1,1e-7)},1e3)}D=!1}try{n=new IntersectionObserver(Y,{...P,root:s.ownerDocument})}catch{n=new IntersectionObserver(Y,P)}n.observe(r)}const d=getWindow(r),l=()=>a(t);return d.addEventListener("resize",l),a(!0),()=>{d.removeEventListener("resize",l),o()}}function autoUpdate(r,e,t,n){n===void 0&&(n={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:d=!1}=n,l=unwrapElement(r),h=i||s?[...l?getOverflowAncestors(l):[],...e?getOverflowAncestors(e):[]]:[];h.forEach(w=>{i&&w.addEventListener("scroll",t),s&&w.addEventListener("resize",t)});const p=l&&a?observeMove(l,t,s):null;let g=-1,S=null;o&&(S=new ResizeObserver(w=>{let[T]=w;T&&T.target===l&&S&&e&&(S.unobserve(e),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{var I;(I=S)==null||I.observe(e)})),t()}),l&&!d&&S.observe(l),e&&S.observe(e));let y,v=d?getBoundingClientRect(r):null;d&&E();function E(){const w=getBoundingClientRect(r);v&&!rectsAreEqual(v,w)&&t(),v=w,y=requestAnimationFrame(E)}return t(),()=>{var w;h.forEach(T=>{i&&T.removeEventListener("scroll",t),s&&T.removeEventListener("resize",t)}),p?.(),(w=S)==null||w.disconnect(),S=null,d&&cancelAnimationFrame(y)}}const offset$1=offset$2,shift$1=shift$2,flip$1=flip$2,size$1=size$2,hide$1=hide$2,arrow$2=arrow$3,limitShift$1=limitShift$2,computePosition=(r,e,t)=>{const n=new Map,i=t??{},s={...platform,...i.platform,_c:n};return computePosition$1(r,e,{...i,platform:s})};var isClient=typeof document<"u",noop$2=function(){},index=isClient?reactExports.useLayoutEffect:noop$2;function deepEqual$1(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(typeof r=="function"&&r.toString()===e.toString())return!0;let t,n,i;if(r&&e&&typeof r=="object"){if(Array.isArray(r)){if(t=r.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!deepEqual$1(r[n],e[n]))return!1;return!0}if(i=Object.keys(r),t=i.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;)if(!{}.hasOwnProperty.call(e,i[n]))return!1;for(n=t;n--!==0;){const s=i[n];if(!(s==="_owner"&&r.$$typeof)&&!deepEqual$1(r[s],e[s]))return!1}return!0}return r!==r&&e!==e}function getDPR(r){return typeof window>"u"?1:(r.ownerDocument.defaultView||window).devicePixelRatio||1}function roundByDPR(r,e){const t=getDPR(r);return Math.round(e*t)/t}function useLatestRef(r){const e=reactExports.useRef(r);return index(()=>{e.current=r}),e}function useFloating(r){r===void 0&&(r={});const{placement:e="bottom",strategy:t="absolute",middleware:n=[],platform:i,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:d,open:l}=r,[h,p]=reactExports.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[g,S]=reactExports.useState(n);deepEqual$1(g,n)||S(n);const[y,v]=reactExports.useState(null),[E,w]=reactExports.useState(null),T=reactExports.useCallback(Ae=>{Ae!==P.current&&(P.current=Ae,v(Ae))},[]),I=reactExports.useCallback(Ae=>{Ae!==D.current&&(D.current=Ae,w(Ae))},[]),C=s||y,O=o||E,P=reactExports.useRef(null),D=reactExports.useRef(null),Y=reactExports.useRef(h),re=d!=null,$=useLatestRef(d),te=useLatestRef(i),be=useLatestRef(l),fe=reactExports.useCallback(()=>{if(!P.current||!D.current)return;const Ae={placement:e,strategy:t,middleware:g};te.current&&(Ae.platform=te.current),computePosition(P.current,D.current,Ae).then(we=>{const ie={...we,isPositioned:be.current!==!1};Pe.current&&!deepEqual$1(Y.current,ie)&&(Y.current=ie,reactDomExports.flushSync(()=>{p(ie)}))})},[g,e,t,te,be]);index(()=>{l===!1&&Y.current.isPositioned&&(Y.current.isPositioned=!1,p(Ae=>({...Ae,isPositioned:!1})))},[l]);const Pe=reactExports.useRef(!1);index(()=>(Pe.current=!0,()=>{Pe.current=!1}),[]),index(()=>{if(C&&(P.current=C),O&&(D.current=O),C&&O){if($.current)return $.current(C,O,fe);fe()}},[C,O,fe,$,re]);const Ue=reactExports.useMemo(()=>({reference:P,floating:D,setReference:T,setFloating:I}),[T,I]),ke=reactExports.useMemo(()=>({reference:C,floating:O}),[C,O]),Ge=reactExports.useMemo(()=>{const Ae={position:t,left:0,top:0};if(!ke.floating)return Ae;const we=roundByDPR(ke.floating,h.x),ie=roundByDPR(ke.floating,h.y);return a?{...Ae,transform:"translate("+we+"px, "+ie+"px)",...getDPR(ke.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:we,top:ie}},[t,a,ke.floating,h.x,h.y]);return reactExports.useMemo(()=>({...h,update:fe,refs:Ue,elements:ke,floatingStyles:Ge}),[h,fe,Ue,ke,Ge])}const arrow$1=r=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:r,fn(t){const{element:n,padding:i}=typeof r=="function"?r(t):r;return n&&e(n)?n.current!=null?arrow$2({element:n.current,padding:i}).fn(t):{}:n?arrow$2({element:n,padding:i}).fn(t):{}}}},offset=(r,e)=>{const t=offset$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},shift=(r,e)=>{const t=shift$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},limitShift=(r,e)=>({fn:limitShift$1(r).fn,options:[r,e]}),flip=(r,e)=>{const t=flip$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},size=(r,e)=>{const t=size$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},hide=(r,e)=>{const t=hide$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},arrow=(r,e)=>{const t=arrow$1(r);return{name:t.name,fn:t.fn,options:[r,e]}};var __defProp$4=Object.defineProperty,__name$3=(r,e)=>__defProp$4(r,"name",{value:e,configurable:!0});function useSize(r){const[e,t]=reactExports.useState(void 0);return useLayoutEffect2(()=>{if(r){t({width:r.offsetWidth,height:r.offsetHeight});const n=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let o,a;if("borderBoxSize"in s){const d=s.borderBoxSize,l=Array.isArray(d)?d[0]:d;o=l.inlineSize,a=l.blockSize}else o=r.offsetWidth,a=r.offsetHeight;t({width:o,height:a})});return n.observe(r,{box:"border-box"}),()=>n.unobserve(r)}else t(void 0)},[r]),e}__name$3(useSize,"useSize");var __defProp$3=Object.defineProperty,__name$2=(r,e)=>__defProp$3(r,"name",{value:e,configurable:!0}),POPPER_NAME="Popper",[createPopperContext,createPopperScope]=createContextScope(POPPER_NAME),[PopperProvider,usePopperContext]=createPopperContext(POPPER_NAME),Popper=__name$2(r=>{const{__scopePopper:e,children:t}=r,[n,i]=reactExports.useState(null),[s,o]=reactExports.useState(void 0);return jsxRuntimeExports.jsx(PopperProvider,{scope:e,anchor:n,onAnchorChange:i,placementState:s,setPlacementState:o,children:t})},"Popper"),ANCHOR_NAME="PopperAnchor",PopperAnchor=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:n,virtualRef:i,...s}=e,o=usePopperContext(ANCHOR_NAME,n),a=reactExports.useRef(null),d=o.onAnchorChange,l=reactExports.useCallback(v=>{a.current=v,v&&d(v)},[d]),h=useComposedRefs(t,l),p=reactExports.useRef(null);reactExports.useEffect(()=>{if(!i)return;const v=p.current;p.current=i.current,v!==p.current&&d(p.current)});const g=o.placementState&&getSideAndAlignFromPlacement(o.placementState),S=g?.[0],y=g?.[1];return i?null:jsxRuntimeExports.jsx(Primitive.div,{"data-radix-popper-side":S,"data-radix-popper-align":y,...s,ref:h})},"PopperAnchor")),CONTENT_NAME$1="PopperContent",[PopperContentProvider,useContentContext]=createPopperContext(CONTENT_NAME$1),PopperContent=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:n,side:i="bottom",sideOffset:s=0,align:o="center",alignOffset:a=0,arrowPadding:d=0,avoidCollisions:l=!0,collisionBoundary:h=[],collisionPadding:p=0,sticky:g="partial",hideWhenDetached:S=!1,updatePositionStrategy:y="optimized",onPlaced:v,...E}=e,w=usePopperContext(CONTENT_NAME$1,n),[T,I]=reactExports.useState(null),C=useComposedRefs(t,I),[O,P]=reactExports.useState(null),D=useSize(O),Y=D?.width??0,re=D?.height??0,$=i+(o!=="center"?"-"+o:""),te=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},be=Array.isArray(h)?h:[h],fe=be.length>0,Pe={padding:te,boundary:be.filter(isNotNull),altBoundary:fe},{refs:Ue,floatingStyles:ke,placement:Ge,isPositioned:Ae,middlewareData:we}=useFloating({strategy:"fixed",placement:$,whileElementsMounted:__name$2((...Fe)=>autoUpdate(...Fe,{animationFrame:y==="always"}),"whileElementsMounted"),elements:{reference:w.anchor},middleware:[offset({mainAxis:s+re,alignmentAxis:a}),l&&shift({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?limitShift():void 0,...Pe}),l&&flip({...Pe}),size({...Pe,apply:__name$2(({elements:Fe,rects:De,availableWidth:K,availableHeight:x})=>{const{width:_,height:A}=De.reference,N=Fe.floating.style;N.setProperty("--radix-popper-available-width",`${K}px`),N.setProperty("--radix-popper-available-height",`${x}px`),N.setProperty("--radix-popper-anchor-width",`${_}px`),N.setProperty("--radix-popper-anchor-height",`${A}px`)},"apply")}),O&&arrow({element:O,padding:d}),transformOrigin({arrowWidth:Y,arrowHeight:re}),S&&hide({strategy:"referenceHidden",...Pe,boundary:fe?Pe.boundary:void 0})]}),ie=w.setPlacementState;useLayoutEffect2(()=>(ie(Ge),()=>{ie(void 0)}),[Ge,ie]);const[xe,Ne]=getSideAndAlignFromPlacement(Ge),Ce=useCallbackRef(v);useLayoutEffect2(()=>{Ae&&Ce?.()},[Ae,Ce]);const je=we.arrow?.x,Ve=we.arrow?.y,We=we.arrow?.centerOffset!==0,[Be,Ie]=reactExports.useState();return useLayoutEffect2(()=>{T&&Ie(window.getComputedStyle(T).zIndex)},[T]),jsxRuntimeExports.jsx("div",{ref:Ue.setFloating,"data-radix-popper-content-wrapper":"",style:{...ke,transform:Ae?ke.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Be,"--radix-popper-transform-origin":[we.transformOrigin?.x,we.transformOrigin?.y].join(" "),...we.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:jsxRuntimeExports.jsx(PopperContentProvider,{scope:n,placedSide:xe,placedAlign:Ne,onArrowChange:P,arrowX:je,arrowY:Ve,shouldHideArrow:We,children:jsxRuntimeExports.jsx(Primitive.div,{"data-side":xe,"data-align":Ne,...E,ref:C,style:{...E.style,animation:Ae?E.style?.animation:"none"}})})})},"PopperContent"));function isNotNull(r){return r!==null}__name$2(isNotNull,"isNotNull");var transformOrigin=__name$2(r=>({name:"transformOrigin",options:r,fn(e){const{placement:t,rects:n,middlewareData:i}=e,o=i.arrow?.centerOffset!==0,a=o?0:r.arrowWidth,d=o?0:r.arrowHeight,[l,h]=getSideAndAlignFromPlacement(t),p={start:"0%",center:"50%",end:"100%"}[h],g=(i.arrow?.x??0)+a/2,S=(i.arrow?.y??0)+d/2;let y="",v="";return l==="bottom"?(y=o?p:`${g}px`,v=`${-d}px`):l==="top"?(y=o?p:`${g}px`,v=`${n.floating.height+d}px`):l==="right"?(y=`${-d}px`,v=o?p:`${S}px`):l==="left"&&(y=`${n.floating.width+d}px`,v=o?p:`${S}px`),{data:{x:y,y:v}}}}),"transformOrigin");function getSideAndAlignFromPlacement(r){const[e,t="center"]=r.split("-");return[e,t]}__name$2(getSideAndAlignFromPlacement,"getSideAndAlignFromPlacement");var Root2=Popper,Anchor=PopperAnchor,Content=PopperContent,__defProp$2=Object.defineProperty,__name$1=(r,e)=>__defProp$2(r,"name",{value:e,configurable:!0}),VISUALLY_HIDDEN_STYLES=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),VisuallyHidden=reactExports.forwardRef(__name$1(function(e,t){return jsxRuntimeExports.jsx(Primitive.span,{...e,ref:t,style:{...VISUALLY_HIDDEN_STYLES,...e.style}})},"VisuallyHidden")),Root=VisuallyHidden,__defProp$1=Object.defineProperty,__name=(r,e)=>__defProp$1(r,"name",{value:e,configurable:!0}),[createTooltipContext,createTooltipScope]=createContextScope("Tooltip",[createPopperScope]),usePopperScope=createPopperScope(),PROVIDER_NAME="TooltipProvider",DEFAULT_DELAY_DURATION=700,TOOLTIP_OPEN="tooltip.open",[TooltipProviderContextProvider,useTooltipProviderContext]=createTooltipContext(PROVIDER_NAME),TooltipProvider$1=__name(r=>{const{__scopeTooltip:e,delayDuration:t=DEFAULT_DELAY_DURATION,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:s}=r,o=reactExports.useRef(!0),a=reactExports.useRef(!1),d=reactExports.useRef(0);return reactExports.useEffect(()=>{const l=d.current;return()=>window.clearTimeout(l)},[]),jsxRuntimeExports.jsx(TooltipProviderContextProvider,{scope:e,isOpenDelayedRef:o,delayDuration:t,onOpen:reactExports.useCallback(()=>{n<=0||(window.clearTimeout(d.current),o.current=!1)},[n]),onClose:reactExports.useCallback(()=>{n<=0||(window.clearTimeout(d.current),d.current=window.setTimeout(()=>o.current=!0,n))},[n]),isPointerInTransitRef:a,onPointerInTransitChange:reactExports.useCallback(l=>{a.current=l},[]),disableHoverableContent:i,children:s})},"TooltipProvider"),TOOLTIP_NAME="Tooltip",[TooltipContextProvider,useTooltipContext]=createTooltipContext(TOOLTIP_NAME),Tooltip$1=__name(r=>{const{__scopeTooltip:e,children:t,open:n,defaultOpen:i,onOpenChange:s,disableHoverableContent:o,delayDuration:a}=r,d=useTooltipProviderContext(TOOLTIP_NAME,r.__scopeTooltip),l=usePopperScope(e),[h,p]=reactExports.useState(null),[g,S]=reactExports.useState(void 0),y=useId(),v=reactExports.useRef(0),E=o??d.disableHoverableContent,w=a??d.delayDuration,T=reactExports.useRef(!1),[I,C]=useControllableState({prop:n,defaultProp:i??!1,onChange:__name($=>{$?(d.onOpen(),document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN))):d.onClose(),s?.($)},"onChange"),caller:TOOLTIP_NAME}),O=reactExports.useMemo(()=>I?T.current?"delayed-open":"instant-open":"closed",[I]),P=reactExports.useCallback(()=>{window.clearTimeout(v.current),v.current=0,T.current=!1,C(!0)},[C]),D=reactExports.useCallback(()=>{window.clearTimeout(v.current),v.current=0,C(!1)},[C]),Y=reactExports.useCallback(()=>{window.clearTimeout(v.current),v.current=window.setTimeout(()=>{T.current=!0,C(!0),v.current=0},w)},[w,C]);reactExports.useEffect(()=>()=>{v.current&&(window.clearTimeout(v.current),v.current=0)},[]);const re=g??y;return jsxRuntimeExports.jsx(Root2,{...l,children:jsxRuntimeExports.jsx(TooltipContextProvider,{scope:e,contentId:re,setContentId:S,open:I,stateAttribute:O,trigger:h,onTriggerChange:p,onTriggerEnter:reactExports.useCallback(()=>{d.isOpenDelayedRef.current?Y():P()},[d.isOpenDelayedRef,Y,P]),onTriggerLeave:reactExports.useCallback(()=>{E?D():(window.clearTimeout(v.current),v.current=0)},[D,E]),onOpen:P,onClose:D,disableHoverableContent:E,children:t})})},"Tooltip"),TRIGGER_NAME="TooltipTrigger",TooltipTrigger$1=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:n,...i}=e,s=useTooltipContext(TRIGGER_NAME,n),o=useTooltipProviderContext(TRIGGER_NAME,n),a=usePopperScope(n),d=reactExports.useRef(null),l=useComposedRefs(t,d,s.onTriggerChange),h=reactExports.useRef(!1),p=reactExports.useRef(!1),g=reactExports.useCallback(()=>h.current=!1,[]);return reactExports.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),jsxRuntimeExports.jsx(Anchor,{asChild:!0,...a,children:jsxRuntimeExports.jsx(Primitive.button,{"aria-describedby":s.open?s.contentId:void 0,"data-state":s.stateAttribute,...i,ref:l,onPointerMove:composeEventHandlers(e.onPointerMove,S=>{S.pointerType!=="touch"&&!p.current&&!o.isPointerInTransitRef.current&&(s.onTriggerEnter(),p.current=!0)}),onPointerLeave:composeEventHandlers(e.onPointerLeave,()=>{s.onTriggerLeave(),p.current=!1}),onPointerDown:composeEventHandlers(e.onPointerDown,()=>{s.open&&s.onClose(),h.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:composeEventHandlers(e.onFocus,()=>{h.current||s.onOpen()}),onBlur:composeEventHandlers(e.onBlur,s.onClose),onClick:composeEventHandlers(e.onClick,s.onClose)})})},"TooltipTrigger")),PORTAL_NAME="TooltipPortal",[PortalProvider,usePortalContext]=createTooltipContext(PORTAL_NAME,{forceMount:void 0}),TooltipPortal$1=__name(r=>{const{__scopeTooltip:e,forceMount:t,children:n,container:i}=r,s=useTooltipContext(PORTAL_NAME,e);return jsxRuntimeExports.jsx(PortalProvider,{scope:e,forceMount:t,children:jsxRuntimeExports.jsx(Presence,{present:t||s.open,children:jsxRuntimeExports.jsx(Portal$1,{asChild:!0,container:i,children:n})})})},"TooltipPortal"),CONTENT_NAME="TooltipContent",TooltipContent$1=reactExports.forwardRef(__name(function(e,t){const n=usePortalContext(CONTENT_NAME,e.__scopeTooltip),{forceMount:i=n.forceMount,side:s="top",...o}=e,a=useTooltipContext(CONTENT_NAME,e.__scopeTooltip);return jsxRuntimeExports.jsx(Presence,{present:i||a.open,children:a.disableHoverableContent?jsxRuntimeExports.jsx(TooltipContentImpl,{side:s,...o,ref:t}):jsxRuntimeExports.jsx(TooltipContentHoverable,{side:s,...o,ref:t})})},"TooltipContent")),TooltipContentHoverable=reactExports.forwardRef(__name(function(e,t){const n=useTooltipContext(CONTENT_NAME,e.__scopeTooltip),i=useTooltipProviderContext(CONTENT_NAME,e.__scopeTooltip),s=reactExports.useRef(null),o=useComposedRefs(t,s),[a,d]=reactExports.useState(null),{trigger:l,onClose:h}=n,p=s.current,{onPointerInTransitChange:g}=i,S=reactExports.useCallback(()=>{d(null),g(!1)},[g]),y=reactExports.useCallback((v,E)=>{const w=v.currentTarget,T={x:v.clientX,y:v.clientY},I=getExitSideFromRect(T,w.getBoundingClientRect()),C=getPaddedExitPoints(T,I),O=getPointsFromRect(E.getBoundingClientRect()),P=getHull([...C,...O]);d(P),g(!0)},[g]);return reactExports.useEffect(()=>()=>S(),[S]),reactExports.useEffect(()=>{if(l&&p){const v=__name(w=>y(w,p),"handleTriggerLeave"),E=__name(w=>y(w,l),"handleContentLeave");return l.addEventListener("pointerleave",v),p.addEventListener("pointerleave",E),()=>{l.removeEventListener("pointerleave",v),p.removeEventListener("pointerleave",E)}}},[l,p,y,S]),reactExports.useEffect(()=>{if(a){const v=__name(E=>{const w=E.target,T={x:E.clientX,y:E.clientY},I=l?.contains(w)||p?.contains(w),C=!isPointInPolygon(T,a);I?S():C&&(S(),h())},"handleTrackPointerGrace");return document.addEventListener("pointermove",v),()=>document.removeEventListener("pointermove",v)}},[l,p,a,h,S]),jsxRuntimeExports.jsx(TooltipContentImpl,{...e,ref:o})},"TooltipContentHoverable")),Slottable=createSlottable("TooltipContent"),TooltipContentImpl=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:n,children:i,"aria-label":s,id:o,onEscapeKeyDown:a,onPointerDownOutside:d,...l}=e,h=useTooltipContext(CONTENT_NAME,n),p=usePopperScope(n),{onClose:g}=h;reactExports.useEffect(()=>(document.addEventListener(TOOLTIP_OPEN,g),()=>document.removeEventListener(TOOLTIP_OPEN,g)),[g]),reactExports.useEffect(()=>{if(h.trigger){const y=__name(v=>{v.target instanceof Node&&v.target.contains(h.trigger)&&g()},"handleScroll");return window.addEventListener("scroll",y,{capture:!0}),()=>window.removeEventListener("scroll",y,{capture:!0})}},[h.trigger,g]);const{setContentId:S}=h;return useLayoutEffect2(()=>(S(o),()=>{S(void 0)}),[o,S]),jsxRuntimeExports.jsx(DismissableLayer,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:a,onPointerDownOutside:d,onFocusOutside:y=>y.preventDefault(),onDismiss:g,children:jsxRuntimeExports.jsxs(Content,{"data-state":h.stateAttribute,role:s?void 0:"tooltip",id:s?void 0:h.contentId,...p,...l,ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[jsxRuntimeExports.jsx(Slottable,{children:i}),s?jsxRuntimeExports.jsx(Root,{id:h.contentId,role:"tooltip",children:s}):null]})})},"TooltipContentImpl"));function getExitSideFromRect(r,e){const t=Math.abs(e.top-r.y),n=Math.abs(e.bottom-r.y),i=Math.abs(e.right-r.x),s=Math.abs(e.left-r.x);switch(Math.min(t,n,i,s)){case s:return"left";case i:return"right";case t:return"top";case n:return"bottom";default:throw new Error("unreachable")}}__name(getExitSideFromRect,"getExitSideFromRect");function getPaddedExitPoints(r,e,t=5){const n=[];switch(e){case"top":n.push({x:r.x-t,y:r.y+t},{x:r.x+t,y:r.y+t});break;case"bottom":n.push({x:r.x-t,y:r.y-t},{x:r.x+t,y:r.y-t});break;case"left":n.push({x:r.x+t,y:r.y-t},{x:r.x+t,y:r.y+t});break;case"right":n.push({x:r.x-t,y:r.y-t},{x:r.x-t,y:r.y+t});break}return n}__name(getPaddedExitPoints,"getPaddedExitPoints");function getPointsFromRect(r){const{top:e,right:t,bottom:n,left:i}=r;return[{x:i,y:e},{x:t,y:e},{x:t,y:n},{x:i,y:n}]}__name(getPointsFromRect,"getPointsFromRect");function isPointInPolygon(r,e){const{x:t,y:n}=r;let i=!1;for(let s=0,o=e.length-1;s<e.length;o=s++){const a=e[s],d=e[o],l=a.x,h=a.y,p=d.x,g=d.y;h>n!=g>n&&t<(p-l)*(n-h)/(g-h)+l&&(i=!i)}return i}__name(isPointInPolygon,"isPointInPolygon");function getHull(r){const e=r.slice();return e.sort((t,n)=>t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0),getHullPresorted(e)}__name(getHull,"getHull");function getHullPresorted(r){if(r.length<=1)return r.slice();const e=[];for(let n=0;n<r.length;n++){const i=r[n];for(;e.length>=2;){const s=e[e.length-1],o=e[e.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))e.pop();else break}e.push(i)}e.pop();const t=[];for(let n=r.length-1;n>=0;n--){const i=r[n];for(;t.length>=2;){const s=t[t.length-1],o=t[t.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))t.pop();else break}t.push(i)}return t.pop(),e.length===1&&t.length===1&&e[0].x===t[0].x&&e[0].y===t[0].y?e:e.concat(t)}__name(getHullPresorted,"getHullPresorted");var Provider=TooltipProvider$1,Root3=Tooltip$1,Trigger=TooltipTrigger$1,Portal=TooltipPortal$1,Content2=TooltipContent$1;const TooltipProvider=Provider,Tooltip=Root3,TooltipTrigger=Trigger,TooltipPortal=Portal,TooltipContent=reactExports.forwardRef(({className:r,sideOffset:e=4,...t},n)=>jsxRuntimeExports.jsx(Content2,{ref:n,sideOffset:e,className:cn("z-[var(--layer-popover)] overflow-hidden rounded-md border border-border/50 bg-popover","px-2 py-1 text-xs text-popover-foreground shadow-md","animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...t}));TooltipContent.displayName=Content2.displayName;function BrandInfo({logo:r,info:e,infoLabel:t="Details",className:n}){const[i,s]=reactExports.useState(!1),o=reactExports.useRef(null);return jsxRuntimeExports.jsxs("div",{className:cn("inline-flex min-w-0 items-center gap-1",n),children:[r,e!=null&&e!==!1?jsxRuntimeExports.jsx(TooltipProvider,{delayDuration:150,children:jsxRuntimeExports.jsxs(Tooltip,{open:i,onOpenChange:s,children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsx("button",{ref:o,type:"button","aria-label":t,"aria-expanded":i,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-primary/10 hover:text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onPointerDown:a=>a.preventDefault(),onClick:a=>{a.preventDefault(),s(d=>!d)},children:jsxRuntimeExports.jsx(Info,{className:"h-4 w-4","aria-hidden":"true"})})}),jsxRuntimeExports.jsx(TooltipPortal,{children:jsxRuntimeExports.jsx(TooltipContent,{side:"bottom",align:"center",collisionPadding:12,onPointerDownOutside:a=>{a.target instanceof Node&&o.current?.contains(a.target)&&a.preventDefault()},className:"max-w-[min(320px,calc(100vw-24px))] space-y-2 p-3 text-left leading-relaxed [overflow-wrap:anywhere]",children:e})})]})}):null]})}const Checkbox=reactExports.forwardRef(({className:r,indeterminate:e=!1,...t},n)=>{const i=reactExports.useRef(null);return reactExports.useImperativeHandle(n,()=>i.current),reactExports.useEffect(()=>{i.current&&(i.current.indeterminate=e)}),jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0 items-center justify-center align-middle",children:[jsxRuntimeExports.jsx("input",{...t,ref:i,type:"checkbox",className:cn("peer m-0 h-4 w-4 shrink-0 appearance-none rounded border border-input bg-background checked:border-primary checked:bg-primary checked:bg-none indeterminate:border-primary indeterminate:bg-primary indeterminate:bg-none disabled:cursor-not-allowed disabled:opacity-50",controlFocusClass,r)}),jsxRuntimeExports.jsx(Check,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-checked:block peer-indeterminate:hidden peer-disabled:opacity-50",strokeWidth:3}),jsxRuntimeExports.jsx(Minus,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-indeterminate:block peer-disabled:opacity-50",strokeWidth:3})]})});Checkbox.displayName="Checkbox";function FormField({label:r,error:e,hint:t,labelAside:n,children:i,className:s,...o}){const a=reactExports.useId(),d=`${a}-error`,l=`${a}-hint`,h=[e?d:void 0,t?l:void 0].filter(Boolean).join(" ")||void 0;return jsxRuntimeExports.jsxs("div",{...o,className:cn("flex flex-col gap-1.5",s),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("label",{htmlFor:a,className:"text-[13px] font-medium text-foreground",children:r}),n]}),i({id:a,...e?{"aria-invalid":!0}:{},"aria-describedby":h}),e?jsxRuntimeExports.jsx("p",{id:d,role:"alert",className:"text-[13px] text-destructive",children:e}):null,t?jsxRuntimeExports.jsx("div",{id:l,className:"text-[13px] text-muted-foreground",children:t}):null]})}const EmailInput=reactExports.forwardRef(({onInput:r,onChange:e,autoCapitalize:t="none",spellCheck:n=!1,...i},s)=>{const o=reactExports.useRef(null),a=reactExports.useRef(null);reactExports.useImperativeHandle(s,()=>o.current,[]);const d=reactExports.useCallback(h=>{const p=a.current??(a.current=h.ownerDocument.createElement("input"));p.type="email",p.multiple=h.multiple,p.required=h.required,p.value=h.value,h.setCustomValidity(p.validity.valid?"":p.validationMessage)},[]);reactExports.useLayoutEffect(()=>{o.current&&d(o.current)}),reactExports.useEffect(()=>{const h=o.current,p=h?.form;if(!h||!p)return;const g=()=>queueMicrotask(()=>d(h));return p.addEventListener("reset",g),()=>p.removeEventListener("reset",g)},[i.form,d]);const l=h=>{d(h),queueMicrotask(()=>d(h))};return jsxRuntimeExports.jsx(Input,{...i,ref:o,type:"text",inputMode:"email",autoCapitalize:t,spellCheck:n,onInput:h=>{l(h.currentTarget),r?.(h)},onChange:h=>{l(h.currentTarget),e?.(h)}})});EmailInput.displayName="EmailInput";const FOCUSABLE=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","summary",'[tabindex]:not([tabindex="-1"])'].join(","),PRIMARY_SELECTOR="[data-pod-sign-in-primary]";function isReachable(r){if(r.hidden||r.closest("[hidden]")||r.matches(":disabled"))return!1;const e=r.ownerDocument.defaultView?.getComputedStyle(r);if(e&&(e.display==="none"||e.visibility==="hidden"))return!1;for(let t=r.parentElement;t;t=t.parentElement){if(t.tagName!=="DETAILS"||t.open)continue;const n=Array.from(t.children).find(i=>i.tagName==="SUMMARY");if(!n||!(n===r||n.contains(r)))return!1}return!0}function useModalFocus(r,e){const t=reactExports.useRef(null),n=reactExports.useRef(e);return n.current=e,reactExports.useEffect(()=>{if(!r)return;const i=document.activeElement instanceof HTMLElement?document.activeElement:null;t.current?.focus();const s=o=>{if(o.key==="Escape"&&n.current){o.preventDefault(),n.current();return}if(o.key!=="Tab")return;const a=t.current;if(!a)return;const d=Array.from(a.querySelectorAll(FOCUSABLE)).filter(isReachable);if(d.length===0){o.preventDefault(),a.focus();return}const l=d.indexOf(document.activeElement);if(!o.shiftKey&&document.activeElement===a){const p=d.find(g=>g.matches(PRIMARY_SELECTOR));if(p){o.preventDefault(),p.focus();return}}const h=o.shiftKey?l<=0?d.length-1:l-1:l===d.length-1?0:l+1;o.preventDefault(),d[h]?.focus()};return document.addEventListener("keydown",s),()=>{document.removeEventListener("keydown",s),i?.focus()}},[r]),t}const bodyClass="flex min-h-0 w-full max-w-[480px] flex-1 flex-col";function PodSignInFrame({presentation:r,ariaLabel:e,appIntro:t,children:n,modal:i=!0,onClose:s,closeLabel:o,dataAttributes:a}){const d=r==="dialog"&&i,l=useModalFocus(d,s),h=t;if(r==="window")return jsxRuntimeExports.jsx("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"window",...a,className:"pod-sign-in flex h-full min-h-0 w-full min-w-0 justify-center overflow-hidden bg-background text-foreground",children:jsxRuntimeExports.jsx("div",{className:bodyClass,children:n})});if(r==="page")return jsxRuntimeExports.jsxs("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"page",...a,className:"pod-sign-in grid min-h-[100dvh] w-full bg-background text-foreground md:grid-cols-2",children:[h?jsxRuntimeExports.jsx("aside",{"data-pod-sign-in":"intro",className:"hidden flex-col justify-center gap-6 bg-[hsl(var(--sunken))] px-12 py-10 md:flex",children:h}):null,jsxRuntimeExports.jsx("div",{className:cn("flex min-w-0 items-center justify-center px-4 py-8",h?"":"md:col-span-2"),children:jsxRuntimeExports.jsx("div",{className:cn(bodyClass,"min-h-[520px]"),children:n})})]});const p=jsxRuntimeExports.jsxs("div",{ref:l,role:d?"dialog":"region","aria-modal":d?!0:void 0,"aria-label":e,tabIndex:-1,"data-pod-sign-in-frame":"dialog",...a,className:cn("pod-sign-in relative flex min-h-[min(440px,90dvh)] max-h-[90dvh] w-[min(480px,calc(100vw-2rem))] flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground shadow-lg focus:outline-none motion-safe:animate-in motion-safe:fade-in-0"),children:[d&&s&&o?jsxRuntimeExports.jsx("button",{type:"button","aria-label":o,className:"absolute right-2 top-2 flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",onClick:s,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null,jsxRuntimeExports.jsx("div",{className:cn(bodyClass,"mx-auto"),children:n})]});return d?jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center bg-background/80 p-4",children:p}):jsxRuntimeExports.jsx("div",{className:"flex w-full items-center justify-center p-4",children:p})}function StorageBadge({kind:r,label:e}){const t=r==="cloud"?Cloud:Laptop;return jsxRuntimeExports.jsx("span",{role:"img","aria-label":e,title:e,"data-storage-kind":r,className:"flex h-[18px] w-[18px] items-center justify-center rounded-full border border-background bg-card text-foreground",children:jsxRuntimeExports.jsx(t,{"aria-hidden":"true",className:"h-3 w-3"})})}const zhCN={restoring:"正在恢复登录…",enterApp:"进入 {app}",reauthenticate:"重新登录",useAnother:"使用其他账号",expiredLine:"登录已过期,需要重新确认",chooseTitle:"登录",chooseLead:"用你的 WebID 账号登录,数据保存在你自己的 Pod 里",useXpod:"使用 Xpod 账号登录",useOtherSolid:"使用其他 Solid 账号",customLabel:"账号服务地址或 WebID",customPlaceholder:"https://example.com/",customSubmit:"继续",noAccount:"没有账号?",register:"注册 Xpod",noticeDetailsToggle:"详情",noticeCopy:"复制",noticeCopied:"已复制",whatIsPod:"什么是 Pod?",whatIsPodBody:"Pod 是保存你数据的个人空间。",whatIsWebId:"什么是 WebID?",whatIsWebIdBody:"WebID 是登录用的身份,它指向你的个人资料和 Pod。",signInWith:"使用 {service} 登录",select:"选择",selected:"已选择",choosePodTitle:"选择 Pod",choosePodLead:"选择要继续使用的 Pod",retry:"重试",goCreate:"去创建",refreshPage:"刷新页面",startAndEnter:"启动 Xpod 并进入",openXpod:"打开 Xpod",noticeUnreachable:"暂时连不上 Xpod,请稍后再试",noticeIncomplete:"登录没有完成,请再试一次",noticeNoWebId:"还没有 WebID",noticeCancelled:"登录已取消",noticeLocalStopped:"这台电脑上的 Xpod 没有运行",noticePending:"上次登录尚未结束",serviceLabel:"账号服务",signInTitle:"登录 {service}",returnToApp:"完成后回到 {app}",email:"邮箱",password:"密码",forgotPassword:"忘记密码?",rememberDevice:"在这台设备上保持登录",signIn:"登录",registerLink:"注册账号",registerTitle:"注册 {service}",username:"用户名",registerSubmit:"注册",haveAccount:"已有账号?登录",podElsewhereSummary:"想用你自己的独立部署存放 Pod?",podElsewhereBody:"注册后,可以在账号页的“存储”里把 Pod 建到你自己的独立部署上;它和当前账号服务是分开的,普通浏览器不会自动把 Pod 转到本机。",noWebIdTitle:"还没有 WebID",noWebIdLead:"新建一个 WebID 来登录 {app},数据存在它的 Pod 里",webIdName:"WebID 名称",noWebIdLocation:"存放在当前服务",createAndContinue:"创建并继续",chooseOtherLocation:"存到边缘设备(打开账号页)",consentTitle:"授权 {app}",unverifiedWarning:"未能验证这个应用的来源,请确认是你要使用的应用",chooseWebId:"用哪个 WebID 登录?",consentConsequence:"{app} 将以这个身份读写你的数据,之后可以在 Xpod 中收回。",requestDetails:"请求详情",scopes:"权限范围",clientId:"应用标识",webIdFull:"WebID",rememberChoice:"以后不再询问",manageAccount:"管理账号",switchAccount:"换一个账号",deny:"拒绝",allow:"允许",storageCloud:"数据存在 Xpod 云端",storageEdge:"数据存在边缘设备上",hostedStorage:"账号服务托管",independentStorage:"独立部署",identityAddress:"WebID(身份地址)",storageAddress:"Pod(存储地址)",showAddresses:"查看地址",webIdSectionTitle:"WebID",webIdEmpty:"还没有 WebID。新建一个,用它登录应用。",createWebId:"新建 WebID",linkExistingWebId:"关联已有 WebID",podOnDevice:"Pod 在 {device}",authorizedApps:"已授权 {count} 个应用",createStepName:"名称",createStepLocation:"存放在",createNameHint:"WebID 地址",changeDevice:"更换 ›",cannotChangeLater:"创建后不能直接更换,以后要换请使用迁移",createPod:"创建 WebID 和 Pod",startDeviceXpod:"启动这台设备上的 Xpod",creatingNote:"关闭页面不会中断创建",cancel:"取消",devicePickerTitle:"选择存放设备",addDevice:"+ 添加设备",deviceSectionTitle:"设备",deviceStatusOk:"正常",deviceStatusUnreachable:"⚠ 其他设备访问不到",deviceStatusStopped:"Xpod 已停止",deviceStatusOffline:"离线",deviceCloud:"Xpod 云端",deviceEdge:"边缘",podCount:"{count} 个 Pod",networkAction:"网络",fixAction:"处理",collapseAction:"收起",webIdSectionHint:"登录应用时使用的身份,数据存在它的 Pod 里",deviceSectionHint:"Pod 可以存放的地方,网络设置跟着设备走",credentialSectionHint:"让脚本或服务以某个 WebID 直接访问 Pod",startAction:"启动",networkTitle:"网络访问",probeLocal:"这台电脑",probeLan:"局域网",probeWan:"其他网络",probeIdle:"未检测",probeChecking:"检测中",probeOk:"可以访问",probeFailed:"不通",tunnelTitle:"选择隧道",enableAndRecheck:"开启并重新检测",enableAndCheck:"开启并检测",recheck:"重新检测",skipForNow:"跳过,稍后设置",reachableVia:"通过 {tunnel} 可以访问",networkFootnote:"只影响其他设备;这台电脑上照常可用",addDeviceTitle:"添加设备",stepInstall:"安装并登录",stepNetwork:"检查网络",stepDone:"完成",joinThisComputer:"把这台电脑加入",installOnOther:"在那台设备上安装 Xpod 边缘并登录本账号",waitingForDevice:"正在等待新设备上线,登录后这里会自动继续",deviceOnline:"已上线",finish:"完成",useThisDevice:"用这台设备",credentialSectionTitle:"密钥",credentialEmpty:"还没有密钥。",createCredential:"新建密钥",revokeCredential:"删除",resumeTitle:"{app} 正在等你完成授权",resumeWaiting:"在下面新建一个 WebID,完成后就能回去授权",resumeReady:"WebID 已就绪,可以回去授权了",resumeCancel:"取消授权",resumeContinue:"继续授权 {app}",close:"关闭"},en={restoring:"Restoring your sign-in…",enterApp:"Open {app}",reauthenticate:"Sign in again",useAnother:"Use another account",expiredLine:"Your sign-in expired. Please confirm again.",chooseTitle:"Sign in",chooseLead:"Sign in with your WebID account. Your data stays in your own Pod.",useXpod:"Sign in with Xpod",useOtherSolid:"Use another Solid account",customLabel:"Sign-in service address or WebID",customPlaceholder:"https://example.com/",customSubmit:"Continue",noAccount:"No account?",register:"Register for Xpod",noticeDetailsToggle:"Details",noticeCopy:"Copy",noticeCopied:"Copied",whatIsPod:"What is a Pod?",whatIsPodBody:"A Pod is a personal space that holds your data.",whatIsWebId:"What is a WebID?",whatIsWebIdBody:"A WebID is the identity you sign in with. It points to your profile and your Pod.",signInWith:"Sign in with {service}",select:"Select",selected:"Selected",choosePodTitle:"Choose a Pod",choosePodLead:"Choose the Pod to continue with",retry:"Retry",goCreate:"Create one",refreshPage:"Refresh page",startAndEnter:"Start Xpod and open",openXpod:"Open Xpod",noticeUnreachable:"Cannot reach Xpod right now. Please try again later.",noticeIncomplete:"Sign-in did not finish. Please try again.",noticeNoWebId:"No WebID yet",noticeCancelled:"Sign-in cancelled",noticeLocalStopped:"Xpod is not running on this computer",noticePending:"The previous sign-in has not finished",serviceLabel:"Sign-in service",signInTitle:"Sign in to {service}",returnToApp:"You will return to {app}",email:"Email",password:"Password",forgotPassword:"Forgot password?",rememberDevice:"Keep me signed in on this device",signIn:"Sign in",registerLink:"Register",registerTitle:"Register for {service}",username:"Username",registerSubmit:"Register",haveAccount:"Already have an account? Sign in",podElsewhereSummary:"Want it on your own standalone deployment?",podElsewhereBody:"After registering, create the Pod on your own standalone deployment under Storage on the account page; it is separate from this account service.",noWebIdTitle:"No WebID yet",noWebIdLead:"Create a WebID to sign in to {app}. Your data lives in its Pod.",webIdName:"WebID name",noWebIdLocation:"Stored on the current service",createAndContinue:"Create and continue",chooseOtherLocation:"Store on an edge device (open account page)",consentTitle:"Authorize {app}",unverifiedWarning:"We could not verify this application. Make sure it is the one you meant to use.",chooseWebId:"Which WebID do you sign in with?",consentConsequence:"{app} will read and write your data as this identity. You can revoke it later in Xpod.",requestDetails:"Request details",scopes:"Permissions",clientId:"Application ID",webIdFull:"WebID",rememberChoice:"Do not ask again",manageAccount:"Manage account",switchAccount:"Switch account",deny:"Deny",allow:"Allow",storageCloud:"Data is stored on Xpod Cloud",storageEdge:"Data is stored on an edge device",hostedStorage:"Hosted by account service",independentStorage:"Independent deployment",identityAddress:"WebID (identity address)",storageAddress:"Pod (storage address)",showAddresses:"View addresses",webIdSectionTitle:"WebID",webIdEmpty:"No WebID yet. Create one to sign in to applications.",createWebId:"New WebID",linkExistingWebId:"Link an existing WebID",podOnDevice:"Pod on {device}",authorizedApps:"{count} authorized apps",createStepName:"Name",createStepLocation:"Store on",createNameHint:"WebID address",changeDevice:"Change ›",cannotChangeLater:"It cannot be changed directly after creation. Use migration later.",createPod:"Create WebID and Pod",startDeviceXpod:"Start Xpod on this device",creatingNote:"Closing this page will not interrupt creation",cancel:"Cancel",devicePickerTitle:"Choose where to store",addDevice:"+ Add device",deviceSectionTitle:"Devices",deviceStatusOk:"Healthy",deviceStatusUnreachable:"⚠ Not reachable from other devices",deviceStatusStopped:"Xpod stopped",deviceStatusOffline:"Offline",deviceCloud:"Xpod Cloud",deviceEdge:"Edge",podCount:"{count} Pods",networkAction:"Network",fixAction:"Fix",collapseAction:"Collapse",webIdSectionHint:"The identity you sign in to apps with. Your data lives in its Pod.",deviceSectionHint:"Places a Pod can live. Network settings follow the device.",credentialSectionHint:"Let a script or service reach a Pod directly as one WebID.",startAction:"Start",networkTitle:"Network access",probeLocal:"This computer",probeLan:"Local network",probeWan:"Other networks",probeIdle:"Not checked",probeChecking:"Checking",probeOk:"Reachable",probeFailed:"Unreachable",tunnelTitle:"Choose a tunnel",enableAndRecheck:"Enable and recheck",enableAndCheck:"Enable and check",recheck:"Recheck",skipForNow:"Skip, set up later",reachableVia:"Reachable through {tunnel}",networkFootnote:"Only affects other devices. This computer keeps working as usual.",addDeviceTitle:"Add a device",stepInstall:"Install and sign in",stepNetwork:"Check network",stepDone:"Done",joinThisComputer:"Add this computer",installOnOther:"Install Xpod Edge on that device and sign in to this account",waitingForDevice:"Waiting for the new device to come online. This continues automatically after sign-in.",deviceOnline:"Online",finish:"Done",useThisDevice:"Use this device",credentialSectionTitle:"Credentials",credentialEmpty:"No credentials yet.",createCredential:"New credential",revokeCredential:"Delete",resumeTitle:"{app} is waiting for you to finish authorizing",resumeWaiting:"Create a WebID below, then you can go back and authorize",resumeReady:"Your WebID is ready. You can go back and authorize.",resumeCancel:"Cancel authorization",resumeContinue:"Continue authorizing {app}",close:"Close"},podSignInCopy={"zh-CN":zhCN,en};function resolvePodSignInCopy(r="zh-CN",e){return{...podSignInCopy[r],...e}}function formatCopy(r,e){return r.replace(/\{(\w+)\}/g,(t,n)=>{const i=e[n];return i===void 0?t:String(i)})}function IdpChrome({serviceName:r,serviceHost:e,icon:t,serviceLabel:n,locale:i}){const s=n??resolvePodSignInCopy(i).serviceLabel;return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"idp-chrome",className:"flex min-h-14 shrink-0 items-center gap-3 border-b border-border bg-[hsl(var(--sunken))] px-6 py-2 text-[13px] text-foreground min-[400px]:px-8",children:[jsxRuntimeExports.jsx("span",{className:"flex shrink-0 items-center justify-center",children:t??jsxRuntimeExports.jsx(XpodMark,{size:24})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 max-w-[50%] shrink-0 truncate font-medium",children:[r," · ",s]}),e?jsxRuntimeExports.jsx("span",{className:"ml-auto truncate font-mono text-xs text-muted-foreground",children:e}):null]})}const primaryButtonClass="h-auto min-h-12 w-full whitespace-normal break-normal rounded-lg py-2 text-base font-medium leading-snug",outlineButtonClass=primaryButtonClass,textButtonClass="h-9 rounded-lg px-2 text-sm font-medium",fieldClass="h-12 w-full rounded-lg border border-input bg-card px-4 text-base text-foreground placeholder:text-muted-foreground disabled:opacity-60";function Spinner({className:r}){return jsxRuntimeExports.jsx(LoaderCircle$1,{"aria-hidden":"true",className:cn("h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none",r)})}function ActionButton({busy:r=!1,children:e,disabled:t,...n}){return jsxRuntimeExports.jsxs(Button,{type:"button",...n,disabled:t||r,"aria-busy":r||void 0,children:[r?jsxRuntimeExports.jsx(Spinner,{className:"mr-2"}):null,e]})}function SourceMark({icon:r,name:e}){return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"source",className:"flex h-6 items-center gap-2 text-[13px] text-muted-foreground",children:[r?jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"flex h-6 w-6 shrink-0 items-center justify-center overflow-hidden rounded-md",children:r}):null,jsxRuntimeExports.jsx("span",{className:"truncate",children:e})]})}function PodAvatar({name:r,avatarUrl:e,storage:t,size:n=56}){return jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0",style:{width:n,height:n},"data-pod-sign-in":"avatar",children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-full w-full rounded-full","aria-hidden":"true",children:[e?jsxRuntimeExports.jsx(AvatarImage,{src:e,alt:""}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"text-base",children:Array.from(r.trim())[0]?.toUpperCase()??"?"})]}),t?jsxRuntimeExports.jsx("span",{className:"absolute -bottom-0.5 -right-0.5",children:jsxRuntimeExports.jsx(StorageBadge,{kind:t.kind,label:t.label})}):null]})}function Field(r){return jsxRuntimeExports.jsx(FormField,{...r,"data-pod-sign-in":"field"})}function Disclosure({summary:r,children:e,className:t}){return jsxRuntimeExports.jsxs("details",{className:cn("text-[13px] text-muted-foreground",t),children:[jsxRuntimeExports.jsx("summary",{className:"cursor-pointer select-none rounded py-1 text-[13px] font-medium text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",children:r}),jsxRuntimeExports.jsx("div",{className:"pt-1 leading-5",children:e})]})}function CheckboxRow({checked:r,onChange:e,label:t,disabled:n}){return jsxRuntimeExports.jsxs("label",{className:"flex min-h-9 cursor-pointer items-center gap-2 text-sm text-foreground",children:[jsxRuntimeExports.jsx(Checkbox,{checked:r,disabled:n,onChange:i=>e(i.target.checked)}),t]})}function usePastDelay(r){const[e,t]=reactExports.useState(!1);return reactExports.useEffect(()=>{const n=setTimeout(()=>t(!0),r);return()=>clearTimeout(n)},[r]),e}function ScreenLayout({chrome:r,children:e,actions:t,onSubmit:n,mainClassName:i,...s}){const o=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[r,jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"main",className:cn("flex min-h-0 flex-1 flex-col gap-7 overflow-y-auto px-6 pb-3 pt-7 min-[400px]:px-8 min-[400px]:pt-8",i),children:e}),t?jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"actions",className:"flex shrink-0 flex-col gap-4 px-6 pb-7 pt-5 min-[400px]:px-8 min-[400px]:pb-8",children:t}):null]}),a="flex min-h-0 flex-1 flex-col";return n?jsxRuntimeExports.jsx("form",{...s,onSubmit:n,className:a,noValidate:!0,children:o}):jsxRuntimeExports.jsx("div",{...s,className:a,children:o})}function resolveIdpCopy({locale:r,copy:e}){return resolvePodSignInCopy(r,e)}function IdpFrameHeader({serviceName:r="Xpod",serviceHost:e,serviceIcon:t,locale:n,copy:i}){return jsxRuntimeExports.jsx(IdpChrome,{serviceName:r,serviceHost:e,icon:t,locale:n,serviceLabel:i?.serviceLabel})}const inputClass=fieldClass;function TextAction({href:r,onClick:e,disabled:t,className:n,children:i}){const s=cn(textButtonClass,"inline-flex shrink-0 items-center justify-center text-primary hover:underline",n);return r&&!t?jsxRuntimeExports.jsx("a",{href:r,className:s,children:i}):jsxRuntimeExports.jsx("button",{type:"button",className:s,disabled:t,onClick:e,children:i})}function IdpSignInView(r){const{serviceName:e,returnToAppName:t,error:n,fieldErrors:i,pending:s=!1,remember:o,defaultEmail:a="",defaultPassword:d="",onFieldChange:l,onRememberChange:h,onSubmit:p,onForgot:g,forgotHref:S,onRegister:y,registerHref:v,onUseOtherSolid:E}=r,w=resolveIdpCopy(r),[T,I]=reactExports.useState(a),[C,O]=reactExports.useState(d),P=D=>{D.preventDefault(),s||p({email:T.trim(),password:C})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-sign-in",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...r}),onSubmit:P,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[n?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:n}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:s,children:w.signIn}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[y||v?jsxRuntimeExports.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-1 gap-y-0",children:[jsxRuntimeExports.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:w.noAccount}),jsxRuntimeExports.jsx(TextAction,{href:v,disabled:s,onClick:y,children:w.registerLink})]}):jsxRuntimeExports.jsx("span",{}),E?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"text-primary hover:underline"),disabled:s,onClick:E,children:w.useOtherSolid}):null]})]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(w.signInTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(w.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"fields",className:"flex flex-col gap-5",children:[jsxRuntimeExports.jsx(Field,{label:w.email,error:i?.email,children:D=>jsxRuntimeExports.jsx(EmailInput,{...D,name:"email",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:T,disabled:s,onChange:Y=>{I(Y.target.value),l?.("email",Y.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:w.password,error:i?.password,labelAside:g||S?jsxRuntimeExports.jsx(TextAction,{className:"min-h-7 text-[13px]",href:S,onClick:g,children:w.forgotPassword}):void 0,children:D=>jsxRuntimeExports.jsx(Input,{...D,name:"password",type:"password",autoComplete:"current-password",className:inputClass,value:C,disabled:s,onChange:Y=>{O(Y.target.value),l?.("password",Y.target.value)}})}),h?jsxRuntimeExports.jsx(CheckboxRow,{checked:o,onChange:h,label:w.rememberDevice,disabled:s}):null]})]})}function IdpRegisterView(r){const{serviceName:e,returnToAppName:t,usernamePreview:n,requireUsername:i,fieldErrors:s,error:o,pending:a=!1,defaultEmail:d="",defaultPassword:l="",defaultUsername:h="",onFieldChange:p,onSubmit:g,onSignIn:S}=r,y=resolveIdpCopy(r),[v,E]=reactExports.useState(h),[w,T]=reactExports.useState(d),[I,C]=reactExports.useState(l),O=P=>{P.preventDefault(),!a&&g({...i?{username:v.trim()}:{},email:w.trim(),password:I})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-register",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...r}),onSubmit:O,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[o?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:o}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:a,children:y.registerSubmit}),S?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"self-center text-primary hover:underline"),disabled:a,onClick:S,children:y.haveAccount}):null]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(y.registerTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(y.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-5",children:[i?jsxRuntimeExports.jsx(Field,{label:y.username,error:s?.username,hint:n?jsxRuntimeExports.jsx("span",{role:"status",className:"font-mono text-xs",children:n}):void 0,children:P=>jsxRuntimeExports.jsx(Input,{...P,name:"username",type:"text",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:v,disabled:a,onChange:D=>{E(D.target.value),p?.("username",D.target.value)}})}):null,jsxRuntimeExports.jsx(Field,{label:y.email,error:s?.email,children:P=>jsxRuntimeExports.jsx(EmailInput,{...P,name:"email",autoComplete:"email",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:w,disabled:a,onChange:D=>{T(D.target.value),p?.("email",D.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:y.password,error:s?.password,children:P=>jsxRuntimeExports.jsx(Input,{...P,name:"password",type:"password",autoComplete:"new-password",className:inputClass,value:I,disabled:a,onChange:D=>{C(D.target.value),p?.("password",D.target.value)}})}),jsxRuntimeExports.jsx(Disclosure,{summary:y.podElsewhereSummary,children:y.podElsewhereBody})]})]})}const __iconNode$1=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],CircleAlert=createLucideIcon$1("circle-alert",__iconNode$1);const __iconNode=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle=createLucideIcon$1("loader-circle",__iconNode);function WebAccountLayout({title:r,description:e,children:t,host:n="document",bare:i=!1,intro:s,serviceIcon:o}){const a=reactExports.useId(),d=n==="window",l=d?"window":"page";return jsxRuntimeExports.jsx("main",{"data-testid":"web-account-page",className:d?"h-dvh w-full overflow-hidden":void 0,children:jsxRuntimeExports.jsx(PodSignInFrame,{presentation:d?"window":"page",ariaLabel:r,appIntro:s,dataAttributes:{"data-web-account-layout":l,"data-web-account-host":d?"window":"document"},children:jsxRuntimeExports.jsx("div",{"data-testid":"web-account-panel","data-web-account-layout":l,"data-web-account-host":d?"window":"document",className:"flex min-h-0 min-w-0 flex-1 flex-col",children:i?t:jsxRuntimeExports.jsxs(ScreenLayout,{chrome:jsxRuntimeExports.jsx(IdpChrome,{serviceName:"Xpod",serviceHost:window.location.host,icon:o}),children:[jsxRuntimeExports.jsxs("header",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{id:a,className:"text-[17px] font-semibold text-foreground",children:r}),e?jsxRuntimeExports.jsx("p",{className:"text-sm leading-[22px] text-muted-foreground",children:e}):null]}),t]})})})})}const introCopy={"zh-CN":{name:"Xpod 账号服务",proposition:"一个账号,管理你的 WebID 和它背后的 Pod。",points:[{title:"WebID 是你的身份",detail:"登录应用时使用它;数据存在你自己的 Pod 里。"},{title:"Pod 存在哪里由你决定",detail:"Xpod 云端或你自己的设备,创建后可以在这里查看。"},{title:"密钥按需签发",detail:"为脚本或服务单独创建凭据,不再需要就撤销。"}]},en:{name:"Xpod accounts",proposition:"One account for your WebID and the Pod behind it.",points:[{title:"Your WebID is your identity",detail:"Apps sign you in with it; your data stays in your own Pod."},{title:"You choose where the Pod lives",detail:"Xpod cloud or your own device, reviewable here after creation."},{title:"Credentials on demand",detail:"Issue a key per script or service, and revoke it when it is done."}]}};function XpodAccountServiceIntro({serviceHost:r,locale:e="zh-CN"}){const t=introCopy[e];return jsxRuntimeExports.jsxs("div",{"data-testid":"web-account-introduction",className:"flex max-w-[460px] flex-col gap-7",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(XpodMark,{size:44}),jsxRuntimeExports.jsx("span",{className:"text-[22px] font-semibold leading-none text-foreground",children:t.name})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"m-0 text-[28px] font-semibold leading-[38px] text-foreground",children:t.proposition}),r?jsxRuntimeExports.jsx("p",{className:"font-mono text-xs text-muted-foreground",children:r}):null]}),jsxRuntimeExports.jsx("ul",{className:"m-0 flex list-none flex-col gap-4 p-0",children:t.points.map(n=>jsxRuntimeExports.jsxs("li",{className:"flex gap-3",children:[jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"mt-2 h-2 w-2 shrink-0 rounded-full bg-primary"}),jsxRuntimeExports.jsxs("span",{className:"flex flex-col gap-0.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[15px] font-semibold text-foreground",children:n.title}),jsxRuntimeExports.jsx("span",{className:"text-sm leading-[22px] text-muted-foreground",children:n.detail})]})]},n.title))})]})}function parseIdentity(r){if(!r||typeof r!="object")throw new Error("Missing deployment identity");const e=r;if(e.edition!=="cloud"&&e.edition!=="local"||typeof e.managed!="boolean")throw new Error("Invalid deployment identity");let t;if(e.edition==="local"&&e.managed&&typeof e.oidcIssuer=="string"){const i=new URL(e.oidcIssuer);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||i.search||i.hash)throw new Error("Invalid account service");t=i.href.replace(/\/$/u,"")}let n;if(typeof e.publicUrl=="string"){const i=new URL(e.publicUrl);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||i.search||i.hash)throw new Error("Invalid public service address");n=i.href}return{edition:e.edition,managed:e.managed,oidcIssuer:t,publicUrl:n}}function XpodDeploymentIdentity({renderLogo:r,className:e}={}){const[t,n]=reactExports.useState();reactExports.useEffect(()=>{const o=new AbortController;return(async()=>{try{const a=await fetch("/api/service-info",{headers:{accept:"application/json"},cache:"no-store",signal:o.signal});if(!a.ok)throw new Error("Deployment identity unavailable");const d=parseIdentity(await a.json());o.signal.aborted||n(d)}catch{o.signal.aborted||n(null)}})(),()=>o.abort()},[]);const i=t?t.edition==="cloud"?"云端":t.managed?"托管部署":"独立部署":t===null?"部署信息暂不可用":"正在识别部署…",s=r?r(i):jsxRuntimeExports.jsxs("span",{"data-testid":"xpod-deployment-logo",className:"inline-flex flex-col items-center gap-0.5",children:[jsxRuntimeExports.jsx(XpodMark,{size:24}),jsxRuntimeExports.jsx("span",{className:"text-[8px] font-medium leading-none text-primary",children:t?i:t===null?"未知":"…"}),t?null:jsxRuntimeExports.jsx("span",{className:"sr-only",children:i})]});return jsxRuntimeExports.jsx("div",{"data-testid":"xpod-deployment-identity",className:e,children:jsxRuntimeExports.jsx(BrandInfo,{logo:s,infoLabel:"部署详情",info:jsxRuntimeExports.jsxs("div",{className:"space-y-2 leading-relaxed",children:[jsxRuntimeExports.jsx("p",{className:"font-semibold",children:"部署详情"}),t?jsxRuntimeExports.jsxs("p",{children:["部署类型:",t.edition==="cloud"?"Cloud":t.managed?"Local · 云端托管":"Local · 独立部署"]}):jsxRuntimeExports.jsx("p",{children:i}),jsxRuntimeExports.jsxs("p",{children:["当前访问:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:window.location.origin})]}),t?jsxRuntimeExports.jsxs("p",{children:[t.edition==="local"?"节点地址":"服务地址",":",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.publicUrl??(t.managed?"尚未分配":"尚未配置")})]}):null,t?.oidcIssuer&&t.oidcIssuer!==window.location.origin?jsxRuntimeExports.jsxs("p",{children:["账号服务:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.oidcIssuer})]}):null]})})})}function XpodAuthSurface(r){const e=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(e==="window"),jsxRuntimeExports.jsx(AuthSurface,{...r,presentation:"compact",host:e})}function XpodSignInFrame({ariaLabel:r,children:e}){const t=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(t==="window"),jsxRuntimeExports.jsx(PodSignInFrame,{presentation:t==="window"?"window":"page",ariaLabel:r,children:e})}function XpodAccountPageSurface({title:r,children:e,bare:t=!1,intro:n,presentation:i="compact"}){const s=getXpodAuthSurfaceHost(),o=i==="compact";return useXpodAuthWindowSurface(s==="window",o?"account":"workspace"),jsxRuntimeExports.jsx(WebAccountLayout,{title:r,host:o?s:"document",bare:t,intro:n??jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),children:e})}function credentialViewCopy(r){return{email:r.emailLabel,password:r.passwordLabel,username:r.usernameLabel,signIn:r.loginAction,registerSubmit:r.registerAction,rememberDevice:"记住账号"}}function XpodBlockingAccountCredentialsSurface(r){const e=getXpodAuthSurfaceHost(),t=r.mode!=="register";useXpodAuthWindowSurface(e==="window",t?"account":"workspace");const{mode:n,values:i,onChange:s,onSubmit:o,onFieldChange:a,onModeChange:d,rememberAccount:l=!0,onRememberAccountChange:h,pending:p=!1,errors:g,copy:S,surfaceTitle:y,footer:v,onForgot:E,onRegister:w,forgotHref:T,registerHref:I}=r,C={serviceName:"Xpod",serviceHost:window.location.host,serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),copy:credentialViewCopy(S)},O=(P,D)=>{s({...i,[P]:D}),a?.(P,D)};return jsxRuntimeExports.jsxs(WebAccountLayout,{title:y,host:t?e:"document",bare:!0,intro:jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),children:[n==="register"?jsxRuntimeExports.jsx(IdpRegisterView,{...C,requireUsername:!1,pending:p,defaultEmail:i.email,defaultPassword:i.password,error:g?.form,fieldErrors:{email:g?.email,password:g?.password},onFieldChange:O,onSubmit:P=>{o({...i,...P})},onSignIn:d?()=>d("login"):void 0}):jsxRuntimeExports.jsx(IdpSignInView,{...C,pending:p,remember:l,defaultEmail:i.email,defaultPassword:i.password,error:g?.form,fieldErrors:{email:g?.email,password:g?.password},onFieldChange:O,onRememberChange:h,onSubmit:P=>{o({...i,...P})},onForgot:E,forgotHref:T,registerHref:I,onRegister:w??(d?()=>d("register"):void 0)}),v?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:v}):null]})}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(r=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(r));for(let n=0;n<r;n++)e+=urlAlphabet[t[n]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<r;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=r=>typeof r=="object"&&r!==null&&typeof r.value=="string",hasTermValue=r=>typeof r=="object"&&r!==null&&typeof r.term=="object"&&r.term!==null&&typeof r.term?.value=="string",resolveTermIri=r=>{if(typeof r=="string")return r;if(hasStringValue$2(r))return r.value;if(hasTermValue(r))return r.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is$1(r,e){if(!r||typeof r!="object")return!1;if(r instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=r.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:n,query:i}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:n,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,n,i=!1){this[SubqueryConfig]={sql:e,selection:t,alias:n,isWith:i}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const i=(is$1(e,Subquery)?e[SubqueryConfig].selection:is$1(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is$1(i,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;const s=i.clone();return s.isSelectionField=!0,s}if(is$1(i,SQL)){if(this.config.sqlBehavior==="sql")return i;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is$1(i,Column)?this.config.alias?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(i.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):i:typeof i!="object"||i===null?i:new Proxy(i,new SelectionProxyHandler(this.config))}}function orderSelectedFields(r,e){return Object.entries(r).reduce((t,[n,i])=>{if(typeof n!="string")return t;const s=e?[...e,n]:[n];return is$1(i,Column)||is$1(i,SQL)||is$1(i,SQL.Aliased)?t.push({path:s,field:i}):is$1(i,Table)?t.push(...orderSelectedFields(i[Table.Symbol.Columns],s)):t.push(...orderSelectedFields(i,s)),t},[])}function applyMixins(r,e){for(const t of e)for(const n of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(r.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n)||Object.create(null))}function getTableLikeName(r){return is$1(r,Subquery)?r[SubqueryConfig].alias:is$1(r,View)?r[ViewBaseConfig].name:is$1(r,SQL)?void 0:r[Table.Symbol.IsAlias]?r[Table.Symbol.Name]:r[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,n){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=n}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(r,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:n,session:i,dialect:s,withList:o,distinct:a}){super(),this.config={withList:o,table:e,fields:{...t},distinct:a},this.isPartialSelect=n,this.session=i,this.dialect=s,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,n)=>{const i=this.tableName,s=getTableLikeName(t);if(typeof s=="string"&&this.config.joins?.some(o=>o.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i=="string"&&(this.config.fields={[i]:this.config.fields}),typeof s=="string"&&!is$1(t,SQL))){const o=is$1(t,Subquery)?t[SubqueryConfig].selection:is$1(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[s]=o}if(typeof n=="function"&&(n=n(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:t,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:n,dialect:i,joinsNotNullableMap:s}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const o=orderSelectedFields(n.fields),a=t.prepareQuery(i.sqlToQuery(this.getSQL()),o,e);return a.joinsNotNullableMap=s,a})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(r){return typeof r=="object"&&r!==null&&"getSQL"in r&&typeof r.getSQL=="function"}function mergeQueries(r){const e={sql:"",params:[]};for(const t of r)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,t){const n=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:i,escapeParam:s,prepareTyping:o,inlineParams:a,paramStartIndex:d}=n;return mergeQueries(e.map(l=>{if(is$1(l,StringChunk))return{sql:l.value.join(""),params:[]};if(is$1(l,Name))return{sql:i(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){const h=[new StringChunk("(")];for(const[p,g]of l.entries())h.push(g),p<l.length-1&&h.push(new StringChunk(", "));return h.push(new StringChunk(")")),this.buildQueryFromSourceParams(h,n)}if(is$1(l,SQL))return this.buildQueryFromSourceParams(l.queryChunks,{...n,inlineParams:a||l.shouldInlineParams});if(is$1(l,Table)){const h=l[Table.Symbol.Schema],p=l[Table.Symbol.Name];return{sql:h===void 0?i(p):i(h)+"."+i(p),params:[]}}if(is$1(l,Column))return{sql:i(l.table[Table.Symbol.Name])+"."+i(l.name),params:[]};if(is$1(l,View)){const h=l[ViewBaseConfig].schema,p=l[ViewBaseConfig].name;return{sql:h===void 0?i(p):i(h)+"."+i(p),params:[]}}if(is$1(l,Param)){const h=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(is$1(h,SQL))return this.buildQueryFromSourceParams([h],n);if(a)return{sql:this.mapInlineParam(h,n),params:[]};let p;return o!==void 0&&(p=[o(l.encoder)]),{sql:s(d.value++,h),params:[h],typings:p}}return is$1(l,Placeholder)?{sql:s(d.value++,l),params:[l]}:is$1(l,SQL.Aliased)&&l.fieldAlias!==void 0?{sql:i(l.fieldAlias),params:[]}:is$1(l,Subquery)?l[SubqueryConfig].isWith?{sql:i(l[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),l[SubqueryConfig].sql,new StringChunk(") "),new Name(l[SubqueryConfig].alias)],n):isSQLWrapper(l)?this.buildQueryFromSourceParams([new StringChunk("("),l.getSQL(),new StringChunk(")")],n):is$1(l,Relation)?this.buildQueryFromSourceParams([l.sourceTable,new StringChunk("."),sql.identifier(l.fieldName)],n):a?{sql:this.mapInlineParam(l,n),params:[]}:{sql:s(d.value++,l),params:[l]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const n=e.toString();return t(n==="[object Object]"?JSON.stringify(e):n)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:r=>r},noopEncoder={mapToDriverValue:r=>r};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(r,...e){const t=[];(e.length>0||r.length>0&&r[0]!=="")&&t.push(new StringChunk(r[0]));for(const[n,i]of e.entries())t.push(i,new StringChunk(r[n+1]));return new SQL(t)}(function(r){function e(){return new SQL([])}r.empty=e;function t(d){return new SQL(d)}r.fromList=t;function n(d){return new SQL([new StringChunk(d)])}r.raw=n;function i(d,l){const h=[];for(const[p,g]of d.entries())p>0&&l!==void 0&&h.push(l),h.push(g);return new SQL(h)}r.join=i;function s(d){return new Name(d)}r.identifier=s;function o(d){return new Placeholder(d)}r.placeholder=o;function a(d,l){return new Param(d,l)}r.param=a})(sql||(sql={}));(function(r){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(n,i){this.sql=n,this.fieldAlias=i}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}r.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const i=e[Table.Symbol.Columns];if(!i)return i;const s={};return Object.keys(i).map(o=>{s[o]=new Proxy(i[o],new ColumnAliasProxyHandler(new Proxy(e,this)))}),s}const n=e[t];return is$1(n,Column)?new Proxy(n,new ColumnAliasProxyHandler(new Proxy(e,this))):n}}var _a$b;class ColumnBuilder{constructor(e,t,n={},i,s){this.name=e,this.dataType=t,this.options={...n},this._predicateUri=i,this.elementType=s??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,n={},i){this.name=e,this.dataType=t,this.options=n,this.tableName=i}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,n={}){super(e,"array",n),this.elementType=t}}function boolean$2(r,e={}){return new ColumnBuilder(r,"boolean",e)}function timestamp(r,e={}){return new ColumnBuilder(r,"datetime",e)}function json(r,e={}){return new ColumnBuilder(r,"json",e)}function object$1(r,e={}){return new ColumnBuilder(r,"object",e)}function uri(r,e={}){return new ColumnBuilder(r,"uri",e)}function id(r="id",e={}){const t=new PodStringColumn(r,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(r,e={}){return new ColumnBuilder(r,"string",e)}function integer$1(r,e={}){return new ColumnBuilder(r,"integer",e)}function date$3(r,e={}){return new ColumnBuilder(r,"datetime",e)}function text(r,e={}){return new ColumnBuilder(r,"string",e)}function real(r,e={}){return new ColumnBuilder(r,"integer",e)}function validateColumnOverride(r,e,t){const n=r.getPredicateUri?.()??r.options?.predicate,i=e.options?.predicate;if(n&&i&&n!==i)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${i}",子 schema 尝试改为 "${n}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(r,e){const t={};for(const[n,i]of Object.entries(r.columns))t[n]=i;for(const[n,i]of Object.entries(e)){const s=r.columns[n];if(s&&!(i instanceof PodColumnBase)){validateColumnOverride(i,s,n);const o=i;!o.getPredicateUri?.()&&!o.options?.predicate&&(o.options={...o.options,predicate:s.options?.predicate})}t[n]=i}return t}function renderDefaultIdTemplate(r,e){if(!/\{[^{}]+\}/.test(r))return r;if(/\{\s*id\s*\}/.test(r))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},n=resolveDate(t,e.now),i={yyyy:String(n.getUTCFullYear()),MM:String(n.getUTCMonth()+1).padStart(2,"0"),dd:String(n.getUTCDate()).padStart(2,"0")};return r.replace(/\{([^{}]+)\}/g,(s,o)=>{const a=o.trim();if(a==="key")return e.key;if(a==="yyyy")return i.yyyy;if(a==="MM")return i.MM;if(a==="dd")return i.dd;const d=resolveExpression(a,t,e);return d==null?"":String(d)})}function resolveDate(r,e=new Date){const t=r.createdAt??r.favoredAt??r.indexedAt??e,n=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(n.getTime())?n:e}function resolveExpression(r,e,t){const n=parseExpression(r);let i=resolveTemplatePath(n.path,e,t);for(const s of n.transforms)i=applyTransform(i,s,n.path,t);return n.selector?applyPathSelector(i,n.selector):i}function parseExpression(r){const e=r.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():r,[n,...i]=t.split("|").map(s=>s.trim()).filter(Boolean);return{path:n??r,transforms:i,selector:e?.[2]?.trim()}}function resolveTemplatePath(r,e,t){const n=r.split("."),i=n[0];return n.reduce((s,o,a)=>{if(typeof s=="string")return i?resolveResourceProperty(s,i,o,t):void 0;if(!(!s||typeof s!="object"))return i&&isResourceProperty(o)&&!((o==="id"||o==="key")&&o in s)?resolveResourceProperty(s,i,o,t):a>0&&o==="id"&&readRef(s)?extractResourceId(s,i??"",t):s[o]},e)}function isResourceProperty(r){return r==="id"||r==="key"||r==="doc"||r==="document"||r==="dir"||r==="owner"}function resolveResourceProperty(r,e,t,n){if(t==="id")return extractResourceId(r,e,n);const i=extractResourceId(r,e,n);if(i){if(t==="key"){const s=extractTemplateValuesForField(r,e,n);return s?.key??s?.id??deriveResourceKey(i)}if(t==="doc"||t==="document")return resourceDocument(i);if(t==="dir"||t==="owner")return deriveOwnerDir(i)}}function applyTransform(r,e,t,n){if(e==="slug")return slugifyValue(String(r??""));const i=extractResourceId(r,t,n);if(e==="resource")return i;if(e==="document")return i?resourceDocument(i):"";if(e==="owner")return i?deriveOwnerDir(i):"";const s=extractTemplateValuesForField(r,t,n);return e==="id"?s?.id??s?.key??i??"":s?.[e]??""}function extractResourceId(r,e,t){const n=readRef(r);if(!n)return null;const i=resolveLinkedResource(e,t);if(!i)return normalizePodDataResourceId$1(n);if(!isCompleteResourceId$1(n))return renderLinkedResourceId(i,n);const s=relativeSubjectFromRef$1(i,n);return normalizePodDataResourceId$1(s??n)}function extractTemplateValuesForField(r,e,t){const n=readRef(r);if(!n)return null;const i=resolveLinkedResource(e,t);if(!i)return null;const s=relativeSubjectFromRef$1(i,n)??(isCompleteResourceId$1(n)?null:renderLinkedResourceId(i,n));if(!s)return null;const o=resourceTemplate(i);return o?extractVarsFromTemplate(normalizePodDataResourceId$1(s),o):{id:normalizePodDataResourceId$1(s)}}function resolveLinkedResource(r,e){const t=e.links?.[r];if(t)return t;const n=e.resource?.columns?.[r];return n?.getLinkTable?.()??n?.options?.linkTable??null}function resourceTemplate(r){const e=r.getSubjectTemplate?.()??r.config?.subjectTemplate;if(e)return e;const t=r.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(r,e){const t=resourceTemplate(r);if(!t)return e;const n=r.columns?.id?.options?.defaultValue;return typeof n=="function"?String(n(e,{})):t.replace(/\{([^}]+)\}/g,(i,s)=>{const o=parseTemplateField(s);return o==="id"||o==="key"?e:""})}function readRef(r){if(typeof r=="string"&&r.length>0)return r;if(!r||typeof r!="object")return null;const e=r,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(r){return normalizeResourcePath$1(r.getResourcePath?.()??r.config?.base??"")}function relativeSubjectFromRef$1(r,e){const t=resourcePath(r);if(!t)return normalizePodDataResourceId$1(e);const n=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const i of n){const s=e.indexOf(i);if(s<0)continue;let o=e.slice(s+i.length);return o.startsWith("/")&&(o=o.slice(1)),o.length>0?o:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(r,e){let t=0;const n=new Map,i=[];let s=0;for(const a of e.matchAll(/\{([^}]+)\}/g)){i.push(escapeRegExp$1(e.slice(s,a.index)));const d=`var${t++}`;n.set(d,parseTemplateField(a[1]??"")),i.push(`(?<${d}>.+?)`),s=a.index+a[0].length}i.push(escapeRegExp$1(e.slice(s)));const o=i.join("");try{const a=r.match(new RegExp(`^${o}$`));if(!a?.groups)return null;const d={};for(const[l,h]of Object.entries(a.groups)){const p=n.get(l);!p||h===void 0||(d[p]=decodeURIComponent(h))}return d}catch{return null}}function parseTemplateField(r){const e=r.split("|").map(n=>n.trim()).filter(Boolean)[0]??r,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(r){return r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(r,e){const t=splitResourcePath(r);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const n=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!n)throw new Error(`Invalid id default path selector [${e}]`);const i=n[1]===""?0:normalizeSliceIndex(Number(n[1]),t.length),s=n[2]===""?t.length:normalizeSliceIndex(Number(n[2]),t.length);return t.slice(i,s).join("/")}function splitResourcePath(r){const e=readRef(r);if(!e)return null;const t=normalizePodDataResourceId$1(e),[n,i]=t.split("#"),s=(n??t).split("/").filter(Boolean);return i&&s.push(i),s}function normalizePodDataResourceId$1(r){const e=r.indexOf("#"),[t,n=""]=e>=0?[r.slice(0,e),r.slice(e)]:[r,""],i=t.indexOf("/.data/");return`${i>=0?t.slice(i+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${n}`}function normalizeResourcePath$1(r){return r.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(r){return/^https?:\/\//u.test(r)||r.startsWith("/")||r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(r)}function deriveOwnerDir(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#"),n=t>=0?e.slice(0,t):e,i=t>=0?e.slice(t+1):"",s=n.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(s?.[1])return s[1];if(n==="task/index.ttl"&&i&&i!=="this")return`task/${i}`;const o=n.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(o?.[1])return o[1];const a=n.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(a?.[1])return a[1];const d=n.split("/").filter(Boolean);return d.length>1?d.slice(0,-1).join("/"):n}function resourceDocument(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#");if(t>=0){const a=e.slice(t+1);if(a&&a!=="this"&&a!=="me"&&a!=="it")return a}const n=resourceDocument(e).replace(/\/+$/u,""),i=n.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(i?.[1])return i[1];const s=n.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const o=n.split("/").filter(Boolean);return o.length>0?o[o.length-1]:e}function slugifyValue(r){return r.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(r,e){return r<0?e+r:r}function normalizeSliceIndex(r,e){const t=r<0?e+r:r;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(r){const e=r.split("|").map(n=>n.trim()).filter(Boolean)[0]??r,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(r){return r.trim().replace(/^(\.\/)+/,"")}function podResourcePath(r){return normalizeResourcePath(r.getResourcePath?.()??r.config?.base??"")}function podResourceSubjectTemplate(r){return r.getSubjectTemplate?.()??r.config?.subjectTemplate}function podResourceIdDefaultTemplate(r){const e=r.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(r){const e=podResourcePath(r),t=normalizeResourcePath(r.getContainerPath?.()??r.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(r,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(r);return t?`${t}${e}`:e}function templateRelativeSubject(r,e){if((podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r))?.startsWith("#")&&!e.startsWith("#")){const n=e.indexOf("#");if(n>=0)return e.slice(n)}return e}function isBaseRelativeSubjectId$1(r){return!r||/^https?:\/\//.test(r)||r.startsWith("/")?!1:r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(r)}function isTemplateCompleteResourceId(r,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r);return t?extractTemplateValues(templateRelativeSubject(r,e),t)!==null:!1}function isResourceRelativeSubjectId(r,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(r,e)}function relativeSubjectFromRef(r,e){const t=podResourcePath(r);if(!t)return null;const n=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const i of n){const s=e.indexOf(i);if(s<0)continue;let o=e.slice(s+i.length);if(o.startsWith("/")&&(o=o.slice(1)),o.length>0)return o}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(r,e)?normalizeResourcePath(e):null}function extractTemplateValues(r,e){if(!e.includes("{"))return r===e?{}:null;let t=0;const n=new Map,i=[];let s=0;for(const a of e.matchAll(/\{([^}]+)\}/g)){i.push(escapeRegExp(e.slice(s,a.index)));const d=`var${t++}`;n.set(d,parseTemplateVariableField$1(a[1]??"")),i.push(`(?<${d}>.+?)`),s=a.index+a[0].length}i.push(escapeRegExp(e.slice(s)));const o=`^${i.join("")}$`;try{const a=r.match(new RegExp(o));if(!a?.groups)return null;const d={};for(const[l,h]of Object.entries(a.groups)){const p=n.get(l);if(!p||h===void 0)continue;const g=decodeURIComponent(h);if(p in d&&d[p]!==g)return null;d[p]=g}return d}catch{return null}}function escapeRegExp(r){return r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(r,e){if(!e)return null;const t=relativeSubjectFromRef(r,e);if(!t)return null;const n=qualifyFragmentResourceId(r,t),i=podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r),s=i?extractTemplateValues(templateRelativeSubject(r,n),i):{id:decodeURIComponent(n)};return s?{resourceId:decodeURIComponent(n),templateValues:s}:null}function extractPodResourceTemplateValue(r,e,t="id"){return parsePodResourceRef(r,e)?.templateValues[t]??null}function resolvePodBaseUrl(r){const e=r.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(r){if(!r||typeof r!="object")return null;const e=r,t=typeof e.getDialect=="function"?e.getDialect():null,n=readPodUrl(t);if(n)return resolvePodBaseUrl(n);const i=typeof e.getSession=="function"?e.getSession():e.session,s=readPodUrl(i);if(s)return resolvePodBaseUrl(s);const o=readWebId(i);return o&&o.includes("/profile/card#me")?resolvePodBaseUrl(o):null}function normalizePodDataResourceId(r){const e=r.indexOf("#"),[t,n=""]=e>=0?[r.slice(0,e),r.slice(e)]:[r,""],i=t.indexOf("/.data/");return`${i>=0?t.slice(i+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${n}`}function resolvePodResourceId(r,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(r,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(r,e),normalizePodDataResourceId(e);const n=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!n)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(n)||isTemplateCompleteResourceId(r,n))return normalizePodDataResourceId(n);const i=resolveDefaultResourceId(r,n,e);if(i)return normalizePodDataResourceId(i);const s=podResourceSubjectTemplate(r);return normalizePodDataResourceId(s?renderSubjectTemplateResourceId(s,n,e):n)}function buildPodResourceIri(r,e){const t=resolvePodBaseUrl(r);if(!t||/^https?:\/\//u.test(e))return e;const n=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(n.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(r,e,t){const n=resolveKnownTargetIri(t);if(n)return n;const i=resolvePodRootTargetPath(t);if(i)return buildPodResourceIri(r,i);const s=resolvePodResourceId(e,t),o=isResourceRelativeSubjectId(e,s)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(s)}`:e.resolveUri?.(s)??`/.data/${normalizePodDataResourceId(s)}`;return buildPodResourceIri(r,o)}function buildPodResourceIriForDatabase(r,e,t){const n=resolvePodBaseUrlFromDatabase(r);if(!n)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(n,e,t)}function resolvePodResourceIriForDatabase(r,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(r,e,t)}catch{return null}}function resolveKnownTargetIri(r){if(typeof r=="string")return/^https?:\/\//u.test(r)?r:null;const e=r["@id"]??r.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(r){if(typeof r=="string")return r.startsWith("/")?r:null;const e=typeof r.id=="string"?r.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(r){return/^https?:\/\//u.test(r)||r.startsWith("/")||r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(r)}function assertCompleteStringResourceId(r,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(r,e))return;const t=r.columns?.id?.options?.defaultValue!==void 0,n=podResourceSubjectTemplate(r);if(t||n)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(r,e,t){const n=r.columns?.id?.options?.defaultValue;if(n===void 0)return null;if(typeof n=="string")return renderDefaultIdTemplate(n,{key:e,row:t,resource:r});if(typeof n!="function")return String(n);const i=n;return i.length===0?String(i()):String(i(e,t))}function renderSubjectTemplateResourceId(r,e,t){const n=r.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(n,{key:encodeURIComponent(e),row:t})}function readPodUrl(r){if(!r||typeof r!="object")return null;const e=r,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(r){if(!r||typeof r!="object")return null;const e=r,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,n){this.initialized=!1;const i=n.type;if(!i)throw new Error("podTable requires a type (RDF class) via options.type");const s=n.typeIndex,o=s==="private"||s==="public",a=this.resolveBase(n.base,e);this.resourcePath=a.resourcePath,this.containerPath=a.containerPath;const d=this.resolveSubjectTemplate(n.subjectTemplate,a.resourcePath,a.containerPath,e);this.subjectTemplate=d.template,this.hasCustomSubjectTemplate=d.isCustom,this.resourceMode=n.resourceMode??(n.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=n.sparqlEndpoint,this.registerTypeIndexEnabled=o&&n.autoRegister!==!1,this.config={name:e,base:a.resourcePath,type:resolveTermIri(i),namespace:n.namespace,typeIndex:o?s:void 0,saiRegistryPath:n.saiRegistryPath,autoRegister:n.autoRegister,containerPath:a.containerPath,hooks:n.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(n.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let l=0;for(const h of Object.values(t))if(h.options.primaryKey&&l++,h.table=this,h.tableName=e,!h.options.predicate&&!h._virtualId&&!n.namespace)throw new Error(`Column "${h.name}" in table "${e}" is missing a predicate.`);if(l!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${l}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const n=t.replace(/\{id\}/g,e);return n.startsWith("#")?`${this.resourcePath}${n}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${n}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const n=this.normalizeBaseInput(e),i=this.normalizeResourcePath(n);if(i.endsWith("/")){const o=this.ensureTrailingSlash(i);return{resourcePath:o,containerPath:o}}const s=this.ensureTrailingSlash(this.deriveContainerPath(i));return{resourcePath:i,containerPath:s}}normalizeBaseInput(e){const t=e.trim(),n=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(n){const[,i,s]=n,o=i.toLowerCase(),a=s.trim();return o==="http"||o==="https"?`${o}://${a}`:a.startsWith("/")?a:`/${a}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const n=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return n.startsWith("/")?n:`/${n}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n===-1?"/":t.slice(0,n+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,n,i){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const n=(Array.isArray(e)?e:[e]).map(i=>resolveTermIri(i)).filter(i=>i&&i.length>0);return Array.from(new Set(n))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(r,e,t){const n={};for(const[i,s]of Object.entries(e)){if(s instanceof PodColumnBase){n[i]=s;continue}let o;switch(s.dataType){case"integer":o=new PodIntegerColumn(s.name,s.options);break;case"datetime":o=new PodDateTimeColumn(s.name,s.options);break;case"boolean":o=new PodBooleanColumn(s.name,s.options);break;case"json":o=new PodJsonColumn(s.name,s.options);break;case"object":o=new PodObjectColumn(s.name,s.options);break;case"array":{const d=s.elementType??s.options.baseType??"string";o=new PodArrayColumn(s.name,d,s.options);break}case"uri":o=new PodUriColumn(s.name,s.options);break;default:o=new PodStringColumn(s.name,s.options);break}const a=s.getPredicateUri?.();a&&o.predicate(a),n[i]=o}return new PodTable(r,n,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const n=mergeSchemaColumns(this,e),i=[this.type];return this.subClassOf&&i.push(...this.subClassOf),solidSchema(n,{...t,subClassOf:i})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(r,e){const t={};for(const[n,i]of Object.entries(r)){if(i instanceof PodColumnBase){t[n]=i;continue}let s;switch(i.dataType){case"integer":s=new PodIntegerColumn(i.name,i.options);break;case"datetime":s=new PodDateTimeColumn(i.name,i.options);break;case"boolean":s=new PodBooleanColumn(i.name,i.options);break;case"json":s=new PodJsonColumn(i.name,i.options);break;case"object":s=new PodObjectColumn(i.name,i.options);break;case"array":{const a=i.elementType??i.options.baseType??"string";s=new PodArrayColumn(i.name,a,i.options);break}case"uri":s=new PodUriColumn(i.name,i.options);break;default:s=new PodStringColumn(i.name,i.options);break}const o=i.getPredicateUri?.();o&&s.predicate(o),t[n]=s}return new SolidSchema(t,e)}function isSolidSchema(r){return r instanceof SolidSchema||r?.$kind==="SolidSchema"}const XSD$8="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(r,e){if(!r)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const i=e.getMapping()?.columns?.[r.name];if(i?.predicate)return i.predicate}if(typeof r.getPredicateUri=="function")return r.getPredicateUri();if(r._predicateUri)return r._predicateUri;if(r.predicate&&typeof r.predicate=="string")return r.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof r.getPredicate=="function")try{return r.getPredicate(t)}catch{}return r.options?.predicate?r.options.predicate:t?`${typeof t=="string"?t:t.uri}${r.name}`:(r.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",r),`http://example.org/${r.name}`)}function formatValue(r,e,t,n){return Array.isArray(r)?r.map(i=>formatSingleValue(i,e,t,n)):formatSingleValue(r,e,t,n)}function formatSingleValue(r,e,t,n){if(r==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const i=String(r);if(i.startsWith("<")&&i.endsWith(">")){const s=i.slice(1,-1);return t&&!t.isAbsoluteUri(s)?`<${t.resolveLink(s,e,n)}>`:i}return t?`<${t.resolveLink(i,e,n)}>`:i.startsWith("<")?i:`<${i}>`}return typeof r=="string"?!e&&(r.startsWith("http://")||r.startsWith("https://"))?`<${r}>`:`"${r.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof r=="number"?Number.isInteger(r)?String(r):`"${r}"^^<${XSD$8}decimal>`:typeof r=="boolean"?`"${r}"^^<${XSD$8}boolean>`:r instanceof Date?`"${r.toISOString()}"^^<${XSD$8}dateTime>`:`"${String(r)}"`}function resolveColumn(r,e){if(r&&typeof r=="object"&&r instanceof PodColumnBase)return r;if(r&&typeof r=="object"&&"name"in r){const t=r.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof r=="string"){const t=e.columns[r];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(r)}`)}function generateSubjectUri(r,e,t){const n=t.resolveSubject(e,r);if(!n)throw new Error("Failed to generate subject URI");return n}var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,n){super(),this.left=e,this.operator=t,this.right=n,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(r,e){return new BinaryExpression(r,"=",e)}function like(r,e){return new BinaryExpression(r,"LIKE",e)}function inArray(r,e){return new BinaryExpression(r,"IN",e)}function and(...r){return new LogicalExpression("AND",r.filter(Boolean))}function or(...r){return new LogicalExpression("OR",r.filter(Boolean))}function parseActivityStreamsMessage(r){const e=JSON.parse(r);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,n=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!n.ok)throw new Error(`SSE connection failed: ${n.status} ${n.statusText}`);if(!n.body)throw new Error("SSE response has no body");this.contentType=n.headers.get("content-type")||"",this._connected=!0,this.reader=n.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:n,value:i}=await this.reader.read();if(n){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const s=e.decode(i,{stream:!0});t+=s,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(n){n.name!=="AbortError"&&this.handleError(n)}}processTurtleBuffer(e){const t=e.split(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-D6dB-UNq.js","assets/createLucideIcon-DrgScGhc.js","assets/dashboard--DWjqkYt.js","assets/dashboard-Cb8CjRQr.css","assets/button-_rwfCMMH.js","assets/PodDeletionAuthorizationPanel-CzrI8Pgw.js","assets/account-session-BZ2ttIdq.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as createLucideIcon$1}from"./createLucideIcon-DrgScGhc.js";import{r as reactExports,j as jsxRuntimeExports,h as useXpodAuthWindowSurface,i as getXpodAuthSurfaceHost,_ as __vitePreload,k as getDefaultExportFromCjs,l as getAugmentedNamespace}from"./dashboard--DWjqkYt.js";import{c as cn,B as Button,u as useComposedRefs,g as createSlottable,d as controlFocusClass}from"./button-_rwfCMMH.js";import{c as createContextScope,P as Primitive,w as useCallbackRef,y as useLayoutEffect2,f as Card,r as createLucideIcon,t as reactDomExports,z as Presence,A as DismissableLayer,B as useId,u as useControllableState,a as composeEventHandlers,E as Portal$1,I as Input}from"./PodDeletionAuthorizationPanel-CzrI8Pgw.js";import{X as XpodMark,f as resolveSolidLocalRouteUrl,h as createSolidLocalRouteFetch,p as probeSolidLocalRouteStatus}from"./account-session-BZ2ttIdq.js";import{QueryEngine}from"@comunica/query-sparql-solid";var __defProp$5=Object.defineProperty,__name$4=(r,e)=>__defProp$5(r,"name",{value:e,configurable:!0}),AVATAR_NAME="Avatar",[createAvatarContext,createAvatarScope]=createContextScope(AVATAR_NAME),STATIC_IMAGE_COUNT_STATE=[0,()=>{}],[AvatarProvider,useAvatarContext]=createAvatarContext(AVATAR_NAME),Avatar$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,...i}=e,[s,o]=reactExports.useState("idle"),[a,d]=useImageCount();return jsxRuntimeExports.jsx(AvatarProvider,{scope:n,imageLoadingStatus:s,setImageLoadingStatus:o,imageCount:a,setImageCount:d,children:jsxRuntimeExports.jsx(Primitive.span,{...i,ref:t})})},"Avatar")),IMAGE_NAME="AvatarImage",AvatarImage$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,src:i,onLoadingStatusChange:s,...o}=e,a=useAvatarContext(IMAGE_NAME,n);a.setImageCount;const d=useImageLoadingStatus(i,{referrerPolicy:o.referrerPolicy,crossOrigin:o.crossOrigin,loadingStatus:a.imageLoadingStatus,setLoadingStatus:a.setImageLoadingStatus}),l=useCallbackRef(p=>{s?.(p)}),h=reactExports.useRef(d);return useLayoutEffect2(()=>{const p=h.current;h.current=d,d!==p&&l(d)},[d,l]),d==="loaded"?jsxRuntimeExports.jsx(Primitive.img,{...o,ref:t,src:i}):null},"AvatarImage")),FALLBACK_NAME="AvatarFallback",AvatarFallback$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,delayMs:i,...s}=e,o=useAvatarContext(FALLBACK_NAME,n),[a,d]=reactExports.useState(i===void 0);return reactExports.useEffect(()=>{if(i!==void 0){const l=window.setTimeout(()=>d(!0),i);return()=>window.clearTimeout(l)}},[i]),a&&o.imageLoadingStatus!=="loaded"?jsxRuntimeExports.jsx(Primitive.span,{...s,ref:t}):null},"AvatarFallback"));function useImageLoadingStatus(r,{loadingStatus:e,setLoadingStatus:t,referrerPolicy:n,crossOrigin:i}){return useLayoutEffect2(()=>{if(!r){t("error");return}const s=new window.Image,o=__name$4(d=>{const l=d.currentTarget;t(getImageLoadingStatus(l))},"handleLoad"),a=__name$4(()=>t("error"),"handleError");return s.addEventListener("load",o),s.addEventListener("error",a),n&&(s.referrerPolicy=n),s.crossOrigin=i??null,s.src=r,t(getImageLoadingStatus(s)),()=>{s.removeEventListener("load",o),s.removeEventListener("error",a),t("idle")}},[r,i,n,t]),e}__name$4(useImageLoadingStatus,"useImageLoadingStatus");function getImageLoadingStatus(r){return r.complete?r.naturalWidth>0?"loaded":"error":"loading"}__name$4(getImageLoadingStatus,"getImageLoadingStatus");function useImageCount(){return STATIC_IMAGE_COUNT_STATE}__name$4(useImageCount,"useImageCount");function useUpdateImageCount(r){}__name$4(useUpdateImageCount,"useUpdateImageCount");const Avatar=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(Avatar$1,{ref:t,className:cn("relative flex shrink-0 overflow-hidden",r),...e}));Avatar.displayName=Avatar$1.displayName;const AvatarImage=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(AvatarImage$1,{ref:t,className:cn("h-full w-full object-cover",r),...e}));AvatarImage.displayName=AvatarImage$1.displayName;const AvatarFallback=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(AvatarFallback$1,{ref:t,className:cn("flex h-full w-full items-center justify-center bg-muted text-lg font-semibold",r),...e}));AvatarFallback.displayName=AvatarFallback$1.displayName;function AuthSurfaceBody({children:r,className:e}){return jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-body",className:cn("min-h-0",e),children:r})}const FOCUSABLE_SELECTOR=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function getFocusable(r){return Array.from(r.querySelectorAll(FOCUSABLE_SELECTOR)).filter(e=>e.getAttribute("aria-hidden")!=="true")}function AuthSurface({mode:r,title:e,children:t,presentation:n="standard",host:i="document",lead:s,onClose:o,closeLabel:a,closeOnEscape:d=!0,className:l,contentClassName:h}){const p=reactExports.useRef(null),g=reactExports.useRef(null),S=reactExports.useId();reactExports.useLayoutEffect(()=>{if(r!=="modal"||typeof document>"u")return;g.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const I=p.current;if(I){const C=getFocusable(I);(n==="compact"?I:C[0]??I).focus()}return()=>{g.current?.focus(),g.current=null}},[r,n]),reactExports.useLayoutEffect(()=>{if(r!=="modal"||typeof document>"u")return;const I=C=>{if(C.key==="Escape"){d&&o&&(C.preventDefault(),o());return}if(C.key!=="Tab")return;const O=p.current;if(!O)return;const P=getFocusable(O);if(P.length===0){C.preventDefault(),O.focus();return}const D=document.activeElement,Y=P.indexOf(D),re=C.shiftKey?Y<=0?P.length-1:Y-1:Y===P.length-1?0:Y+1;C.preventDefault(),P[re].focus()};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[d,r,o]);const y=r==="modal"?{role:"dialog","aria-modal":!0,"aria-labelledby":S}:{role:"region","aria-labelledby":S},v=n==="compact",E=i==="window",w=v?"flex min-h-0 flex-1 flex-col overflow-y-auto":"max-h-[min(80vh,48rem)] overflow-y-auto",T=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[v?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h1",{id:S,className:"sr-only",children:e}),r==="modal"&&o&&a?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":a,className:"absolute right-2 top-2 z-[var(--layer-sticky)]",children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}):jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border/60 p-4",children:[jsxRuntimeExports.jsx("h1",{id:S,className:"text-lg font-semibold text-foreground",children:e}),r==="modal"&&o&&a?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":a,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}),s?jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-lead",className:cn(v?"shrink-0 px-5 pt-7 has-[[data-presentation=compact]]:pt-5":"border-b border-border/60 p-4"),children:s}):null,jsxRuntimeExports.jsx(AuthSurfaceBody,{className:cn(w,h),children:t})]});return jsxRuntimeExports.jsx("div",{"data-testid":`auth-surface-${r}`,"data-auth-surface-mode":r,"data-auth-surface-presentation":v?"compact":void 0,"data-auth-surface-host":E?"window":void 0,className:cn(E?"fixed inset-0 z-[var(--layer-modal)] flex items-stretch justify-stretch overflow-hidden bg-card p-0":r==="modal"?cn("fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center p-4","bg-background"):r==="page"?"flex min-h-[100dvh] w-full items-center justify-center bg-background p-4":"flex min-h-0 w-full items-center justify-center p-4",l),children:E?jsxRuntimeExports.jsx("div",{ref:p,...y,"data-auth-surface-frame":"window",tabIndex:-1,className:"relative flex h-full min-h-0 w-full flex-col overflow-hidden bg-card text-card-foreground focus:outline-none",children:T}):v?jsxRuntimeExports.jsx("div",{ref:p,...y,"data-auth-surface-frame":"compact",tabIndex:-1,style:{outline:"none"},className:"flex h-[400px] w-[280px] max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] min-w-0 flex-col overflow-y-auto overscroll-contain focus:outline-none",children:T}):jsxRuntimeExports.jsx(Card,{ref:p,...y,tabIndex:-1,style:{outline:"none"},className:cn("relative flex min-h-0 w-full flex-col border-border bg-card text-card-foreground focus:outline-none",r==="embedded"?"max-w-none shadow-none":"max-w-lg"),children:T})})}const __iconNode$7=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Check=createLucideIcon("check",__iconNode$7);const __iconNode$6=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Cloud=createLucideIcon("cloud",__iconNode$6);const __iconNode$5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Info=createLucideIcon("info",__iconNode$5);const __iconNode$4=[["path",{d:"M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z",key:"1pdavp"}],["path",{d:"M20.054 15.987H3.946",key:"14rxg9"}]],Laptop=createLucideIcon("laptop",__iconNode$4);const __iconNode$3=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle$1=createLucideIcon("loader-circle",__iconNode$3);const __iconNode$2=[["path",{d:"M5 12h14",key:"1ays0h"}]],Minus=createLucideIcon("minus",__iconNode$2),sides=["top","right","bottom","left"],min=Math.min,max=Math.max,round=Math.round,floor=Math.floor,createCoords=r=>({x:r,y:r}),oppositeSideMap={left:"right",right:"left",bottom:"top",top:"bottom"};function clamp(r,e,t){return max(r,min(e,t))}function evaluate(r,e){return typeof r=="function"?r(e):r}function getSide(r){return r.split("-")[0]}function getAlignment(r){return r.split("-")[1]}function getOppositeAxis(r){return r==="x"?"y":"x"}function getAxisLength(r){return r==="y"?"height":"width"}function getSideAxis(r){const e=r[0];return e==="t"||e==="b"?"y":"x"}function getAlignmentAxis(r){return getOppositeAxis(getSideAxis(r))}function getAlignmentSides(r,e,t){t===void 0&&(t=!1);const n=getAlignment(r),i=getAlignmentAxis(r),s=getAxisLength(i);let o=i==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=getOppositePlacement(o)),[o,getOppositePlacement(o)]}function getExpandedPlacements(r){const e=getOppositePlacement(r);return[getOppositeAlignmentPlacement(r),e,getOppositeAlignmentPlacement(e)]}function getOppositeAlignmentPlacement(r){return r.includes("start")?r.replace("start","end"):r.replace("end","start")}const lrPlacement=["left","right"],rlPlacement=["right","left"],tbPlacement=["top","bottom"],btPlacement=["bottom","top"];function getSideList(r,e,t){switch(r){case"top":case"bottom":return t?e?rlPlacement:lrPlacement:e?lrPlacement:rlPlacement;case"left":case"right":return e?tbPlacement:btPlacement;default:return[]}}function getOppositeAxisPlacements(r,e,t,n){const i=getAlignment(r);let s=getSideList(getSide(r),t==="start",n);return i&&(s=s.map(o=>o+"-"+i),e&&(s=s.concat(s.map(getOppositeAlignmentPlacement)))),s}function getOppositePlacement(r){const e=getSide(r);return oppositeSideMap[e]+r.slice(e.length)}function expandPaddingObject(r){var e,t,n,i;return{top:(e=r.top)!=null?e:0,right:(t=r.right)!=null?t:0,bottom:(n=r.bottom)!=null?n:0,left:(i=r.left)!=null?i:0}}function getPaddingObject(r){return typeof r!="number"?expandPaddingObject(r):{top:r,right:r,bottom:r,left:r}}function rectToClientRect(r){const{x:e,y:t,width:n,height:i}=r;return{width:n,height:i,top:t,left:e,right:e+n,bottom:t+i,x:e,y:t}}function computeCoordsFromPlacement(r,e,t){let{reference:n,floating:i}=r;const s=getSideAxis(e),o=getAlignmentAxis(e),a=getAxisLength(o),d=getSide(e),l=s==="y",h=n.x+n.width/2-i.width/2,p=n.y+n.height/2-i.height/2,g=n[a]/2-i[a]/2;let S;switch(d){case"top":S={x:h,y:n.y-i.height};break;case"bottom":S={x:h,y:n.y+n.height};break;case"right":S={x:n.x+n.width,y:p};break;case"left":S={x:n.x-i.width,y:p};break;default:S={x:n.x,y:n.y}}const y=getAlignment(e);return y&&(S[o]+=g*(y==="end"?1:-1)*(t&&l?-1:1)),S}async function detectOverflow(r,e){var t;e===void 0&&(e={});const{x:n,y:i,platform:s,rects:o,elements:a,strategy:d}=r,{boundary:l="clippingAncestors",rootBoundary:h="viewport",elementContext:p="floating",altBoundary:g=!1,padding:S=0}=evaluate(e,r),y=getPaddingObject(S),E=a[g?p==="floating"?"reference":"floating":p],w=rectToClientRect(await s.getClippingRect({element:(t=await(s.isElement==null?void 0:s.isElement(E)))==null||t?E:E.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:l,rootBoundary:h,strategy:d})),T=p==="floating"?{x:n,y:i,width:o.floating.width,height:o.floating.height}:o.reference,I=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),C=await(s.isElement==null?void 0:s.isElement(I))&&await(s.getScale==null?void 0:s.getScale(I))||{x:1,y:1},O=rectToClientRect(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:T,offsetParent:I,strategy:d}):T);return{top:(w.top-O.top+y.top)/C.y,bottom:(O.bottom-w.bottom+y.bottom)/C.y,left:(w.left-O.left+y.left)/C.x,right:(O.right-w.right+y.right)/C.x}}const MAX_RESET_COUNT=50,computePosition$1=async(r,e,t)=>{const{placement:n="bottom",strategy:i="absolute",middleware:s=[],platform:o}=t,a=o.detectOverflow?o:{...o,detectOverflow},d=await(o.isRTL==null?void 0:o.isRTL(e));let l=await o.getElementRects({reference:r,floating:e,strategy:i}),{x:h,y:p}=computeCoordsFromPlacement(l,n,d),g=n,S=0;const y={};for(let v=0;v<s.length;v++){const E=s[v];if(!E)continue;const{name:w,fn:T}=E,{x:I,y:C,data:O,reset:P}=await T({x:h,y:p,initialPlacement:n,placement:g,strategy:i,middlewareData:y,rects:l,platform:a,elements:{reference:r,floating:e}});h=I??h,p=C??p,y[w]={...y[w],...O},P&&S<MAX_RESET_COUNT&&(S++,typeof P=="object"&&(P.placement&&(g=P.placement),P.rects&&(l=P.rects===!0?await o.getElementRects({reference:r,floating:e,strategy:i}):P.rects),{x:h,y:p}=computeCoordsFromPlacement(l,g,d)),v=-1)}return{x:h,y:p,placement:g,strategy:i,middlewareData:y}},arrow$3=r=>({name:"arrow",options:r,async fn(e){const{x:t,y:n,placement:i,rects:s,platform:o,elements:a,middlewareData:d}=e,{element:l,padding:h=0}=evaluate(r,e)||{};if(l==null)return{};const p=getPaddingObject(h),g={x:t,y:n},S=getAlignmentAxis(i),y=getAxisLength(S),v=await o.getDimensions(l),E=S==="y",w=E?"top":"left",T=E?"bottom":"right",I=E?"clientHeight":"clientWidth",C=s.reference[y]+s.reference[S]-g[S]-s.floating[y],O=g[S]-s.reference[S],P=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l));let D=P?P[I]:0;(!D||!await(o.isElement==null?void 0:o.isElement(P)))&&(D=a.floating[I]||s.floating[y]);const Y=C/2-O/2,re=D/2-v[y]/2-1,$=min(p[w],re),te=min(p[T],re),be=D-v[y]-te,fe=D/2-v[y]/2+Y,Pe=clamp($,fe,be),Ue=!d.arrow&&getAlignment(i)!=null&&fe!==Pe&&s.reference[y]/2-(fe<$?$:te)-v[y]/2<0,ke=Ue?fe<$?fe-$:fe-be:0;return{[S]:g[S]+ke,data:{[S]:Pe,centerOffset:fe-Pe-ke,...Ue&&{alignmentOffset:ke}},reset:Ue}}}),flip$2=function(r){return r===void 0&&(r={}),{name:"flip",options:r,async fn(e){var t,n;const{placement:i,middlewareData:s,rects:o,initialPlacement:a,platform:d,elements:l}=e,{mainAxis:h=!0,crossAxis:p=!0,fallbackPlacements:g,fallbackStrategy:S="bestFit",fallbackAxisSideDirection:y="none",flipAlignment:v=!0,...E}=evaluate(r,e);if((t=s.arrow)!=null&&t.alignmentOffset)return{};const w=getSide(i),T=getSideAxis(a),I=getSide(a)===a,C=await(d.isRTL==null?void 0:d.isRTL(l.floating)),O=g||(I||!v?[getOppositePlacement(a)]:getExpandedPlacements(a)),P=y!=="none";!g&&P&&O.push(...getOppositeAxisPlacements(a,v,y,C));const D=[a,...O],Y=await d.detectOverflow(e,E),re=[];let $=((n=s.flip)==null?void 0:n.overflows)||[];if(h&&re.push(Y[w]),p){const Pe=getAlignmentSides(i,o,C);re.push(Y[Pe[0]],Y[Pe[1]])}if($=[...$,{placement:i,overflows:re}],!re.every(Pe=>Pe<=0)){var te,be;const Pe=(((te=s.flip)==null?void 0:te.index)||0)+1,Ue=D[Pe];if(Ue&&(!(p==="alignment"?T!==getSideAxis(Ue):!1)||$.every(Ae=>getSideAxis(Ae.placement)===T?Ae.overflows[0]>0:!0)))return{data:{index:Pe,overflows:$},reset:{placement:Ue}};let ke=(be=$.filter(Ge=>Ge.overflows[0]<=0).sort((Ge,Ae)=>Ge.overflows[1]-Ae.overflows[1])[0])==null?void 0:be.placement;if(!ke)switch(S){case"bestFit":{var fe;const Ge=(fe=$.filter(Ae=>{if(P){const we=getSideAxis(Ae.placement);return we===T||we==="y"}return!0}).map(Ae=>[Ae.placement,Ae.overflows.filter(we=>we>0).reduce((we,ie)=>we+ie,0)]).sort((Ae,we)=>Ae[1]-we[1])[0])==null?void 0:fe[0];Ge&&(ke=Ge);break}case"initialPlacement":ke=a;break}if(i!==ke)return{reset:{placement:ke}}}return{}}}};function getSideOffsets(r,e){return{top:r.top-e.height,right:r.right-e.width,bottom:r.bottom-e.height,left:r.left-e.width}}function isAnySideFullyClipped(r){return sides.some(e=>r[e]>=0)}const hide$2=function(r){return r===void 0&&(r={}),{name:"hide",options:r,async fn(e){const{rects:t,platform:n}=e,{strategy:i="referenceHidden",...s}=evaluate(r,e);switch(i){case"referenceHidden":{const o=await n.detectOverflow(e,{...s,elementContext:"reference"}),a=getSideOffsets(o,t.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:isAnySideFullyClipped(a)}}}case"escaped":{const o=await n.detectOverflow(e,{...s,altBoundary:!0}),a=getSideOffsets(o,t.floating);return{data:{escapedOffsets:a,escaped:isAnySideFullyClipped(a)}}}default:return{}}}}},originSides=new Set(["left","top"]);async function convertValueToCoords(r,e){const{placement:t,platform:n,elements:i}=r,s=await(n.isRTL==null?void 0:n.isRTL(i.floating)),o=getSide(t),a=getAlignment(t),d=getSideAxis(t)==="y",l=originSides.has(o)?-1:1,h=s&&d?-1:1,p=evaluate(e,r);let{mainAxis:g,crossAxis:S,alignmentAxis:y}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return a&&typeof y=="number"&&(S=a==="end"?y*-1:y),d?{x:S*h,y:g*l}:{x:g*l,y:S*h}}const offset$2=function(r){return r===void 0&&(r=0),{name:"offset",options:r,async fn(e){var t,n;const{x:i,y:s,placement:o,middlewareData:a}=e,d=await convertValueToCoords(e,r);return o===((t=a.offset)==null?void 0:t.placement)&&(n=a.arrow)!=null&&n.alignmentOffset?{}:{x:i+d.x,y:s+d.y,data:{...d,placement:o}}}}},shift$2=function(r){return r===void 0&&(r={}),{name:"shift",options:r,async fn(e){const{x:t,y:n,placement:i,platform:s}=e,{mainAxis:o=!0,crossAxis:a=!1,limiter:d={fn:T=>{let{x:I,y:C}=T;return{x:I,y:C}}},...l}=evaluate(r,e),h={x:t,y:n},p=await s.detectOverflow(e,l),g=getSideAxis(i),S=getOppositeAxis(g);let y=h[S],v=h[g];const E=(T,I)=>clamp(I+p[T==="y"?"top":"left"],I,I-p[T==="y"?"bottom":"right"]);o&&(y=E(S,y)),a&&(v=E(g,v));const w=d.fn({...e,[S]:y,[g]:v});return{...w,data:{x:w.x-t,y:w.y-n,enabled:{[S]:o,[g]:a}}}}}},limitShift$2=function(r){return r===void 0&&(r={}),{options:r,fn(e){var t,n;const{x:i,y:s,placement:o,rects:a,middlewareData:d}=e,{offset:l=0,mainAxis:h=!0,crossAxis:p=!0}=evaluate(r,e),g={x:i,y:s},S=getSideAxis(o),y=getOppositeAxis(S);let v=g[y],E=g[S];const w=evaluate(l,e),T=typeof w=="number"?{mainAxis:w,crossAxis:0}:{mainAxis:(t=w.mainAxis)!=null?t:0,crossAxis:(n=w.crossAxis)!=null?n:0};if(h){const O=y==="y"?"height":"width",P=a.reference[y]-a.floating[O]+T.mainAxis,D=a.reference[y]+a.reference[O]-T.mainAxis;v<P?v=P:v>D&&(v=D)}if(p){var I,C;const O=y==="y"?"width":"height",P=originSides.has(getSide(o)),D=a.reference[S]-a.floating[O]+(P&&((I=d.offset)==null?void 0:I[S])||0)+(P?0:T.crossAxis),Y=a.reference[S]+a.reference[O]+(P?0:((C=d.offset)==null?void 0:C[S])||0)-(P?T.crossAxis:0);E<D?E=D:E>Y&&(E=Y)}return{[y]:v,[S]:E}}}},size$2=function(r){return r===void 0&&(r={}),{name:"size",options:r,async fn(e){const{placement:t,rects:n,platform:i,elements:s}=e,{apply:o=()=>{},...a}=evaluate(r,e),d=await i.detectOverflow(e,a),l=getSide(t),h=getAlignment(t),p=getSideAxis(t)==="y",{width:g,height:S}=n.floating;let y,v;l==="top"||l==="bottom"?(y=l,v=h===(await(i.isRTL==null?void 0:i.isRTL(s.floating))?"start":"end")?"left":"right"):(v=l,y=h==="end"?"top":"bottom");const E=S-d.top-d.bottom,w=g-d.left-d.right,T=min(S-d[y],E),I=min(g-d[v],w),C=e.middlewareData.shift,O=!C;let P=T,D=I;C!=null&&C.enabled.x&&(D=w),C!=null&&C.enabled.y&&(P=E),O&&!h&&(p?D=g-2*max(d.left,d.right):P=S-2*max(d.top,d.bottom)),await o({...e,availableWidth:D,availableHeight:P});const Y=await i.getDimensions(s.floating);return g!==Y.width||S!==Y.height?{reset:{rects:!0}}:{}}}};function hasWindow(){return typeof window<"u"}function getNodeName(r){return isNode(r)?(r.nodeName||"").toLowerCase():"#document"}function getWindow(r){var e;return(r==null||(e=r.ownerDocument)==null?void 0:e.defaultView)||window}function getDocumentElement(r){var e;return(e=(isNode(r)?r.ownerDocument:r.document)||window.document)==null?void 0:e.documentElement}function isNode(r){return hasWindow()?r instanceof Node||r instanceof getWindow(r).Node:!1}function isElement(r){return hasWindow()?r instanceof Element||r instanceof getWindow(r).Element:!1}function isHTMLElement(r){return hasWindow()?r instanceof HTMLElement||r instanceof getWindow(r).HTMLElement:!1}function isShadowRoot(r){return!hasWindow()||typeof ShadowRoot>"u"?!1:r instanceof ShadowRoot||r instanceof getWindow(r).ShadowRoot}function isOverflowElement(r){const{overflow:e,overflowX:t,overflowY:n,display:i}=getComputedStyle$1(r);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&i!=="inline"&&i!=="contents"}function isTableElement(r){return/^(table|td|th)$/.test(getNodeName(r))}function isTopLayer(r){try{if(r.matches(":popover-open"))return!0}catch{}try{return r.matches(":modal")}catch{return!1}}const willChangeRe=/transform|translate|scale|rotate|perspective|filter/,containRe=/paint|layout|strict|content/,isNotNone=r=>!!r&&r!=="none";let isWebKitValue;function isContainingBlock(r){const e=isElement(r)?getComputedStyle$1(r):r;return isNotNone(e.transform)||isNotNone(e.translate)||isNotNone(e.scale)||isNotNone(e.rotate)||isNotNone(e.perspective)||!isWebKit()&&(isNotNone(e.backdropFilter)||isNotNone(e.filter))||willChangeRe.test(e.willChange||"")||containRe.test(e.contain||"")}function getContainingBlock(r){let e=getParentNode(r);for(;isHTMLElement(e)&&!isLastTraversableNode(e);){if(isContainingBlock(e))return e;if(isTopLayer(e))return null;e=getParentNode(e)}return null}function isWebKit(){return isWebKitValue==null&&(isWebKitValue=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),isWebKitValue}function isLastTraversableNode(r){return/^(html|body|#document)$/.test(getNodeName(r))}function getComputedStyle$1(r){return getWindow(r).getComputedStyle(r)}function getNodeScroll(r){return isElement(r)?{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}:{scrollLeft:r.scrollX,scrollTop:r.scrollY}}function getParentNode(r){if(getNodeName(r)==="html")return r;const e=r.assignedSlot||r.parentNode||isShadowRoot(r)&&r.host||getDocumentElement(r);return isShadowRoot(e)?e.host:e}function getNearestOverflowAncestor(r){const e=getParentNode(r);return isLastTraversableNode(e)?(r.ownerDocument||r).body:isHTMLElement(e)&&isOverflowElement(e)?e:getNearestOverflowAncestor(e)}function getOverflowAncestors(r,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const i=getNearestOverflowAncestor(r),s=i===((n=r.ownerDocument)==null?void 0:n.body),o=getWindow(i);if(s){const a=getFrameElement(o);return e.concat(o,o.visualViewport||[],isOverflowElement(i)?i:[],a&&t?getOverflowAncestors(a):[])}else return e.concat(i,getOverflowAncestors(i,[],t))}function getFrameElement(r){return r.parent&&Object.getPrototypeOf(r.parent)?r.frameElement:null}function getCssDimensions(r){const e=getComputedStyle$1(r);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=isHTMLElement(r),s=i?r.offsetWidth:t,o=i?r.offsetHeight:n,a=round(t)!==s||round(n)!==o;return a&&(t=s,n=o),{width:t,height:n,$:a}}function unwrapElement(r){return isElement(r)?r:r.contextElement}function getScale(r){const e=unwrapElement(r);if(!isHTMLElement(e))return createCoords(1);const t=e.getBoundingClientRect(),{width:n,height:i,$:s}=getCssDimensions(e);let o=(s?round(t.width):t.width)/n,a=(s?round(t.height):t.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const noOffsets=createCoords(0);function getVisualOffsets(r){const e=getWindow(r);return!isWebKit()||!e.visualViewport?noOffsets:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function shouldAddVisualOffsets(r,e,t){return e===void 0&&(e=!1),!!t&&e&&t===getWindow(r)}function getBoundingClientRect(r,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const i=r.getBoundingClientRect(),s=unwrapElement(r);let o=createCoords(1);e&&(n?isElement(n)&&(o=getScale(n)):o=getScale(r));const a=shouldAddVisualOffsets(s,t,n)?getVisualOffsets(s):createCoords(0);let d=(i.left+a.x)/o.x,l=(i.top+a.y)/o.y,h=i.width/o.x,p=i.height/o.y;if(s&&n){const g=getWindow(s),S=isElement(n)?getWindow(n):n;let y=g,v=getFrameElement(y);for(;v&&S!==y;){const E=getScale(v),w=v.getBoundingClientRect(),T=getComputedStyle$1(v),I=w.left+(v.clientLeft+parseFloat(T.paddingLeft))*E.x,C=w.top+(v.clientTop+parseFloat(T.paddingTop))*E.y;d*=E.x,l*=E.y,h*=E.x,p*=E.y,d+=I,l+=C,y=getWindow(v),v=getFrameElement(y)}}return rectToClientRect({width:h,height:p,x:d,y:l})}function getWindowScrollBarX(r,e){const t=getNodeScroll(r).scrollLeft;return e?e.left+t:getBoundingClientRect(getDocumentElement(r)).left+t}function getHTMLOffset(r,e){const t=r.getBoundingClientRect(),n=t.left+e.scrollLeft-getWindowScrollBarX(r,t),i=t.top+e.scrollTop;return{x:n,y:i}}function convertOffsetParentRelativeRectToViewportRelativeRect(r){let{elements:e,rect:t,offsetParent:n,strategy:i}=r;const s=i==="fixed",o=getDocumentElement(n),a=e?isTopLayer(e.floating):!1;if(n===o||a&&s)return t;let d={scrollLeft:0,scrollTop:0},l=createCoords(1);const h=createCoords(0),p=isHTMLElement(n);if((p||!s)&&((getNodeName(n)!=="body"||isOverflowElement(o))&&(d=getNodeScroll(n)),p)){const S=getBoundingClientRect(n);l=getScale(n),h.x=S.x+n.clientLeft,h.y=S.y+n.clientTop}const g=o&&!p&&!s?getHTMLOffset(o,d):createCoords(0);return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-d.scrollLeft*l.x+h.x+g.x,y:t.y*l.y-d.scrollTop*l.y+h.y+g.y}}function getClientRects(r){return r.getClientRects?Array.from(r.getClientRects()):[]}function getDocumentRect(r){const e=getNodeScroll(r),t=r.ownerDocument.body,n=max(r.scrollWidth,r.clientWidth,t.scrollWidth,t.clientWidth),i=max(r.scrollHeight,r.clientHeight,t.scrollHeight,t.clientHeight);let s=-e.scrollLeft+getWindowScrollBarX(r);const o=-e.scrollTop;return getComputedStyle$1(t).direction==="rtl"&&(s+=max(r.clientWidth,t.clientWidth)-n),{width:n,height:i,x:s,y:o}}const SCROLLBAR_MAX=25;function getViewportRect(r,e,t){t===void 0&&(t="viewport");const n=t==="layoutViewport",i=getWindow(r),s=getDocumentElement(r),o=i.visualViewport;let a=s.clientWidth,d=s.clientHeight,l=0,h=0;if(o){const g=!isWebKit()||e==="fixed";n?g||(l=-o.offsetLeft,h=-o.offsetTop):(a=o.width,d=o.height,g&&(l=o.offsetLeft,h=o.offsetTop))}if(getWindowScrollBarX(s)<=0){const g=s.ownerDocument,S=g.body,y=getComputedStyle(S),v=g.compatMode==="CSS1Compat"&&parseFloat(y.marginLeft)+parseFloat(y.marginRight)||0,E=Math.abs(s.clientWidth-S.clientWidth-v),w=getComputedStyle(s).scrollbarGutter==="stable both-edges"?E/2:E;w<=SCROLLBAR_MAX&&(a-=w)}return{width:a,height:d,x:l,y:h}}function getInnerBoundingClientRect(r,e){const t=getBoundingClientRect(r,!0,e==="fixed"),n=t.top+r.clientTop,i=t.left+r.clientLeft,s=getScale(r),o=r.clientWidth*s.x,a=r.clientHeight*s.y,d=i*s.x,l=n*s.y;return{width:o,height:a,x:d,y:l}}function getClientRectFromClippingAncestor(r,e,t){let n;if(e==="viewport"||e==="layoutViewport")n=getViewportRect(r,t,e);else if(e==="document")n=getDocumentRect(getDocumentElement(r));else if(isElement(e))n=getInnerBoundingClientRect(e,t);else{const i=getVisualOffsets(r);n={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return rectToClientRect(n)}function getClippingElementAncestors(r,e){const t=e.get(r);if(t)return t;let n=getOverflowAncestors(r,[],!1).filter(a=>isElement(a)&&getNodeName(a)!=="body"),i=null;const s=getComputedStyle$1(r).position==="fixed";let o=s?getParentNode(r):r;for(;isElement(o)&&!isLastTraversableNode(o);){const a=getComputedStyle$1(o),d=isContainingBlock(o),l=i?i.position:s?"fixed":"";!d&&(l==="fixed"||l==="absolute"&&a.position==="static")?n=n.filter(p=>p!==o):i=a,o=getParentNode(o)}return e.set(r,n),n}function getClippingRect(r){let{element:e,boundary:t,rootBoundary:n,strategy:i}=r;const o=[...t==="clippingAncestors"?isTopLayer(e)?[]:getClippingElementAncestors(e,this._c):[].concat(t),n],a=getClientRectFromClippingAncestor(e,o[0],i);let d=a.top,l=a.right,h=a.bottom,p=a.left;for(let g=1;g<o.length;g++){const S=getClientRectFromClippingAncestor(e,o[g],i);d=max(S.top,d),l=min(S.right,l),h=min(S.bottom,h),p=max(S.left,p)}return{width:l-p,height:h-d,x:p,y:d}}function getDimensions(r){const{width:e,height:t}=getCssDimensions(r);return{width:e,height:t}}function getRectRelativeToOffsetParent(r,e,t){const n=isHTMLElement(e),i=getDocumentElement(e),s=t==="fixed",o=getBoundingClientRect(r,!0,s,e);let a={scrollLeft:0,scrollTop:0};const d=createCoords(0);if((n||!s)&&((getNodeName(e)!=="body"||isOverflowElement(i))&&(a=getNodeScroll(e)),n)){const g=getBoundingClientRect(e,!0,s,e);d.x=g.x+e.clientLeft,d.y=g.y+e.clientTop}!n&&i&&(d.x=getWindowScrollBarX(i));const l=i&&!n&&!s?getHTMLOffset(i,a):createCoords(0),h=o.left+a.scrollLeft-d.x-l.x,p=o.top+a.scrollTop-d.y-l.y;return{x:h,y:p,width:o.width,height:o.height}}function isStaticPositioned(r){return getComputedStyle$1(r).position==="static"}function getTrueOffsetParent(r,e){if(!isHTMLElement(r)||getComputedStyle$1(r).position==="fixed")return null;if(e)return e(r);let t=r.offsetParent;return getDocumentElement(r)===t&&(t=t.ownerDocument.body),t}function getOffsetParent(r,e){const t=getWindow(r);if(isTopLayer(r))return t;if(!isHTMLElement(r)){let i=getParentNode(r);for(;i&&!isLastTraversableNode(i);){if(isElement(i)&&!isStaticPositioned(i))return i;i=getParentNode(i)}return t}let n=getTrueOffsetParent(r,e);for(;n&&isTableElement(n)&&isStaticPositioned(n);)n=getTrueOffsetParent(n,e);return n&&isLastTraversableNode(n)&&isStaticPositioned(n)&&!isContainingBlock(n)?t:n||getContainingBlock(r)||t}const getElementRects=async function(r){const e=this.getOffsetParent||getOffsetParent,t=this.getDimensions,n=await t(r.floating);return{reference:getRectRelativeToOffsetParent(r.reference,await e(r.floating),r.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function isRTL(r){return getComputedStyle$1(r).direction==="rtl"}const platform={convertOffsetParentRelativeRectToViewportRelativeRect,getDocumentElement,getClippingRect,getOffsetParent,getElementRects,getClientRects,getDimensions,getScale,isElement,isRTL};function rectsAreEqual(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function observeMove(r,e,t){let n=null,i;const s=getDocumentElement(r);function o(){var h;clearTimeout(i),(h=n)==null||h.disconnect(),n=null}function a(h,p){h===void 0&&(h=!1),p===void 0&&(p=1),o();const g=r.getBoundingClientRect(),{left:S,top:y,width:v,height:E}=g;if(h||e(),!v||!E)return;const w=floor(y),T=floor(s.clientWidth-(S+v)),I=floor(s.clientHeight-(y+E)),C=floor(S),P={rootMargin:-w+"px "+-T+"px "+-I+"px "+-C+"px",threshold:max(0,min(1,p))||1};let D=!0;function Y(re){const $=re[0].intersectionRatio;if(!rectsAreEqual(g,r.getBoundingClientRect()))return a();if($!==p){if(!D)return a();$?a(!1,$):i=setTimeout(()=>{a(!1,1e-7)},1e3)}D=!1}try{n=new IntersectionObserver(Y,{...P,root:s.ownerDocument})}catch{n=new IntersectionObserver(Y,P)}n.observe(r)}const d=getWindow(r),l=()=>a(t);return d.addEventListener("resize",l),a(!0),()=>{d.removeEventListener("resize",l),o()}}function autoUpdate(r,e,t,n){n===void 0&&(n={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:d=!1}=n,l=unwrapElement(r),h=i||s?[...l?getOverflowAncestors(l):[],...e?getOverflowAncestors(e):[]]:[];h.forEach(w=>{i&&w.addEventListener("scroll",t),s&&w.addEventListener("resize",t)});const p=l&&a?observeMove(l,t,s):null;let g=-1,S=null;o&&(S=new ResizeObserver(w=>{let[T]=w;T&&T.target===l&&S&&e&&(S.unobserve(e),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{var I;(I=S)==null||I.observe(e)})),t()}),l&&!d&&S.observe(l),e&&S.observe(e));let y,v=d?getBoundingClientRect(r):null;d&&E();function E(){const w=getBoundingClientRect(r);v&&!rectsAreEqual(v,w)&&t(),v=w,y=requestAnimationFrame(E)}return t(),()=>{var w;h.forEach(T=>{i&&T.removeEventListener("scroll",t),s&&T.removeEventListener("resize",t)}),p?.(),(w=S)==null||w.disconnect(),S=null,d&&cancelAnimationFrame(y)}}const offset$1=offset$2,shift$1=shift$2,flip$1=flip$2,size$1=size$2,hide$1=hide$2,arrow$2=arrow$3,limitShift$1=limitShift$2,computePosition=(r,e,t)=>{const n=new Map,i=t??{},s={...platform,...i.platform,_c:n};return computePosition$1(r,e,{...i,platform:s})};var isClient=typeof document<"u",noop$2=function(){},index=isClient?reactExports.useLayoutEffect:noop$2;function deepEqual$1(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(typeof r=="function"&&r.toString()===e.toString())return!0;let t,n,i;if(r&&e&&typeof r=="object"){if(Array.isArray(r)){if(t=r.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!deepEqual$1(r[n],e[n]))return!1;return!0}if(i=Object.keys(r),t=i.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;)if(!{}.hasOwnProperty.call(e,i[n]))return!1;for(n=t;n--!==0;){const s=i[n];if(!(s==="_owner"&&r.$$typeof)&&!deepEqual$1(r[s],e[s]))return!1}return!0}return r!==r&&e!==e}function getDPR(r){return typeof window>"u"?1:(r.ownerDocument.defaultView||window).devicePixelRatio||1}function roundByDPR(r,e){const t=getDPR(r);return Math.round(e*t)/t}function useLatestRef(r){const e=reactExports.useRef(r);return index(()=>{e.current=r}),e}function useFloating(r){r===void 0&&(r={});const{placement:e="bottom",strategy:t="absolute",middleware:n=[],platform:i,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:d,open:l}=r,[h,p]=reactExports.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[g,S]=reactExports.useState(n);deepEqual$1(g,n)||S(n);const[y,v]=reactExports.useState(null),[E,w]=reactExports.useState(null),T=reactExports.useCallback(Ae=>{Ae!==P.current&&(P.current=Ae,v(Ae))},[]),I=reactExports.useCallback(Ae=>{Ae!==D.current&&(D.current=Ae,w(Ae))},[]),C=s||y,O=o||E,P=reactExports.useRef(null),D=reactExports.useRef(null),Y=reactExports.useRef(h),re=d!=null,$=useLatestRef(d),te=useLatestRef(i),be=useLatestRef(l),fe=reactExports.useCallback(()=>{if(!P.current||!D.current)return;const Ae={placement:e,strategy:t,middleware:g};te.current&&(Ae.platform=te.current),computePosition(P.current,D.current,Ae).then(we=>{const ie={...we,isPositioned:be.current!==!1};Pe.current&&!deepEqual$1(Y.current,ie)&&(Y.current=ie,reactDomExports.flushSync(()=>{p(ie)}))})},[g,e,t,te,be]);index(()=>{l===!1&&Y.current.isPositioned&&(Y.current.isPositioned=!1,p(Ae=>({...Ae,isPositioned:!1})))},[l]);const Pe=reactExports.useRef(!1);index(()=>(Pe.current=!0,()=>{Pe.current=!1}),[]),index(()=>{if(C&&(P.current=C),O&&(D.current=O),C&&O){if($.current)return $.current(C,O,fe);fe()}},[C,O,fe,$,re]);const Ue=reactExports.useMemo(()=>({reference:P,floating:D,setReference:T,setFloating:I}),[T,I]),ke=reactExports.useMemo(()=>({reference:C,floating:O}),[C,O]),Ge=reactExports.useMemo(()=>{const Ae={position:t,left:0,top:0};if(!ke.floating)return Ae;const we=roundByDPR(ke.floating,h.x),ie=roundByDPR(ke.floating,h.y);return a?{...Ae,transform:"translate("+we+"px, "+ie+"px)",...getDPR(ke.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:we,top:ie}},[t,a,ke.floating,h.x,h.y]);return reactExports.useMemo(()=>({...h,update:fe,refs:Ue,elements:ke,floatingStyles:Ge}),[h,fe,Ue,ke,Ge])}const arrow$1=r=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:r,fn(t){const{element:n,padding:i}=typeof r=="function"?r(t):r;return n&&e(n)?n.current!=null?arrow$2({element:n.current,padding:i}).fn(t):{}:n?arrow$2({element:n,padding:i}).fn(t):{}}}},offset=(r,e)=>{const t=offset$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},shift=(r,e)=>{const t=shift$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},limitShift=(r,e)=>({fn:limitShift$1(r).fn,options:[r,e]}),flip=(r,e)=>{const t=flip$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},size=(r,e)=>{const t=size$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},hide=(r,e)=>{const t=hide$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},arrow=(r,e)=>{const t=arrow$1(r);return{name:t.name,fn:t.fn,options:[r,e]}};var __defProp$4=Object.defineProperty,__name$3=(r,e)=>__defProp$4(r,"name",{value:e,configurable:!0});function useSize(r){const[e,t]=reactExports.useState(void 0);return useLayoutEffect2(()=>{if(r){t({width:r.offsetWidth,height:r.offsetHeight});const n=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let o,a;if("borderBoxSize"in s){const d=s.borderBoxSize,l=Array.isArray(d)?d[0]:d;o=l.inlineSize,a=l.blockSize}else o=r.offsetWidth,a=r.offsetHeight;t({width:o,height:a})});return n.observe(r,{box:"border-box"}),()=>n.unobserve(r)}else t(void 0)},[r]),e}__name$3(useSize,"useSize");var __defProp$3=Object.defineProperty,__name$2=(r,e)=>__defProp$3(r,"name",{value:e,configurable:!0}),POPPER_NAME="Popper",[createPopperContext,createPopperScope]=createContextScope(POPPER_NAME),[PopperProvider,usePopperContext]=createPopperContext(POPPER_NAME),Popper=__name$2(r=>{const{__scopePopper:e,children:t}=r,[n,i]=reactExports.useState(null),[s,o]=reactExports.useState(void 0);return jsxRuntimeExports.jsx(PopperProvider,{scope:e,anchor:n,onAnchorChange:i,placementState:s,setPlacementState:o,children:t})},"Popper"),ANCHOR_NAME="PopperAnchor",PopperAnchor=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:n,virtualRef:i,...s}=e,o=usePopperContext(ANCHOR_NAME,n),a=reactExports.useRef(null),d=o.onAnchorChange,l=reactExports.useCallback(v=>{a.current=v,v&&d(v)},[d]),h=useComposedRefs(t,l),p=reactExports.useRef(null);reactExports.useEffect(()=>{if(!i)return;const v=p.current;p.current=i.current,v!==p.current&&d(p.current)});const g=o.placementState&&getSideAndAlignFromPlacement(o.placementState),S=g?.[0],y=g?.[1];return i?null:jsxRuntimeExports.jsx(Primitive.div,{"data-radix-popper-side":S,"data-radix-popper-align":y,...s,ref:h})},"PopperAnchor")),CONTENT_NAME$1="PopperContent",[PopperContentProvider,useContentContext]=createPopperContext(CONTENT_NAME$1),PopperContent=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:n,side:i="bottom",sideOffset:s=0,align:o="center",alignOffset:a=0,arrowPadding:d=0,avoidCollisions:l=!0,collisionBoundary:h=[],collisionPadding:p=0,sticky:g="partial",hideWhenDetached:S=!1,updatePositionStrategy:y="optimized",onPlaced:v,...E}=e,w=usePopperContext(CONTENT_NAME$1,n),[T,I]=reactExports.useState(null),C=useComposedRefs(t,I),[O,P]=reactExports.useState(null),D=useSize(O),Y=D?.width??0,re=D?.height??0,$=i+(o!=="center"?"-"+o:""),te=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},be=Array.isArray(h)?h:[h],fe=be.length>0,Pe={padding:te,boundary:be.filter(isNotNull),altBoundary:fe},{refs:Ue,floatingStyles:ke,placement:Ge,isPositioned:Ae,middlewareData:we}=useFloating({strategy:"fixed",placement:$,whileElementsMounted:__name$2((...Fe)=>autoUpdate(...Fe,{animationFrame:y==="always"}),"whileElementsMounted"),elements:{reference:w.anchor},middleware:[offset({mainAxis:s+re,alignmentAxis:a}),l&&shift({mainAxis:!0,crossAxis:!1,limiter:g==="partial"?limitShift():void 0,...Pe}),l&&flip({...Pe}),size({...Pe,apply:__name$2(({elements:Fe,rects:De,availableWidth:K,availableHeight:x})=>{const{width:_,height:A}=De.reference,N=Fe.floating.style;N.setProperty("--radix-popper-available-width",`${K}px`),N.setProperty("--radix-popper-available-height",`${x}px`),N.setProperty("--radix-popper-anchor-width",`${_}px`),N.setProperty("--radix-popper-anchor-height",`${A}px`)},"apply")}),O&&arrow({element:O,padding:d}),transformOrigin({arrowWidth:Y,arrowHeight:re}),S&&hide({strategy:"referenceHidden",...Pe,boundary:fe?Pe.boundary:void 0})]}),ie=w.setPlacementState;useLayoutEffect2(()=>(ie(Ge),()=>{ie(void 0)}),[Ge,ie]);const[xe,Ne]=getSideAndAlignFromPlacement(Ge),Ce=useCallbackRef(v);useLayoutEffect2(()=>{Ae&&Ce?.()},[Ae,Ce]);const je=we.arrow?.x,Ve=we.arrow?.y,We=we.arrow?.centerOffset!==0,[Be,Ie]=reactExports.useState();return useLayoutEffect2(()=>{T&&Ie(window.getComputedStyle(T).zIndex)},[T]),jsxRuntimeExports.jsx("div",{ref:Ue.setFloating,"data-radix-popper-content-wrapper":"",style:{...ke,transform:Ae?ke.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Be,"--radix-popper-transform-origin":[we.transformOrigin?.x,we.transformOrigin?.y].join(" "),...we.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:jsxRuntimeExports.jsx(PopperContentProvider,{scope:n,placedSide:xe,placedAlign:Ne,onArrowChange:P,arrowX:je,arrowY:Ve,shouldHideArrow:We,children:jsxRuntimeExports.jsx(Primitive.div,{"data-side":xe,"data-align":Ne,...E,ref:C,style:{...E.style,animation:Ae?E.style?.animation:"none"}})})})},"PopperContent"));function isNotNull(r){return r!==null}__name$2(isNotNull,"isNotNull");var transformOrigin=__name$2(r=>({name:"transformOrigin",options:r,fn(e){const{placement:t,rects:n,middlewareData:i}=e,o=i.arrow?.centerOffset!==0,a=o?0:r.arrowWidth,d=o?0:r.arrowHeight,[l,h]=getSideAndAlignFromPlacement(t),p={start:"0%",center:"50%",end:"100%"}[h],g=(i.arrow?.x??0)+a/2,S=(i.arrow?.y??0)+d/2;let y="",v="";return l==="bottom"?(y=o?p:`${g}px`,v=`${-d}px`):l==="top"?(y=o?p:`${g}px`,v=`${n.floating.height+d}px`):l==="right"?(y=`${-d}px`,v=o?p:`${S}px`):l==="left"&&(y=`${n.floating.width+d}px`,v=o?p:`${S}px`),{data:{x:y,y:v}}}}),"transformOrigin");function getSideAndAlignFromPlacement(r){const[e,t="center"]=r.split("-");return[e,t]}__name$2(getSideAndAlignFromPlacement,"getSideAndAlignFromPlacement");var Root2=Popper,Anchor=PopperAnchor,Content=PopperContent,__defProp$2=Object.defineProperty,__name$1=(r,e)=>__defProp$2(r,"name",{value:e,configurable:!0}),VISUALLY_HIDDEN_STYLES=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),VisuallyHidden=reactExports.forwardRef(__name$1(function(e,t){return jsxRuntimeExports.jsx(Primitive.span,{...e,ref:t,style:{...VISUALLY_HIDDEN_STYLES,...e.style}})},"VisuallyHidden")),Root=VisuallyHidden,__defProp$1=Object.defineProperty,__name=(r,e)=>__defProp$1(r,"name",{value:e,configurable:!0}),[createTooltipContext,createTooltipScope]=createContextScope("Tooltip",[createPopperScope]),usePopperScope=createPopperScope(),PROVIDER_NAME="TooltipProvider",DEFAULT_DELAY_DURATION=700,TOOLTIP_OPEN="tooltip.open",[TooltipProviderContextProvider,useTooltipProviderContext]=createTooltipContext(PROVIDER_NAME),TooltipProvider$1=__name(r=>{const{__scopeTooltip:e,delayDuration:t=DEFAULT_DELAY_DURATION,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:s}=r,o=reactExports.useRef(!0),a=reactExports.useRef(!1),d=reactExports.useRef(0);return reactExports.useEffect(()=>{const l=d.current;return()=>window.clearTimeout(l)},[]),jsxRuntimeExports.jsx(TooltipProviderContextProvider,{scope:e,isOpenDelayedRef:o,delayDuration:t,onOpen:reactExports.useCallback(()=>{n<=0||(window.clearTimeout(d.current),o.current=!1)},[n]),onClose:reactExports.useCallback(()=>{n<=0||(window.clearTimeout(d.current),d.current=window.setTimeout(()=>o.current=!0,n))},[n]),isPointerInTransitRef:a,onPointerInTransitChange:reactExports.useCallback(l=>{a.current=l},[]),disableHoverableContent:i,children:s})},"TooltipProvider"),TOOLTIP_NAME="Tooltip",[TooltipContextProvider,useTooltipContext]=createTooltipContext(TOOLTIP_NAME),Tooltip$1=__name(r=>{const{__scopeTooltip:e,children:t,open:n,defaultOpen:i,onOpenChange:s,disableHoverableContent:o,delayDuration:a}=r,d=useTooltipProviderContext(TOOLTIP_NAME,r.__scopeTooltip),l=usePopperScope(e),[h,p]=reactExports.useState(null),[g,S]=reactExports.useState(void 0),y=useId(),v=reactExports.useRef(0),E=o??d.disableHoverableContent,w=a??d.delayDuration,T=reactExports.useRef(!1),[I,C]=useControllableState({prop:n,defaultProp:i??!1,onChange:__name($=>{$?(d.onOpen(),document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN))):d.onClose(),s?.($)},"onChange"),caller:TOOLTIP_NAME}),O=reactExports.useMemo(()=>I?T.current?"delayed-open":"instant-open":"closed",[I]),P=reactExports.useCallback(()=>{window.clearTimeout(v.current),v.current=0,T.current=!1,C(!0)},[C]),D=reactExports.useCallback(()=>{window.clearTimeout(v.current),v.current=0,C(!1)},[C]),Y=reactExports.useCallback(()=>{window.clearTimeout(v.current),v.current=window.setTimeout(()=>{T.current=!0,C(!0),v.current=0},w)},[w,C]);reactExports.useEffect(()=>()=>{v.current&&(window.clearTimeout(v.current),v.current=0)},[]);const re=g??y;return jsxRuntimeExports.jsx(Root2,{...l,children:jsxRuntimeExports.jsx(TooltipContextProvider,{scope:e,contentId:re,setContentId:S,open:I,stateAttribute:O,trigger:h,onTriggerChange:p,onTriggerEnter:reactExports.useCallback(()=>{d.isOpenDelayedRef.current?Y():P()},[d.isOpenDelayedRef,Y,P]),onTriggerLeave:reactExports.useCallback(()=>{E?D():(window.clearTimeout(v.current),v.current=0)},[D,E]),onOpen:P,onClose:D,disableHoverableContent:E,children:t})})},"Tooltip"),TRIGGER_NAME="TooltipTrigger",TooltipTrigger$1=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:n,...i}=e,s=useTooltipContext(TRIGGER_NAME,n),o=useTooltipProviderContext(TRIGGER_NAME,n),a=usePopperScope(n),d=reactExports.useRef(null),l=useComposedRefs(t,d,s.onTriggerChange),h=reactExports.useRef(!1),p=reactExports.useRef(!1),g=reactExports.useCallback(()=>h.current=!1,[]);return reactExports.useEffect(()=>()=>document.removeEventListener("pointerup",g),[g]),jsxRuntimeExports.jsx(Anchor,{asChild:!0,...a,children:jsxRuntimeExports.jsx(Primitive.button,{"aria-describedby":s.open?s.contentId:void 0,"data-state":s.stateAttribute,...i,ref:l,onPointerMove:composeEventHandlers(e.onPointerMove,S=>{S.pointerType!=="touch"&&!p.current&&!o.isPointerInTransitRef.current&&(s.onTriggerEnter(),p.current=!0)}),onPointerLeave:composeEventHandlers(e.onPointerLeave,()=>{s.onTriggerLeave(),p.current=!1}),onPointerDown:composeEventHandlers(e.onPointerDown,()=>{s.open&&s.onClose(),h.current=!0,document.addEventListener("pointerup",g,{once:!0})}),onFocus:composeEventHandlers(e.onFocus,()=>{h.current||s.onOpen()}),onBlur:composeEventHandlers(e.onBlur,s.onClose),onClick:composeEventHandlers(e.onClick,s.onClose)})})},"TooltipTrigger")),PORTAL_NAME="TooltipPortal",[PortalProvider,usePortalContext]=createTooltipContext(PORTAL_NAME,{forceMount:void 0}),TooltipPortal$1=__name(r=>{const{__scopeTooltip:e,forceMount:t,children:n,container:i}=r,s=useTooltipContext(PORTAL_NAME,e);return jsxRuntimeExports.jsx(PortalProvider,{scope:e,forceMount:t,children:jsxRuntimeExports.jsx(Presence,{present:t||s.open,children:jsxRuntimeExports.jsx(Portal$1,{asChild:!0,container:i,children:n})})})},"TooltipPortal"),CONTENT_NAME="TooltipContent",TooltipContent$1=reactExports.forwardRef(__name(function(e,t){const n=usePortalContext(CONTENT_NAME,e.__scopeTooltip),{forceMount:i=n.forceMount,side:s="top",...o}=e,a=useTooltipContext(CONTENT_NAME,e.__scopeTooltip);return jsxRuntimeExports.jsx(Presence,{present:i||a.open,children:a.disableHoverableContent?jsxRuntimeExports.jsx(TooltipContentImpl,{side:s,...o,ref:t}):jsxRuntimeExports.jsx(TooltipContentHoverable,{side:s,...o,ref:t})})},"TooltipContent")),TooltipContentHoverable=reactExports.forwardRef(__name(function(e,t){const n=useTooltipContext(CONTENT_NAME,e.__scopeTooltip),i=useTooltipProviderContext(CONTENT_NAME,e.__scopeTooltip),s=reactExports.useRef(null),o=useComposedRefs(t,s),[a,d]=reactExports.useState(null),{trigger:l,onClose:h}=n,p=s.current,{onPointerInTransitChange:g}=i,S=reactExports.useCallback(()=>{d(null),g(!1)},[g]),y=reactExports.useCallback((v,E)=>{const w=v.currentTarget,T={x:v.clientX,y:v.clientY},I=getExitSideFromRect(T,w.getBoundingClientRect()),C=getPaddedExitPoints(T,I),O=getPointsFromRect(E.getBoundingClientRect()),P=getHull([...C,...O]);d(P),g(!0)},[g]);return reactExports.useEffect(()=>()=>S(),[S]),reactExports.useEffect(()=>{if(l&&p){const v=__name(w=>y(w,p),"handleTriggerLeave"),E=__name(w=>y(w,l),"handleContentLeave");return l.addEventListener("pointerleave",v),p.addEventListener("pointerleave",E),()=>{l.removeEventListener("pointerleave",v),p.removeEventListener("pointerleave",E)}}},[l,p,y,S]),reactExports.useEffect(()=>{if(a){const v=__name(E=>{const w=E.target,T={x:E.clientX,y:E.clientY},I=l?.contains(w)||p?.contains(w),C=!isPointInPolygon(T,a);I?S():C&&(S(),h())},"handleTrackPointerGrace");return document.addEventListener("pointermove",v),()=>document.removeEventListener("pointermove",v)}},[l,p,a,h,S]),jsxRuntimeExports.jsx(TooltipContentImpl,{...e,ref:o})},"TooltipContentHoverable")),Slottable=createSlottable("TooltipContent"),TooltipContentImpl=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:n,children:i,"aria-label":s,id:o,onEscapeKeyDown:a,onPointerDownOutside:d,...l}=e,h=useTooltipContext(CONTENT_NAME,n),p=usePopperScope(n),{onClose:g}=h;reactExports.useEffect(()=>(document.addEventListener(TOOLTIP_OPEN,g),()=>document.removeEventListener(TOOLTIP_OPEN,g)),[g]),reactExports.useEffect(()=>{if(h.trigger){const y=__name(v=>{v.target instanceof Node&&v.target.contains(h.trigger)&&g()},"handleScroll");return window.addEventListener("scroll",y,{capture:!0}),()=>window.removeEventListener("scroll",y,{capture:!0})}},[h.trigger,g]);const{setContentId:S}=h;return useLayoutEffect2(()=>(S(o),()=>{S(void 0)}),[o,S]),jsxRuntimeExports.jsx(DismissableLayer,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:a,onPointerDownOutside:d,onFocusOutside:y=>y.preventDefault(),onDismiss:g,children:jsxRuntimeExports.jsxs(Content,{"data-state":h.stateAttribute,role:s?void 0:"tooltip",id:s?void 0:h.contentId,...p,...l,ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[jsxRuntimeExports.jsx(Slottable,{children:i}),s?jsxRuntimeExports.jsx(Root,{id:h.contentId,role:"tooltip",children:s}):null]})})},"TooltipContentImpl"));function getExitSideFromRect(r,e){const t=Math.abs(e.top-r.y),n=Math.abs(e.bottom-r.y),i=Math.abs(e.right-r.x),s=Math.abs(e.left-r.x);switch(Math.min(t,n,i,s)){case s:return"left";case i:return"right";case t:return"top";case n:return"bottom";default:throw new Error("unreachable")}}__name(getExitSideFromRect,"getExitSideFromRect");function getPaddedExitPoints(r,e,t=5){const n=[];switch(e){case"top":n.push({x:r.x-t,y:r.y+t},{x:r.x+t,y:r.y+t});break;case"bottom":n.push({x:r.x-t,y:r.y-t},{x:r.x+t,y:r.y-t});break;case"left":n.push({x:r.x+t,y:r.y-t},{x:r.x+t,y:r.y+t});break;case"right":n.push({x:r.x-t,y:r.y-t},{x:r.x-t,y:r.y+t});break}return n}__name(getPaddedExitPoints,"getPaddedExitPoints");function getPointsFromRect(r){const{top:e,right:t,bottom:n,left:i}=r;return[{x:i,y:e},{x:t,y:e},{x:t,y:n},{x:i,y:n}]}__name(getPointsFromRect,"getPointsFromRect");function isPointInPolygon(r,e){const{x:t,y:n}=r;let i=!1;for(let s=0,o=e.length-1;s<e.length;o=s++){const a=e[s],d=e[o],l=a.x,h=a.y,p=d.x,g=d.y;h>n!=g>n&&t<(p-l)*(n-h)/(g-h)+l&&(i=!i)}return i}__name(isPointInPolygon,"isPointInPolygon");function getHull(r){const e=r.slice();return e.sort((t,n)=>t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0),getHullPresorted(e)}__name(getHull,"getHull");function getHullPresorted(r){if(r.length<=1)return r.slice();const e=[];for(let n=0;n<r.length;n++){const i=r[n];for(;e.length>=2;){const s=e[e.length-1],o=e[e.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))e.pop();else break}e.push(i)}e.pop();const t=[];for(let n=r.length-1;n>=0;n--){const i=r[n];for(;t.length>=2;){const s=t[t.length-1],o=t[t.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))t.pop();else break}t.push(i)}return t.pop(),e.length===1&&t.length===1&&e[0].x===t[0].x&&e[0].y===t[0].y?e:e.concat(t)}__name(getHullPresorted,"getHullPresorted");var Provider=TooltipProvider$1,Root3=Tooltip$1,Trigger=TooltipTrigger$1,Portal=TooltipPortal$1,Content2=TooltipContent$1;const TooltipProvider=Provider,Tooltip=Root3,TooltipTrigger=Trigger,TooltipPortal=Portal,TooltipContent=reactExports.forwardRef(({className:r,sideOffset:e=4,...t},n)=>jsxRuntimeExports.jsx(Content2,{ref:n,sideOffset:e,className:cn("z-[var(--layer-popover)] overflow-hidden rounded-md border border-border/50 bg-popover","px-2 py-1 text-xs text-popover-foreground shadow-md","animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...t}));TooltipContent.displayName=Content2.displayName;function BrandInfo({logo:r,info:e,infoLabel:t="Details",className:n}){const[i,s]=reactExports.useState(!1),o=reactExports.useRef(null);return jsxRuntimeExports.jsxs("div",{className:cn("inline-flex min-w-0 items-center gap-1",n),children:[r,e!=null&&e!==!1?jsxRuntimeExports.jsx(TooltipProvider,{delayDuration:150,children:jsxRuntimeExports.jsxs(Tooltip,{open:i,onOpenChange:s,children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsx("button",{ref:o,type:"button","aria-label":t,"aria-expanded":i,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-primary/10 hover:text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onPointerDown:a=>a.preventDefault(),onClick:a=>{a.preventDefault(),s(d=>!d)},children:jsxRuntimeExports.jsx(Info,{className:"h-4 w-4","aria-hidden":"true"})})}),jsxRuntimeExports.jsx(TooltipPortal,{children:jsxRuntimeExports.jsx(TooltipContent,{side:"bottom",align:"center",collisionPadding:12,onPointerDownOutside:a=>{a.target instanceof Node&&o.current?.contains(a.target)&&a.preventDefault()},className:"max-w-[min(320px,calc(100vw-24px))] space-y-2 p-3 text-left leading-relaxed [overflow-wrap:anywhere]",children:e})})]})}):null]})}const Checkbox=reactExports.forwardRef(({className:r,indeterminate:e=!1,...t},n)=>{const i=reactExports.useRef(null);return reactExports.useImperativeHandle(n,()=>i.current),reactExports.useEffect(()=>{i.current&&(i.current.indeterminate=e)}),jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0 items-center justify-center align-middle",children:[jsxRuntimeExports.jsx("input",{...t,ref:i,type:"checkbox",className:cn("peer m-0 h-4 w-4 shrink-0 appearance-none rounded border border-input bg-background checked:border-primary checked:bg-primary checked:bg-none indeterminate:border-primary indeterminate:bg-primary indeterminate:bg-none disabled:cursor-not-allowed disabled:opacity-50",controlFocusClass,r)}),jsxRuntimeExports.jsx(Check,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-checked:block peer-indeterminate:hidden peer-disabled:opacity-50",strokeWidth:3}),jsxRuntimeExports.jsx(Minus,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-indeterminate:block peer-disabled:opacity-50",strokeWidth:3})]})});Checkbox.displayName="Checkbox";function FormField({label:r,error:e,hint:t,labelAside:n,children:i,className:s,...o}){const a=reactExports.useId(),d=`${a}-error`,l=`${a}-hint`,h=[e?d:void 0,t?l:void 0].filter(Boolean).join(" ")||void 0;return jsxRuntimeExports.jsxs("div",{...o,className:cn("flex flex-col gap-1.5",s),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("label",{htmlFor:a,className:"text-[13px] font-medium text-foreground",children:r}),n]}),i({id:a,...e?{"aria-invalid":!0}:{},"aria-describedby":h}),e?jsxRuntimeExports.jsx("p",{id:d,role:"alert",className:"text-[13px] text-destructive",children:e}):null,t?jsxRuntimeExports.jsx("div",{id:l,className:"text-[13px] text-muted-foreground",children:t}):null]})}const EmailInput=reactExports.forwardRef(({onInput:r,onChange:e,autoCapitalize:t="none",spellCheck:n=!1,...i},s)=>{const o=reactExports.useRef(null),a=reactExports.useRef(null);reactExports.useImperativeHandle(s,()=>o.current,[]);const d=reactExports.useCallback(h=>{const p=a.current??(a.current=h.ownerDocument.createElement("input"));p.type="email",p.multiple=h.multiple,p.required=h.required,p.value=h.value,h.setCustomValidity(p.validity.valid?"":p.validationMessage)},[]);reactExports.useLayoutEffect(()=>{o.current&&d(o.current)}),reactExports.useEffect(()=>{const h=o.current,p=h?.form;if(!h||!p)return;const g=()=>queueMicrotask(()=>d(h));return p.addEventListener("reset",g),()=>p.removeEventListener("reset",g)},[i.form,d]);const l=h=>{d(h),queueMicrotask(()=>d(h))};return jsxRuntimeExports.jsx(Input,{...i,ref:o,type:"text",inputMode:"email",autoCapitalize:t,spellCheck:n,onInput:h=>{l(h.currentTarget),r?.(h)},onChange:h=>{l(h.currentTarget),e?.(h)}})});EmailInput.displayName="EmailInput";const FOCUSABLE=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","summary",'[tabindex]:not([tabindex="-1"])'].join(","),PRIMARY_SELECTOR="[data-pod-sign-in-primary]";function isReachable(r){if(r.hidden||r.closest("[hidden]")||r.matches(":disabled"))return!1;const e=r.ownerDocument.defaultView?.getComputedStyle(r);if(e&&(e.display==="none"||e.visibility==="hidden"))return!1;for(let t=r.parentElement;t;t=t.parentElement){if(t.tagName!=="DETAILS"||t.open)continue;const n=Array.from(t.children).find(i=>i.tagName==="SUMMARY");if(!n||!(n===r||n.contains(r)))return!1}return!0}function useModalFocus(r,e){const t=reactExports.useRef(null),n=reactExports.useRef(e);return n.current=e,reactExports.useEffect(()=>{if(!r)return;const i=document.activeElement instanceof HTMLElement?document.activeElement:null;t.current?.focus();const s=o=>{if(o.key==="Escape"&&n.current){o.preventDefault(),n.current();return}if(o.key!=="Tab")return;const a=t.current;if(!a)return;const d=Array.from(a.querySelectorAll(FOCUSABLE)).filter(isReachable);if(d.length===0){o.preventDefault(),a.focus();return}const l=d.indexOf(document.activeElement);if(!o.shiftKey&&document.activeElement===a){const p=d.find(g=>g.matches(PRIMARY_SELECTOR));if(p){o.preventDefault(),p.focus();return}}const h=o.shiftKey?l<=0?d.length-1:l-1:l===d.length-1?0:l+1;o.preventDefault(),d[h]?.focus()};return document.addEventListener("keydown",s),()=>{document.removeEventListener("keydown",s),i?.focus()}},[r]),t}const bodyClass="flex min-h-0 w-full max-w-[480px] flex-1 flex-col";function PodSignInFrame({presentation:r,ariaLabel:e,appIntro:t,children:n,modal:i=!0,onClose:s,closeLabel:o,dataAttributes:a}){const d=r==="dialog"&&i,l=useModalFocus(d,s),h=t;if(r==="window")return jsxRuntimeExports.jsx("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"window",...a,className:"pod-sign-in flex h-full min-h-0 w-full min-w-0 justify-center overflow-hidden bg-background text-foreground",children:jsxRuntimeExports.jsx("div",{className:bodyClass,children:n})});if(r==="page")return jsxRuntimeExports.jsxs("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"page",...a,className:"pod-sign-in grid min-h-[100dvh] w-full bg-background text-foreground md:grid-cols-2",children:[h?jsxRuntimeExports.jsx("aside",{"data-pod-sign-in":"intro",className:"hidden flex-col justify-center gap-6 bg-[hsl(var(--sunken))] px-12 py-10 md:flex",children:h}):null,jsxRuntimeExports.jsx("div",{className:cn("flex min-w-0 items-center justify-center px-4 py-8",h?"":"md:col-span-2"),children:jsxRuntimeExports.jsx("div",{className:cn(bodyClass,"min-h-[520px]"),children:n})})]});const p=jsxRuntimeExports.jsxs("div",{ref:l,role:d?"dialog":"region","aria-modal":d?!0:void 0,"aria-label":e,tabIndex:-1,"data-pod-sign-in-frame":"dialog",...a,className:cn("pod-sign-in relative flex min-h-[min(440px,90dvh)] max-h-[90dvh] w-[min(480px,calc(100vw-2rem))] flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground shadow-lg focus:outline-none motion-safe:animate-in motion-safe:fade-in-0"),children:[d&&s&&o?jsxRuntimeExports.jsx("button",{type:"button","aria-label":o,className:"absolute right-2 top-2 flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",onClick:s,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null,jsxRuntimeExports.jsx("div",{className:cn(bodyClass,"mx-auto"),children:n})]});return d?jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center bg-background/80 p-4",children:p}):jsxRuntimeExports.jsx("div",{className:"flex w-full items-center justify-center p-4",children:p})}function StorageBadge({kind:r,label:e}){const t=r==="cloud"?Cloud:Laptop;return jsxRuntimeExports.jsx("span",{role:"img","aria-label":e,title:e,"data-storage-kind":r,className:"flex h-[18px] w-[18px] items-center justify-center rounded-full border border-background bg-card text-foreground",children:jsxRuntimeExports.jsx(t,{"aria-hidden":"true",className:"h-3 w-3"})})}const zhCN={restoring:"正在恢复登录…",enterApp:"进入 {app}",reauthenticate:"重新登录",useAnother:"使用其他账号",expiredLine:"登录已过期,需要重新确认",chooseTitle:"登录",chooseLead:"用你的 WebID 账号登录,数据保存在你自己的 Pod 里",useXpod:"使用 Xpod 账号登录",useOtherSolid:"使用其他 Solid 账号",customLabel:"账号服务地址或 WebID",customPlaceholder:"https://example.com/",customSubmit:"继续",noAccount:"没有账号?",register:"注册 Xpod",noticeDetailsToggle:"详情",noticeCopy:"复制",noticeCopied:"已复制",whatIsPod:"什么是 Pod?",whatIsPodBody:"Pod 是保存你数据的个人空间。",whatIsWebId:"什么是 WebID?",whatIsWebIdBody:"WebID 是登录用的身份,它指向你的个人资料和 Pod。",signInWith:"使用 {service} 登录",select:"选择",selected:"已选择",choosePodTitle:"选择 Pod",choosePodLead:"选择要继续使用的 Pod",retry:"重试",goCreate:"去创建",refreshPage:"刷新页面",startAndEnter:"启动 Xpod 并进入",openXpod:"打开 Xpod",noticeUnreachable:"暂时连不上 Xpod,请稍后再试",noticeIncomplete:"登录没有完成,请再试一次",noticeNoWebId:"还没有 WebID",noticeCancelled:"登录已取消",noticeLocalStopped:"这台电脑上的 Xpod 没有运行",noticePending:"上次登录尚未结束",serviceLabel:"账号服务",signInTitle:"登录 {service}",returnToApp:"完成后回到 {app}",email:"邮箱",password:"密码",forgotPassword:"忘记密码?",rememberDevice:"在这台设备上保持登录",signIn:"登录",registerLink:"注册账号",registerTitle:"注册 {service}",username:"用户名",registerSubmit:"注册",haveAccount:"已有账号?登录",podElsewhereSummary:"想用你自己的独立部署存放 Pod?",podElsewhereBody:"注册后,可以在账号页的“存储”里把 Pod 建到你自己的独立部署上;它和当前账号服务是分开的,普通浏览器不会自动把 Pod 转到本机。",noWebIdTitle:"还没有 WebID",noWebIdLead:"新建一个 WebID 来登录 {app},数据存在它的 Pod 里",webIdName:"WebID 名称",noWebIdLocation:"存放在当前服务",createAndContinue:"创建并继续",chooseOtherLocation:"存到边缘设备(打开账号页)",consentTitle:"授权 {app}",unverifiedWarning:"未能验证这个应用的来源,请确认是你要使用的应用",chooseWebId:"用哪个 WebID 登录?",consentConsequence:"{app} 将以这个身份读写你的数据,之后可以在 Xpod 中收回。",requestDetails:"请求详情",scopes:"权限范围",clientId:"应用标识",webIdFull:"WebID",rememberChoice:"以后不再询问",manageAccount:"管理账号",switchAccount:"换一个账号",deny:"拒绝",allow:"允许",storageCloud:"数据存在 Xpod 云端",storageEdge:"数据存在边缘设备上",hostedStorage:"账号服务托管",independentStorage:"独立部署",identityAddress:"WebID(身份地址)",storageAddress:"Pod(存储地址)",showAddresses:"查看地址",webIdSectionTitle:"WebID",webIdEmpty:"还没有 WebID。新建一个,用它登录应用。",createWebId:"新建 WebID",linkExistingWebId:"关联已有 WebID",podOnDevice:"Pod 在 {device}",authorizedApps:"已授权 {count} 个应用",createStepName:"名称",createStepLocation:"存放在",createNameHint:"WebID 地址",changeDevice:"更换 ›",cannotChangeLater:"创建后不能直接更换,以后要换请使用迁移",createPod:"创建 WebID 和 Pod",startDeviceXpod:"启动这台设备上的 Xpod",creatingNote:"关闭页面不会中断创建",cancel:"取消",devicePickerTitle:"选择存放设备",addDevice:"+ 添加设备",deviceSectionTitle:"设备",deviceStatusOk:"正常",deviceStatusUnreachable:"⚠ 其他设备访问不到",deviceStatusStopped:"Xpod 已停止",deviceStatusOffline:"离线",deviceCloud:"Xpod 云端",deviceEdge:"边缘",podCount:"{count} 个 Pod",networkAction:"网络",fixAction:"处理",collapseAction:"收起",webIdSectionHint:"登录应用时使用的身份,数据存在它的 Pod 里",deviceSectionHint:"Pod 可以存放的地方,网络设置跟着设备走",credentialSectionHint:"让脚本或服务以某个 WebID 直接访问 Pod",startAction:"启动",networkTitle:"网络访问",probeLocal:"这台电脑",probeLan:"局域网",probeWan:"其他网络",probeIdle:"未检测",probeChecking:"检测中",probeOk:"可以访问",probeFailed:"不通",tunnelTitle:"选择隧道",enableAndRecheck:"开启并重新检测",enableAndCheck:"开启并检测",recheck:"重新检测",skipForNow:"跳过,稍后设置",reachableVia:"通过 {tunnel} 可以访问",networkFootnote:"只影响其他设备;这台电脑上照常可用",addDeviceTitle:"添加设备",stepInstall:"安装并登录",stepNetwork:"检查网络",stepDone:"完成",joinThisComputer:"把这台电脑加入",installOnOther:"在那台设备上安装 Xpod 边缘并登录本账号",waitingForDevice:"正在等待新设备上线,登录后这里会自动继续",deviceOnline:"已上线",finish:"完成",useThisDevice:"用这台设备",credentialSectionTitle:"密钥",credentialEmpty:"还没有密钥。",createCredential:"新建密钥",revokeCredential:"删除",resumeTitle:"{app} 正在等你完成授权",resumeWaiting:"在下面新建一个 WebID,完成后就能回去授权",resumeReady:"WebID 已就绪,可以回去授权了",resumeCancel:"取消授权",resumeContinue:"继续授权 {app}",close:"关闭"},en={restoring:"Restoring your sign-in…",enterApp:"Open {app}",reauthenticate:"Sign in again",useAnother:"Use another account",expiredLine:"Your sign-in expired. Please confirm again.",chooseTitle:"Sign in",chooseLead:"Sign in with your WebID account. Your data stays in your own Pod.",useXpod:"Sign in with Xpod",useOtherSolid:"Use another Solid account",customLabel:"Sign-in service address or WebID",customPlaceholder:"https://example.com/",customSubmit:"Continue",noAccount:"No account?",register:"Register for Xpod",noticeDetailsToggle:"Details",noticeCopy:"Copy",noticeCopied:"Copied",whatIsPod:"What is a Pod?",whatIsPodBody:"A Pod is a personal space that holds your data.",whatIsWebId:"What is a WebID?",whatIsWebIdBody:"A WebID is the identity you sign in with. It points to your profile and your Pod.",signInWith:"Sign in with {service}",select:"Select",selected:"Selected",choosePodTitle:"Choose a Pod",choosePodLead:"Choose the Pod to continue with",retry:"Retry",goCreate:"Create one",refreshPage:"Refresh page",startAndEnter:"Start Xpod and open",openXpod:"Open Xpod",noticeUnreachable:"Cannot reach Xpod right now. Please try again later.",noticeIncomplete:"Sign-in did not finish. Please try again.",noticeNoWebId:"No WebID yet",noticeCancelled:"Sign-in cancelled",noticeLocalStopped:"Xpod is not running on this computer",noticePending:"The previous sign-in has not finished",serviceLabel:"Sign-in service",signInTitle:"Sign in to {service}",returnToApp:"You will return to {app}",email:"Email",password:"Password",forgotPassword:"Forgot password?",rememberDevice:"Keep me signed in on this device",signIn:"Sign in",registerLink:"Register",registerTitle:"Register for {service}",username:"Username",registerSubmit:"Register",haveAccount:"Already have an account? Sign in",podElsewhereSummary:"Want it on your own standalone deployment?",podElsewhereBody:"After registering, create the Pod on your own standalone deployment under Storage on the account page; it is separate from this account service.",noWebIdTitle:"No WebID yet",noWebIdLead:"Create a WebID to sign in to {app}. Your data lives in its Pod.",webIdName:"WebID name",noWebIdLocation:"Stored on the current service",createAndContinue:"Create and continue",chooseOtherLocation:"Store on an edge device (open account page)",consentTitle:"Authorize {app}",unverifiedWarning:"We could not verify this application. Make sure it is the one you meant to use.",chooseWebId:"Which WebID do you sign in with?",consentConsequence:"{app} will read and write your data as this identity. You can revoke it later in Xpod.",requestDetails:"Request details",scopes:"Permissions",clientId:"Application ID",webIdFull:"WebID",rememberChoice:"Do not ask again",manageAccount:"Manage account",switchAccount:"Switch account",deny:"Deny",allow:"Allow",storageCloud:"Data is stored on Xpod Cloud",storageEdge:"Data is stored on an edge device",hostedStorage:"Hosted by account service",independentStorage:"Independent deployment",identityAddress:"WebID (identity address)",storageAddress:"Pod (storage address)",showAddresses:"View addresses",webIdSectionTitle:"WebID",webIdEmpty:"No WebID yet. Create one to sign in to applications.",createWebId:"New WebID",linkExistingWebId:"Link an existing WebID",podOnDevice:"Pod on {device}",authorizedApps:"{count} authorized apps",createStepName:"Name",createStepLocation:"Store on",createNameHint:"WebID address",changeDevice:"Change ›",cannotChangeLater:"It cannot be changed directly after creation. Use migration later.",createPod:"Create WebID and Pod",startDeviceXpod:"Start Xpod on this device",creatingNote:"Closing this page will not interrupt creation",cancel:"Cancel",devicePickerTitle:"Choose where to store",addDevice:"+ Add device",deviceSectionTitle:"Devices",deviceStatusOk:"Healthy",deviceStatusUnreachable:"⚠ Not reachable from other devices",deviceStatusStopped:"Xpod stopped",deviceStatusOffline:"Offline",deviceCloud:"Xpod Cloud",deviceEdge:"Edge",podCount:"{count} Pods",networkAction:"Network",fixAction:"Fix",collapseAction:"Collapse",webIdSectionHint:"The identity you sign in to apps with. Your data lives in its Pod.",deviceSectionHint:"Places a Pod can live. Network settings follow the device.",credentialSectionHint:"Let a script or service reach a Pod directly as one WebID.",startAction:"Start",networkTitle:"Network access",probeLocal:"This computer",probeLan:"Local network",probeWan:"Other networks",probeIdle:"Not checked",probeChecking:"Checking",probeOk:"Reachable",probeFailed:"Unreachable",tunnelTitle:"Choose a tunnel",enableAndRecheck:"Enable and recheck",enableAndCheck:"Enable and check",recheck:"Recheck",skipForNow:"Skip, set up later",reachableVia:"Reachable through {tunnel}",networkFootnote:"Only affects other devices. This computer keeps working as usual.",addDeviceTitle:"Add a device",stepInstall:"Install and sign in",stepNetwork:"Check network",stepDone:"Done",joinThisComputer:"Add this computer",installOnOther:"Install Xpod Edge on that device and sign in to this account",waitingForDevice:"Waiting for the new device to come online. This continues automatically after sign-in.",deviceOnline:"Online",finish:"Done",useThisDevice:"Use this device",credentialSectionTitle:"Credentials",credentialEmpty:"No credentials yet.",createCredential:"New credential",revokeCredential:"Delete",resumeTitle:"{app} is waiting for you to finish authorizing",resumeWaiting:"Create a WebID below, then you can go back and authorize",resumeReady:"Your WebID is ready. You can go back and authorize.",resumeCancel:"Cancel authorization",resumeContinue:"Continue authorizing {app}",close:"Close"},podSignInCopy={"zh-CN":zhCN,en};function resolvePodSignInCopy(r="zh-CN",e){return{...podSignInCopy[r],...e}}function formatCopy(r,e){return r.replace(/\{(\w+)\}/g,(t,n)=>{const i=e[n];return i===void 0?t:String(i)})}function IdpChrome({serviceName:r,serviceHost:e,icon:t,serviceLabel:n,locale:i}){const s=n??resolvePodSignInCopy(i).serviceLabel;return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"idp-chrome",className:"flex min-h-14 shrink-0 items-center gap-3 border-b border-border bg-[hsl(var(--sunken))] px-6 py-2 text-[13px] text-foreground min-[400px]:px-8",children:[jsxRuntimeExports.jsx("span",{className:"flex shrink-0 items-center justify-center",children:t??jsxRuntimeExports.jsx(XpodMark,{size:24})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 max-w-[50%] shrink-0 truncate font-medium",children:[r," · ",s]}),e?jsxRuntimeExports.jsx("span",{className:"ml-auto truncate font-mono text-xs text-muted-foreground",children:e}):null]})}const primaryButtonClass="h-auto min-h-12 w-full whitespace-normal break-normal rounded-lg py-2 text-base font-medium leading-snug",outlineButtonClass=primaryButtonClass,textButtonClass="h-9 rounded-lg px-2 text-sm font-medium",fieldClass="h-12 w-full rounded-lg border border-input bg-card px-4 text-base text-foreground placeholder:text-muted-foreground disabled:opacity-60";function Spinner({className:r}){return jsxRuntimeExports.jsx(LoaderCircle$1,{"aria-hidden":"true",className:cn("h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none",r)})}function ActionButton({busy:r=!1,children:e,disabled:t,...n}){return jsxRuntimeExports.jsxs(Button,{type:"button",...n,disabled:t||r,"aria-busy":r||void 0,children:[r?jsxRuntimeExports.jsx(Spinner,{className:"mr-2"}):null,e]})}function SourceMark({icon:r,name:e}){return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"source",className:"flex h-6 items-center gap-2 text-[13px] text-muted-foreground",children:[r?jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"flex h-6 w-6 shrink-0 items-center justify-center overflow-hidden rounded-md",children:r}):null,jsxRuntimeExports.jsx("span",{className:"truncate",children:e})]})}function PodAvatar({name:r,avatarUrl:e,storage:t,size:n=56}){return jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0",style:{width:n,height:n},"data-pod-sign-in":"avatar",children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-full w-full rounded-full","aria-hidden":"true",children:[e?jsxRuntimeExports.jsx(AvatarImage,{src:e,alt:""}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"text-base",children:Array.from(r.trim())[0]?.toUpperCase()??"?"})]}),t?jsxRuntimeExports.jsx("span",{className:"absolute -bottom-0.5 -right-0.5",children:jsxRuntimeExports.jsx(StorageBadge,{kind:t.kind,label:t.label})}):null]})}function Field(r){return jsxRuntimeExports.jsx(FormField,{...r,"data-pod-sign-in":"field"})}function Disclosure({summary:r,children:e,className:t}){return jsxRuntimeExports.jsxs("details",{className:cn("text-[13px] text-muted-foreground",t),children:[jsxRuntimeExports.jsx("summary",{className:"cursor-pointer select-none rounded py-1 text-[13px] font-medium text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",children:r}),jsxRuntimeExports.jsx("div",{className:"pt-1 leading-5",children:e})]})}function CheckboxRow({checked:r,onChange:e,label:t,disabled:n}){return jsxRuntimeExports.jsxs("label",{className:"flex min-h-9 cursor-pointer items-center gap-2 text-sm text-foreground",children:[jsxRuntimeExports.jsx(Checkbox,{checked:r,disabled:n,onChange:i=>e(i.target.checked)}),t]})}function usePastDelay(r){const[e,t]=reactExports.useState(!1);return reactExports.useEffect(()=>{const n=setTimeout(()=>t(!0),r);return()=>clearTimeout(n)},[r]),e}function ScreenLayout({chrome:r,children:e,actions:t,onSubmit:n,mainClassName:i,...s}){const o=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[r,jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"main",className:cn("flex min-h-0 flex-1 flex-col gap-7 overflow-y-auto px-6 pb-3 pt-7 min-[400px]:px-8 min-[400px]:pt-8",i),children:e}),t?jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"actions",className:"flex shrink-0 flex-col gap-4 px-6 pb-7 pt-5 min-[400px]:px-8 min-[400px]:pb-8",children:t}):null]}),a="flex min-h-0 flex-1 flex-col";return n?jsxRuntimeExports.jsx("form",{...s,onSubmit:n,className:a,noValidate:!0,children:o}):jsxRuntimeExports.jsx("div",{...s,className:a,children:o})}function resolveIdpCopy({locale:r,copy:e}){return resolvePodSignInCopy(r,e)}function IdpFrameHeader({serviceName:r="Xpod",serviceHost:e,serviceIcon:t,locale:n,copy:i}){return jsxRuntimeExports.jsx(IdpChrome,{serviceName:r,serviceHost:e,icon:t,locale:n,serviceLabel:i?.serviceLabel})}const inputClass=fieldClass;function TextAction({href:r,onClick:e,disabled:t,className:n,children:i}){const s=cn(textButtonClass,"inline-flex shrink-0 items-center justify-center text-primary hover:underline",n);return r&&!t?jsxRuntimeExports.jsx("a",{href:r,className:s,children:i}):jsxRuntimeExports.jsx("button",{type:"button",className:s,disabled:t,onClick:e,children:i})}function IdpSignInView(r){const{serviceName:e,returnToAppName:t,error:n,fieldErrors:i,pending:s=!1,remember:o,defaultEmail:a="",defaultPassword:d="",onFieldChange:l,onRememberChange:h,onSubmit:p,onForgot:g,forgotHref:S,onRegister:y,registerHref:v,onUseOtherSolid:E}=r,w=resolveIdpCopy(r),[T,I]=reactExports.useState(a),[C,O]=reactExports.useState(d),P=D=>{D.preventDefault(),s||p({email:T.trim(),password:C})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-sign-in",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...r}),onSubmit:P,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[n?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:n}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:s,children:w.signIn}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[y||v?jsxRuntimeExports.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-1 gap-y-0",children:[jsxRuntimeExports.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:w.noAccount}),jsxRuntimeExports.jsx(TextAction,{href:v,disabled:s,onClick:y,children:w.registerLink})]}):jsxRuntimeExports.jsx("span",{}),E?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"text-primary hover:underline"),disabled:s,onClick:E,children:w.useOtherSolid}):null]})]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(w.signInTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(w.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"fields",className:"flex flex-col gap-5",children:[jsxRuntimeExports.jsx(Field,{label:w.email,error:i?.email,children:D=>jsxRuntimeExports.jsx(EmailInput,{...D,name:"email",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:T,disabled:s,onChange:Y=>{I(Y.target.value),l?.("email",Y.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:w.password,error:i?.password,labelAside:g||S?jsxRuntimeExports.jsx(TextAction,{className:"min-h-7 text-[13px]",href:S,onClick:g,children:w.forgotPassword}):void 0,children:D=>jsxRuntimeExports.jsx(Input,{...D,name:"password",type:"password",autoComplete:"current-password",className:inputClass,value:C,disabled:s,onChange:Y=>{O(Y.target.value),l?.("password",Y.target.value)}})}),h?jsxRuntimeExports.jsx(CheckboxRow,{checked:o,onChange:h,label:w.rememberDevice,disabled:s}):null]})]})}function IdpRegisterView(r){const{serviceName:e,returnToAppName:t,usernamePreview:n,requireUsername:i,fieldErrors:s,error:o,pending:a=!1,defaultEmail:d="",defaultPassword:l="",defaultUsername:h="",onFieldChange:p,onSubmit:g,onSignIn:S}=r,y=resolveIdpCopy(r),[v,E]=reactExports.useState(h),[w,T]=reactExports.useState(d),[I,C]=reactExports.useState(l),O=P=>{P.preventDefault(),!a&&g({...i?{username:v.trim()}:{},email:w.trim(),password:I})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-register",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...r}),onSubmit:O,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[o?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:o}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:a,children:y.registerSubmit}),S?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"self-center text-primary hover:underline"),disabled:a,onClick:S,children:y.haveAccount}):null]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(y.registerTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(y.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-5",children:[i?jsxRuntimeExports.jsx(Field,{label:y.username,error:s?.username,hint:n?jsxRuntimeExports.jsx("span",{role:"status",className:"font-mono text-xs",children:n}):void 0,children:P=>jsxRuntimeExports.jsx(Input,{...P,name:"username",type:"text",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:v,disabled:a,onChange:D=>{E(D.target.value),p?.("username",D.target.value)}})}):null,jsxRuntimeExports.jsx(Field,{label:y.email,error:s?.email,children:P=>jsxRuntimeExports.jsx(EmailInput,{...P,name:"email",autoComplete:"email",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:w,disabled:a,onChange:D=>{T(D.target.value),p?.("email",D.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:y.password,error:s?.password,children:P=>jsxRuntimeExports.jsx(Input,{...P,name:"password",type:"password",autoComplete:"new-password",className:inputClass,value:I,disabled:a,onChange:D=>{C(D.target.value),p?.("password",D.target.value)}})}),jsxRuntimeExports.jsx(Disclosure,{summary:y.podElsewhereSummary,children:y.podElsewhereBody})]})]})}const __iconNode$1=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],CircleAlert=createLucideIcon$1("circle-alert",__iconNode$1);const __iconNode=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle=createLucideIcon$1("loader-circle",__iconNode);function WebAccountLayout({title:r,description:e,children:t,host:n="document",bare:i=!1,intro:s,serviceIcon:o}){const a=reactExports.useId(),d=n==="window",l=d?"window":"page";return jsxRuntimeExports.jsx("main",{"data-testid":"web-account-page",className:d?"h-dvh w-full overflow-hidden":void 0,children:jsxRuntimeExports.jsx(PodSignInFrame,{presentation:d?"window":"page",ariaLabel:r,appIntro:s,dataAttributes:{"data-web-account-layout":l,"data-web-account-host":d?"window":"document"},children:jsxRuntimeExports.jsx("div",{"data-testid":"web-account-panel","data-web-account-layout":l,"data-web-account-host":d?"window":"document",className:"flex min-h-0 min-w-0 flex-1 flex-col",children:i?t:jsxRuntimeExports.jsxs(ScreenLayout,{chrome:jsxRuntimeExports.jsx(IdpChrome,{serviceName:"Xpod",serviceHost:window.location.host,icon:o}),children:[jsxRuntimeExports.jsxs("header",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{id:a,className:"text-[17px] font-semibold text-foreground",children:r}),e?jsxRuntimeExports.jsx("p",{className:"text-sm leading-[22px] text-muted-foreground",children:e}):null]}),t]})})})})}const introCopy={"zh-CN":{name:"Xpod 账号服务",proposition:"一个账号,管理你的 WebID 和它背后的 Pod。",points:[{title:"WebID 是你的身份",detail:"登录应用时使用它;数据存在你自己的 Pod 里。"},{title:"Pod 存在哪里由你决定",detail:"Xpod 云端或你自己的设备,创建后可以在这里查看。"},{title:"密钥按需签发",detail:"为脚本或服务单独创建凭据,不再需要就撤销。"}]},en:{name:"Xpod accounts",proposition:"One account for your WebID and the Pod behind it.",points:[{title:"Your WebID is your identity",detail:"Apps sign you in with it; your data stays in your own Pod."},{title:"You choose where the Pod lives",detail:"Xpod cloud or your own device, reviewable here after creation."},{title:"Credentials on demand",detail:"Issue a key per script or service, and revoke it when it is done."}]}};function XpodAccountServiceIntro({serviceHost:r,locale:e="zh-CN"}){const t=introCopy[e];return jsxRuntimeExports.jsxs("div",{"data-testid":"web-account-introduction",className:"flex max-w-[460px] flex-col gap-7",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(XpodMark,{size:44}),jsxRuntimeExports.jsx("span",{className:"text-[22px] font-semibold leading-none text-foreground",children:t.name})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"m-0 text-[28px] font-semibold leading-[38px] text-foreground",children:t.proposition}),r?jsxRuntimeExports.jsx("p",{className:"font-mono text-xs text-muted-foreground",children:r}):null]}),jsxRuntimeExports.jsx("ul",{className:"m-0 flex list-none flex-col gap-4 p-0",children:t.points.map(n=>jsxRuntimeExports.jsxs("li",{className:"flex gap-3",children:[jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"mt-2 h-2 w-2 shrink-0 rounded-full bg-primary"}),jsxRuntimeExports.jsxs("span",{className:"flex flex-col gap-0.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[15px] font-semibold text-foreground",children:n.title}),jsxRuntimeExports.jsx("span",{className:"text-sm leading-[22px] text-muted-foreground",children:n.detail})]})]},n.title))})]})}function parseIdentity(r){if(!r||typeof r!="object")throw new Error("Missing deployment identity");const e=r;if(e.edition!=="cloud"&&e.edition!=="local"||typeof e.managed!="boolean")throw new Error("Invalid deployment identity");let t;if(e.edition==="local"&&e.managed&&typeof e.oidcIssuer=="string"){const i=new URL(e.oidcIssuer);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||i.search||i.hash)throw new Error("Invalid account service");t=i.href.replace(/\/$/u,"")}let n;if(typeof e.publicUrl=="string"){const i=new URL(e.publicUrl);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||i.search||i.hash)throw new Error("Invalid public service address");n=i.href}return{edition:e.edition,managed:e.managed,oidcIssuer:t,publicUrl:n}}function XpodDeploymentIdentity({renderLogo:r,className:e}={}){const[t,n]=reactExports.useState();reactExports.useEffect(()=>{const o=new AbortController;return(async()=>{try{const a=await fetch("/api/service-info",{headers:{accept:"application/json"},cache:"no-store",signal:o.signal});if(!a.ok)throw new Error("Deployment identity unavailable");const d=parseIdentity(await a.json());o.signal.aborted||n(d)}catch{o.signal.aborted||n(null)}})(),()=>o.abort()},[]);const i=t?t.edition==="cloud"?"云端":t.managed?"托管部署":"独立部署":t===null?"部署信息暂不可用":"正在识别部署…",s=r?r(i):jsxRuntimeExports.jsxs("span",{"data-testid":"xpod-deployment-logo",className:"inline-flex flex-col items-center gap-0.5",children:[jsxRuntimeExports.jsx(XpodMark,{size:24}),jsxRuntimeExports.jsx("span",{className:"text-[8px] font-medium leading-none text-primary",children:t?i:t===null?"未知":"…"}),t?null:jsxRuntimeExports.jsx("span",{className:"sr-only",children:i})]});return jsxRuntimeExports.jsx("div",{"data-testid":"xpod-deployment-identity",className:e,children:jsxRuntimeExports.jsx(BrandInfo,{logo:s,infoLabel:"部署详情",info:jsxRuntimeExports.jsxs("div",{className:"space-y-2 leading-relaxed",children:[jsxRuntimeExports.jsx("p",{className:"font-semibold",children:"部署详情"}),t?jsxRuntimeExports.jsxs("p",{children:["部署类型:",t.edition==="cloud"?"Cloud":t.managed?"Local · 云端托管":"Local · 独立部署"]}):jsxRuntimeExports.jsx("p",{children:i}),jsxRuntimeExports.jsxs("p",{children:["当前访问:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:window.location.origin})]}),t?jsxRuntimeExports.jsxs("p",{children:[t.edition==="local"?"节点地址":"服务地址",":",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.publicUrl??(t.managed?"尚未分配":"尚未配置")})]}):null,t?.oidcIssuer&&t.oidcIssuer!==window.location.origin?jsxRuntimeExports.jsxs("p",{children:["账号服务:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.oidcIssuer})]}):null]})})})}function XpodAuthSurface(r){const e=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(e==="window"),jsxRuntimeExports.jsx(AuthSurface,{...r,presentation:"compact",host:e})}function XpodSignInFrame({ariaLabel:r,children:e}){const t=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(t==="window"),jsxRuntimeExports.jsx(PodSignInFrame,{presentation:t==="window"?"window":"page",ariaLabel:r,children:e})}function XpodAccountPageSurface({title:r,children:e,bare:t=!1,intro:n,presentation:i="compact"}){const s=getXpodAuthSurfaceHost(),o=i==="compact";return useXpodAuthWindowSurface(s==="window",o?"account":"workspace"),jsxRuntimeExports.jsx(WebAccountLayout,{title:r,host:o?s:"document",bare:t,intro:n??jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),children:e})}function credentialViewCopy(r){return{email:r.emailLabel,password:r.passwordLabel,username:r.usernameLabel,signIn:r.loginAction,registerSubmit:r.registerAction,rememberDevice:"记住账号"}}function XpodBlockingAccountCredentialsSurface(r){const e=getXpodAuthSurfaceHost(),t=r.mode!=="register";useXpodAuthWindowSurface(e==="window",t?"account":"workspace");const{mode:n,values:i,onChange:s,onSubmit:o,onFieldChange:a,onModeChange:d,rememberAccount:l=!0,onRememberAccountChange:h,pending:p=!1,errors:g,copy:S,surfaceTitle:y,footer:v,onForgot:E,onRegister:w,forgotHref:T,registerHref:I}=r,C={serviceName:"Xpod",serviceHost:window.location.host,serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),copy:credentialViewCopy(S)},O=(P,D)=>{s({...i,[P]:D}),a?.(P,D)};return jsxRuntimeExports.jsxs(WebAccountLayout,{title:y,host:t?e:"document",bare:!0,intro:jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),children:[n==="register"?jsxRuntimeExports.jsx(IdpRegisterView,{...C,requireUsername:!1,pending:p,defaultEmail:i.email,defaultPassword:i.password,error:g?.form,fieldErrors:{email:g?.email,password:g?.password},onFieldChange:O,onSubmit:P=>{o({...i,...P})},onSignIn:d?()=>d("login"):void 0}):jsxRuntimeExports.jsx(IdpSignInView,{...C,pending:p,remember:l,defaultEmail:i.email,defaultPassword:i.password,error:g?.form,fieldErrors:{email:g?.email,password:g?.password},onFieldChange:O,onRememberChange:h,onSubmit:P=>{o({...i,...P})},onForgot:E,forgotHref:T,registerHref:I,onRegister:w??(d?()=>d("register"):void 0)}),v?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:v}):null]})}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(r=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(r));for(let n=0;n<r;n++)e+=urlAlphabet[t[n]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<r;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=r=>typeof r=="object"&&r!==null&&typeof r.value=="string",hasTermValue=r=>typeof r=="object"&&r!==null&&typeof r.term=="object"&&r.term!==null&&typeof r.term?.value=="string",resolveTermIri=r=>{if(typeof r=="string")return r;if(hasStringValue$2(r))return r.value;if(hasTermValue(r))return r.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is$1(r,e){if(!r||typeof r!="object")return!1;if(r instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=r.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:n,query:i}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:n,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,n,i=!1){this[SubqueryConfig]={sql:e,selection:t,alias:n,isWith:i}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const i=(is$1(e,Subquery)?e[SubqueryConfig].selection:is$1(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is$1(i,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;const s=i.clone();return s.isSelectionField=!0,s}if(is$1(i,SQL)){if(this.config.sqlBehavior==="sql")return i;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is$1(i,Column)?this.config.alias?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(i.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):i:typeof i!="object"||i===null?i:new Proxy(i,new SelectionProxyHandler(this.config))}}function orderSelectedFields(r,e){return Object.entries(r).reduce((t,[n,i])=>{if(typeof n!="string")return t;const s=e?[...e,n]:[n];return is$1(i,Column)||is$1(i,SQL)||is$1(i,SQL.Aliased)?t.push({path:s,field:i}):is$1(i,Table)?t.push(...orderSelectedFields(i[Table.Symbol.Columns],s)):t.push(...orderSelectedFields(i,s)),t},[])}function applyMixins(r,e){for(const t of e)for(const n of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(r.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n)||Object.create(null))}function getTableLikeName(r){return is$1(r,Subquery)?r[SubqueryConfig].alias:is$1(r,View)?r[ViewBaseConfig].name:is$1(r,SQL)?void 0:r[Table.Symbol.IsAlias]?r[Table.Symbol.Name]:r[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,n){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=n}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(r,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:n,session:i,dialect:s,withList:o,distinct:a}){super(),this.config={withList:o,table:e,fields:{...t},distinct:a},this.isPartialSelect=n,this.session=i,this.dialect=s,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,n)=>{const i=this.tableName,s=getTableLikeName(t);if(typeof s=="string"&&this.config.joins?.some(o=>o.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i=="string"&&(this.config.fields={[i]:this.config.fields}),typeof s=="string"&&!is$1(t,SQL))){const o=is$1(t,Subquery)?t[SubqueryConfig].selection:is$1(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[s]=o}if(typeof n=="function"&&(n=n(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:t,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:n,dialect:i,joinsNotNullableMap:s}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const o=orderSelectedFields(n.fields),a=t.prepareQuery(i.sqlToQuery(this.getSQL()),o,e);return a.joinsNotNullableMap=s,a})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(r){return typeof r=="object"&&r!==null&&"getSQL"in r&&typeof r.getSQL=="function"}function mergeQueries(r){const e={sql:"",params:[]};for(const t of r)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,t){const n=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:i,escapeParam:s,prepareTyping:o,inlineParams:a,paramStartIndex:d}=n;return mergeQueries(e.map(l=>{if(is$1(l,StringChunk))return{sql:l.value.join(""),params:[]};if(is$1(l,Name))return{sql:i(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){const h=[new StringChunk("(")];for(const[p,g]of l.entries())h.push(g),p<l.length-1&&h.push(new StringChunk(", "));return h.push(new StringChunk(")")),this.buildQueryFromSourceParams(h,n)}if(is$1(l,SQL))return this.buildQueryFromSourceParams(l.queryChunks,{...n,inlineParams:a||l.shouldInlineParams});if(is$1(l,Table)){const h=l[Table.Symbol.Schema],p=l[Table.Symbol.Name];return{sql:h===void 0?i(p):i(h)+"."+i(p),params:[]}}if(is$1(l,Column))return{sql:i(l.table[Table.Symbol.Name])+"."+i(l.name),params:[]};if(is$1(l,View)){const h=l[ViewBaseConfig].schema,p=l[ViewBaseConfig].name;return{sql:h===void 0?i(p):i(h)+"."+i(p),params:[]}}if(is$1(l,Param)){const h=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(is$1(h,SQL))return this.buildQueryFromSourceParams([h],n);if(a)return{sql:this.mapInlineParam(h,n),params:[]};let p;return o!==void 0&&(p=[o(l.encoder)]),{sql:s(d.value++,h),params:[h],typings:p}}return is$1(l,Placeholder)?{sql:s(d.value++,l),params:[l]}:is$1(l,SQL.Aliased)&&l.fieldAlias!==void 0?{sql:i(l.fieldAlias),params:[]}:is$1(l,Subquery)?l[SubqueryConfig].isWith?{sql:i(l[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),l[SubqueryConfig].sql,new StringChunk(") "),new Name(l[SubqueryConfig].alias)],n):isSQLWrapper(l)?this.buildQueryFromSourceParams([new StringChunk("("),l.getSQL(),new StringChunk(")")],n):is$1(l,Relation)?this.buildQueryFromSourceParams([l.sourceTable,new StringChunk("."),sql.identifier(l.fieldName)],n):a?{sql:this.mapInlineParam(l,n),params:[]}:{sql:s(d.value++,l),params:[l]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const n=e.toString();return t(n==="[object Object]"?JSON.stringify(e):n)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:r=>r},noopEncoder={mapToDriverValue:r=>r};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(r,...e){const t=[];(e.length>0||r.length>0&&r[0]!=="")&&t.push(new StringChunk(r[0]));for(const[n,i]of e.entries())t.push(i,new StringChunk(r[n+1]));return new SQL(t)}(function(r){function e(){return new SQL([])}r.empty=e;function t(d){return new SQL(d)}r.fromList=t;function n(d){return new SQL([new StringChunk(d)])}r.raw=n;function i(d,l){const h=[];for(const[p,g]of d.entries())p>0&&l!==void 0&&h.push(l),h.push(g);return new SQL(h)}r.join=i;function s(d){return new Name(d)}r.identifier=s;function o(d){return new Placeholder(d)}r.placeholder=o;function a(d,l){return new Param(d,l)}r.param=a})(sql||(sql={}));(function(r){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(n,i){this.sql=n,this.fieldAlias=i}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}r.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const i=e[Table.Symbol.Columns];if(!i)return i;const s={};return Object.keys(i).map(o=>{s[o]=new Proxy(i[o],new ColumnAliasProxyHandler(new Proxy(e,this)))}),s}const n=e[t];return is$1(n,Column)?new Proxy(n,new ColumnAliasProxyHandler(new Proxy(e,this))):n}}var _a$b;class ColumnBuilder{constructor(e,t,n={},i,s){this.name=e,this.dataType=t,this.options={...n},this._predicateUri=i,this.elementType=s??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,n={},i){this.name=e,this.dataType=t,this.options=n,this.tableName=i}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,n={}){super(e,"array",n),this.elementType=t}}function boolean$2(r,e={}){return new ColumnBuilder(r,"boolean",e)}function timestamp(r,e={}){return new ColumnBuilder(r,"datetime",e)}function json(r,e={}){return new ColumnBuilder(r,"json",e)}function object$1(r,e={}){return new ColumnBuilder(r,"object",e)}function uri(r,e={}){return new ColumnBuilder(r,"uri",e)}function id(r="id",e={}){const t=new PodStringColumn(r,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(r,e={}){return new ColumnBuilder(r,"string",e)}function integer$1(r,e={}){return new ColumnBuilder(r,"integer",e)}function date$3(r,e={}){return new ColumnBuilder(r,"datetime",e)}function text(r,e={}){return new ColumnBuilder(r,"string",e)}function real(r,e={}){return new ColumnBuilder(r,"integer",e)}function validateColumnOverride(r,e,t){const n=r.getPredicateUri?.()??r.options?.predicate,i=e.options?.predicate;if(n&&i&&n!==i)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${i}",子 schema 尝试改为 "${n}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(r,e){const t={};for(const[n,i]of Object.entries(r.columns))t[n]=i;for(const[n,i]of Object.entries(e)){const s=r.columns[n];if(s&&!(i instanceof PodColumnBase)){validateColumnOverride(i,s,n);const o=i;!o.getPredicateUri?.()&&!o.options?.predicate&&(o.options={...o.options,predicate:s.options?.predicate})}t[n]=i}return t}function renderDefaultIdTemplate(r,e){if(!/\{[^{}]+\}/.test(r))return r;if(/\{\s*id\s*\}/.test(r))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},n=resolveDate(t,e.now),i={yyyy:String(n.getUTCFullYear()),MM:String(n.getUTCMonth()+1).padStart(2,"0"),dd:String(n.getUTCDate()).padStart(2,"0")};return r.replace(/\{([^{}]+)\}/g,(s,o)=>{const a=o.trim();if(a==="key")return e.key;if(a==="yyyy")return i.yyyy;if(a==="MM")return i.MM;if(a==="dd")return i.dd;const d=resolveExpression(a,t,e);return d==null?"":String(d)})}function resolveDate(r,e=new Date){const t=r.createdAt??r.favoredAt??r.indexedAt??e,n=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(n.getTime())?n:e}function resolveExpression(r,e,t){const n=parseExpression(r);let i=resolveTemplatePath(n.path,e,t);for(const s of n.transforms)i=applyTransform(i,s,n.path,t);return n.selector?applyPathSelector(i,n.selector):i}function parseExpression(r){const e=r.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():r,[n,...i]=t.split("|").map(s=>s.trim()).filter(Boolean);return{path:n??r,transforms:i,selector:e?.[2]?.trim()}}function resolveTemplatePath(r,e,t){const n=r.split("."),i=n[0];return n.reduce((s,o,a)=>{if(typeof s=="string")return i?resolveResourceProperty(s,i,o,t):void 0;if(!(!s||typeof s!="object"))return i&&isResourceProperty(o)&&!((o==="id"||o==="key")&&o in s)?resolveResourceProperty(s,i,o,t):a>0&&o==="id"&&readRef(s)?extractResourceId(s,i??"",t):s[o]},e)}function isResourceProperty(r){return r==="id"||r==="key"||r==="doc"||r==="document"||r==="dir"||r==="owner"}function resolveResourceProperty(r,e,t,n){if(t==="id")return extractResourceId(r,e,n);const i=extractResourceId(r,e,n);if(i){if(t==="key"){const s=extractTemplateValuesForField(r,e,n);return s?.key??s?.id??deriveResourceKey(i)}if(t==="doc"||t==="document")return resourceDocument(i);if(t==="dir"||t==="owner")return deriveOwnerDir(i)}}function applyTransform(r,e,t,n){if(e==="slug")return slugifyValue(String(r??""));const i=extractResourceId(r,t,n);if(e==="resource")return i;if(e==="document")return i?resourceDocument(i):"";if(e==="owner")return i?deriveOwnerDir(i):"";const s=extractTemplateValuesForField(r,t,n);return e==="id"?s?.id??s?.key??i??"":s?.[e]??""}function extractResourceId(r,e,t){const n=readRef(r);if(!n)return null;const i=resolveLinkedResource(e,t);if(!i)return normalizePodDataResourceId$1(n);if(!isCompleteResourceId$1(n))return renderLinkedResourceId(i,n);const s=relativeSubjectFromRef$1(i,n);return normalizePodDataResourceId$1(s??n)}function extractTemplateValuesForField(r,e,t){const n=readRef(r);if(!n)return null;const i=resolveLinkedResource(e,t);if(!i)return null;const s=relativeSubjectFromRef$1(i,n)??(isCompleteResourceId$1(n)?null:renderLinkedResourceId(i,n));if(!s)return null;const o=resourceTemplate(i);return o?extractVarsFromTemplate(normalizePodDataResourceId$1(s),o):{id:normalizePodDataResourceId$1(s)}}function resolveLinkedResource(r,e){const t=e.links?.[r];if(t)return t;const n=e.resource?.columns?.[r];return n?.getLinkTable?.()??n?.options?.linkTable??null}function resourceTemplate(r){const e=r.getSubjectTemplate?.()??r.config?.subjectTemplate;if(e)return e;const t=r.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(r,e){const t=resourceTemplate(r);if(!t)return e;const n=r.columns?.id?.options?.defaultValue;return typeof n=="function"?String(n(e,{})):t.replace(/\{([^}]+)\}/g,(i,s)=>{const o=parseTemplateField(s);return o==="id"||o==="key"?e:""})}function readRef(r){if(typeof r=="string"&&r.length>0)return r;if(!r||typeof r!="object")return null;const e=r,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(r){return normalizeResourcePath$1(r.getResourcePath?.()??r.config?.base??"")}function relativeSubjectFromRef$1(r,e){const t=resourcePath(r);if(!t)return normalizePodDataResourceId$1(e);const n=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const i of n){const s=e.indexOf(i);if(s<0)continue;let o=e.slice(s+i.length);return o.startsWith("/")&&(o=o.slice(1)),o.length>0?o:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(r,e){let t=0;const n=new Map,i=[];let s=0;for(const a of e.matchAll(/\{([^}]+)\}/g)){i.push(escapeRegExp$1(e.slice(s,a.index)));const d=`var${t++}`;n.set(d,parseTemplateField(a[1]??"")),i.push(`(?<${d}>.+?)`),s=a.index+a[0].length}i.push(escapeRegExp$1(e.slice(s)));const o=i.join("");try{const a=r.match(new RegExp(`^${o}$`));if(!a?.groups)return null;const d={};for(const[l,h]of Object.entries(a.groups)){const p=n.get(l);!p||h===void 0||(d[p]=decodeURIComponent(h))}return d}catch{return null}}function parseTemplateField(r){const e=r.split("|").map(n=>n.trim()).filter(Boolean)[0]??r,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(r){return r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(r,e){const t=splitResourcePath(r);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const n=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!n)throw new Error(`Invalid id default path selector [${e}]`);const i=n[1]===""?0:normalizeSliceIndex(Number(n[1]),t.length),s=n[2]===""?t.length:normalizeSliceIndex(Number(n[2]),t.length);return t.slice(i,s).join("/")}function splitResourcePath(r){const e=readRef(r);if(!e)return null;const t=normalizePodDataResourceId$1(e),[n,i]=t.split("#"),s=(n??t).split("/").filter(Boolean);return i&&s.push(i),s}function normalizePodDataResourceId$1(r){const e=r.indexOf("#"),[t,n=""]=e>=0?[r.slice(0,e),r.slice(e)]:[r,""],i=t.indexOf("/.data/");return`${i>=0?t.slice(i+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${n}`}function normalizeResourcePath$1(r){return r.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(r){return/^https?:\/\//u.test(r)||r.startsWith("/")||r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(r)}function deriveOwnerDir(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#"),n=t>=0?e.slice(0,t):e,i=t>=0?e.slice(t+1):"",s=n.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(s?.[1])return s[1];if(n==="task/index.ttl"&&i&&i!=="this")return`task/${i}`;const o=n.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(o?.[1])return o[1];const a=n.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(a?.[1])return a[1];const d=n.split("/").filter(Boolean);return d.length>1?d.slice(0,-1).join("/"):n}function resourceDocument(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#");if(t>=0){const a=e.slice(t+1);if(a&&a!=="this"&&a!=="me"&&a!=="it")return a}const n=resourceDocument(e).replace(/\/+$/u,""),i=n.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(i?.[1])return i[1];const s=n.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const o=n.split("/").filter(Boolean);return o.length>0?o[o.length-1]:e}function slugifyValue(r){return r.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(r,e){return r<0?e+r:r}function normalizeSliceIndex(r,e){const t=r<0?e+r:r;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(r){const e=r.split("|").map(n=>n.trim()).filter(Boolean)[0]??r,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(r){return r.trim().replace(/^(\.\/)+/,"")}function podResourcePath(r){return normalizeResourcePath(r.getResourcePath?.()??r.config?.base??"")}function podResourceSubjectTemplate(r){return r.getSubjectTemplate?.()??r.config?.subjectTemplate}function podResourceIdDefaultTemplate(r){const e=r.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(r){const e=podResourcePath(r),t=normalizeResourcePath(r.getContainerPath?.()??r.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(r,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(r);return t?`${t}${e}`:e}function templateRelativeSubject(r,e){if((podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r))?.startsWith("#")&&!e.startsWith("#")){const n=e.indexOf("#");if(n>=0)return e.slice(n)}return e}function isBaseRelativeSubjectId$1(r){return!r||/^https?:\/\//.test(r)||r.startsWith("/")?!1:r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(r)}function isTemplateCompleteResourceId(r,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r);return t?extractTemplateValues(templateRelativeSubject(r,e),t)!==null:!1}function isResourceRelativeSubjectId(r,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(r,e)}function relativeSubjectFromRef(r,e){const t=podResourcePath(r);if(!t)return null;const n=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const i of n){const s=e.indexOf(i);if(s<0)continue;let o=e.slice(s+i.length);if(o.startsWith("/")&&(o=o.slice(1)),o.length>0)return o}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(r,e)?normalizeResourcePath(e):null}function extractTemplateValues(r,e){if(!e.includes("{"))return r===e?{}:null;let t=0;const n=new Map,i=[];let s=0;for(const a of e.matchAll(/\{([^}]+)\}/g)){i.push(escapeRegExp(e.slice(s,a.index)));const d=`var${t++}`;n.set(d,parseTemplateVariableField$1(a[1]??"")),i.push(`(?<${d}>.+?)`),s=a.index+a[0].length}i.push(escapeRegExp(e.slice(s)));const o=`^${i.join("")}$`;try{const a=r.match(new RegExp(o));if(!a?.groups)return null;const d={};for(const[l,h]of Object.entries(a.groups)){const p=n.get(l);if(!p||h===void 0)continue;const g=decodeURIComponent(h);if(p in d&&d[p]!==g)return null;d[p]=g}return d}catch{return null}}function escapeRegExp(r){return r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(r,e){if(!e)return null;const t=relativeSubjectFromRef(r,e);if(!t)return null;const n=qualifyFragmentResourceId(r,t),i=podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r),s=i?extractTemplateValues(templateRelativeSubject(r,n),i):{id:decodeURIComponent(n)};return s?{resourceId:decodeURIComponent(n),templateValues:s}:null}function extractPodResourceTemplateValue(r,e,t="id"){return parsePodResourceRef(r,e)?.templateValues[t]??null}function resolvePodBaseUrl(r){const e=r.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(r){if(!r||typeof r!="object")return null;const e=r,t=typeof e.getDialect=="function"?e.getDialect():null,n=readPodUrl(t);if(n)return resolvePodBaseUrl(n);const i=typeof e.getSession=="function"?e.getSession():e.session,s=readPodUrl(i);if(s)return resolvePodBaseUrl(s);const o=readWebId(i);return o&&o.includes("/profile/card#me")?resolvePodBaseUrl(o):null}function normalizePodDataResourceId(r){const e=r.indexOf("#"),[t,n=""]=e>=0?[r.slice(0,e),r.slice(e)]:[r,""],i=t.indexOf("/.data/");return`${i>=0?t.slice(i+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${n}`}function resolvePodResourceId(r,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(r,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(r,e),normalizePodDataResourceId(e);const n=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!n)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(n)||isTemplateCompleteResourceId(r,n))return normalizePodDataResourceId(n);const i=resolveDefaultResourceId(r,n,e);if(i)return normalizePodDataResourceId(i);const s=podResourceSubjectTemplate(r);return normalizePodDataResourceId(s?renderSubjectTemplateResourceId(s,n,e):n)}function buildPodResourceIri(r,e){const t=resolvePodBaseUrl(r);if(!t||/^https?:\/\//u.test(e))return e;const n=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(n.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(r,e,t){const n=resolveKnownTargetIri(t);if(n)return n;const i=resolvePodRootTargetPath(t);if(i)return buildPodResourceIri(r,i);const s=resolvePodResourceId(e,t),o=isResourceRelativeSubjectId(e,s)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(s)}`:e.resolveUri?.(s)??`/.data/${normalizePodDataResourceId(s)}`;return buildPodResourceIri(r,o)}function buildPodResourceIriForDatabase(r,e,t){const n=resolvePodBaseUrlFromDatabase(r);if(!n)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(n,e,t)}function resolvePodResourceIriForDatabase(r,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(r,e,t)}catch{return null}}function resolveKnownTargetIri(r){if(typeof r=="string")return/^https?:\/\//u.test(r)?r:null;const e=r["@id"]??r.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(r){if(typeof r=="string")return r.startsWith("/")?r:null;const e=typeof r.id=="string"?r.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(r){return/^https?:\/\//u.test(r)||r.startsWith("/")||r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(r)}function assertCompleteStringResourceId(r,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(r,e))return;const t=r.columns?.id?.options?.defaultValue!==void 0,n=podResourceSubjectTemplate(r);if(t||n)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(r,e,t){const n=r.columns?.id?.options?.defaultValue;if(n===void 0)return null;if(typeof n=="string")return renderDefaultIdTemplate(n,{key:e,row:t,resource:r});if(typeof n!="function")return String(n);const i=n;return i.length===0?String(i()):String(i(e,t))}function renderSubjectTemplateResourceId(r,e,t){const n=r.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(n,{key:encodeURIComponent(e),row:t})}function readPodUrl(r){if(!r||typeof r!="object")return null;const e=r,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(r){if(!r||typeof r!="object")return null;const e=r,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,n){this.initialized=!1;const i=n.type;if(!i)throw new Error("podTable requires a type (RDF class) via options.type");const s=n.typeIndex,o=s==="private"||s==="public",a=this.resolveBase(n.base,e);this.resourcePath=a.resourcePath,this.containerPath=a.containerPath;const d=this.resolveSubjectTemplate(n.subjectTemplate,a.resourcePath,a.containerPath,e);this.subjectTemplate=d.template,this.hasCustomSubjectTemplate=d.isCustom,this.resourceMode=n.resourceMode??(n.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=n.sparqlEndpoint,this.registerTypeIndexEnabled=o&&n.autoRegister!==!1,this.config={name:e,base:a.resourcePath,type:resolveTermIri(i),namespace:n.namespace,typeIndex:o?s:void 0,saiRegistryPath:n.saiRegistryPath,autoRegister:n.autoRegister,containerPath:a.containerPath,hooks:n.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(n.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let l=0;for(const h of Object.values(t))if(h.options.primaryKey&&l++,h.table=this,h.tableName=e,!h.options.predicate&&!h._virtualId&&!n.namespace)throw new Error(`Column "${h.name}" in table "${e}" is missing a predicate.`);if(l!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${l}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const n=t.replace(/\{id\}/g,e);return n.startsWith("#")?`${this.resourcePath}${n}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${n}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const n=this.normalizeBaseInput(e),i=this.normalizeResourcePath(n);if(i.endsWith("/")){const o=this.ensureTrailingSlash(i);return{resourcePath:o,containerPath:o}}const s=this.ensureTrailingSlash(this.deriveContainerPath(i));return{resourcePath:i,containerPath:s}}normalizeBaseInput(e){const t=e.trim(),n=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(n){const[,i,s]=n,o=i.toLowerCase(),a=s.trim();return o==="http"||o==="https"?`${o}://${a}`:a.startsWith("/")?a:`/${a}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const n=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return n.startsWith("/")?n:`/${n}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n===-1?"/":t.slice(0,n+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,n,i){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const n=(Array.isArray(e)?e:[e]).map(i=>resolveTermIri(i)).filter(i=>i&&i.length>0);return Array.from(new Set(n))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(r,e,t){const n={};for(const[i,s]of Object.entries(e)){if(s instanceof PodColumnBase){n[i]=s;continue}let o;switch(s.dataType){case"integer":o=new PodIntegerColumn(s.name,s.options);break;case"datetime":o=new PodDateTimeColumn(s.name,s.options);break;case"boolean":o=new PodBooleanColumn(s.name,s.options);break;case"json":o=new PodJsonColumn(s.name,s.options);break;case"object":o=new PodObjectColumn(s.name,s.options);break;case"array":{const d=s.elementType??s.options.baseType??"string";o=new PodArrayColumn(s.name,d,s.options);break}case"uri":o=new PodUriColumn(s.name,s.options);break;default:o=new PodStringColumn(s.name,s.options);break}const a=s.getPredicateUri?.();a&&o.predicate(a),n[i]=o}return new PodTable(r,n,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const n=mergeSchemaColumns(this,e),i=[this.type];return this.subClassOf&&i.push(...this.subClassOf),solidSchema(n,{...t,subClassOf:i})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(r,e){const t={};for(const[n,i]of Object.entries(r)){if(i instanceof PodColumnBase){t[n]=i;continue}let s;switch(i.dataType){case"integer":s=new PodIntegerColumn(i.name,i.options);break;case"datetime":s=new PodDateTimeColumn(i.name,i.options);break;case"boolean":s=new PodBooleanColumn(i.name,i.options);break;case"json":s=new PodJsonColumn(i.name,i.options);break;case"object":s=new PodObjectColumn(i.name,i.options);break;case"array":{const a=i.elementType??i.options.baseType??"string";s=new PodArrayColumn(i.name,a,i.options);break}case"uri":s=new PodUriColumn(i.name,i.options);break;default:s=new PodStringColumn(i.name,i.options);break}const o=i.getPredicateUri?.();o&&s.predicate(o),t[n]=s}return new SolidSchema(t,e)}function isSolidSchema(r){return r instanceof SolidSchema||r?.$kind==="SolidSchema"}const XSD$8="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(r,e){if(!r)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const i=e.getMapping()?.columns?.[r.name];if(i?.predicate)return i.predicate}if(typeof r.getPredicateUri=="function")return r.getPredicateUri();if(r._predicateUri)return r._predicateUri;if(r.predicate&&typeof r.predicate=="string")return r.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof r.getPredicate=="function")try{return r.getPredicate(t)}catch{}return r.options?.predicate?r.options.predicate:t?`${typeof t=="string"?t:t.uri}${r.name}`:(r.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",r),`http://example.org/${r.name}`)}function formatValue(r,e,t,n){return Array.isArray(r)?r.map(i=>formatSingleValue(i,e,t,n)):formatSingleValue(r,e,t,n)}function formatSingleValue(r,e,t,n){if(r==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const i=String(r);if(i.startsWith("<")&&i.endsWith(">")){const s=i.slice(1,-1);return t&&!t.isAbsoluteUri(s)?`<${t.resolveLink(s,e,n)}>`:i}return t?`<${t.resolveLink(i,e,n)}>`:i.startsWith("<")?i:`<${i}>`}return typeof r=="string"?!e&&(r.startsWith("http://")||r.startsWith("https://"))?`<${r}>`:`"${r.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof r=="number"?Number.isInteger(r)?String(r):`"${r}"^^<${XSD$8}decimal>`:typeof r=="boolean"?`"${r}"^^<${XSD$8}boolean>`:r instanceof Date?`"${r.toISOString()}"^^<${XSD$8}dateTime>`:`"${String(r)}"`}function resolveColumn(r,e){if(r&&typeof r=="object"&&r instanceof PodColumnBase)return r;if(r&&typeof r=="object"&&"name"in r){const t=r.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof r=="string"){const t=e.columns[r];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(r)}`)}function generateSubjectUri(r,e,t){const n=t.resolveSubject(e,r);if(!n)throw new Error("Failed to generate subject URI");return n}var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,n){super(),this.left=e,this.operator=t,this.right=n,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(r,e){return new BinaryExpression(r,"=",e)}function like(r,e){return new BinaryExpression(r,"LIKE",e)}function inArray(r,e){return new BinaryExpression(r,"IN",e)}function and(...r){return new LogicalExpression("AND",r.filter(Boolean))}function or(...r){return new LogicalExpression("OR",r.filter(Boolean))}function parseActivityStreamsMessage(r){const e=JSON.parse(r);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,n=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!n.ok)throw new Error(`SSE connection failed: ${n.status} ${n.statusText}`);if(!n.body)throw new Error("SSE response has no body");this.contentType=n.headers.get("content-type")||"",this._connected=!0,this.reader=n.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:n,value:i}=await this.reader.read();if(n){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const s=e.decode(i,{stream:!0});t+=s,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(n){n.name!=="AbortError"&&this.handleError(n)}}processTurtleBuffer(e){const t=e.split(`
|
|
3
3
|
`);let n="";for(let i=0;i<t.length;i++){const s=t[i];n+=s+`
|
|
4
4
|
`,s.trim().endsWith(".")&&(this.parseTurtleNotification(n.trim()),n="")}return n}processSSEBuffer(e){const t=e.split(`
|
|
5
5
|
|
|
@@ -30,7 +30,7 @@ import{c as createLucideIcon$1}from"./createLucideIcon-yLhAxnfL.js";import{r as
|
|
|
30
30
|
FILTER(?typePredicate = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?typeObject = <${e.config.type}> && CONTAINS(STR(?subject), "${escapeSparqlString(o)}"))`:`?subject ?predicate ?object .
|
|
31
31
|
FILTER(CONTAINS(STR(?subject), "${escapeSparqlString(o)}"))`}
|
|
32
32
|
}
|
|
33
|
-
LIMIT 50`,prefixes:{}},l=i.kind==="sparql"?await this.dialect.executeOnResource(i.resourceUrl,d,i.descriptor):await this.dialect.getSPARQLExecutor().queryContainer(i.resourceUrl,d),h=Array.from(new Set(l.map(p=>this.extractSubjectFromLookupRow(p)).filter(p=>!!p).filter(p=>this.subjectMatchesShortId(e,p,t,s))));if(h.length>1)throw new Error(`${n} found multiple resources for short id '${t}' in '${e.config?.name??"resource"}'. Use a base-relative resource id or full IRI to disambiguate.`);return h[0]??this.getIndexedSubject(e,t)}async resolveIdSubjectForExactOperation(e,t,n){return this.needsShortIdSubjectLookup(e,t)?await this.lookupSubjectIriByShortId(e,t,n):this.resolveIdSubject(e,t,n)}async findById(e,t){const n=await this.resolveIdSubjectForExactOperation(e,t,"findById");return n?await this.findByIri(e,n):null}async findByLocator(e,t){this.warnFindByLocatorDeprecation();const n=this.resolveLocatorSubject(e,t,"findByLocator");return await this.findByIri(e,n)}async findByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.findById(e,t);const n=this.resolveResourceTargetIri(e,t,"findByResource");return await this.findByIri(e,n)}async findByIri(e,t){if(!t||typeof t!="string")throw new Error("findByIri requires a valid IRI string");const n=await this.findByIriViaExactResource(e,t);return n!==void 0?n:(await this.session.select().from(e).whereByIri(t).limit(1))[0]??null}getColumnPredicate(e,t){return t.options?.predicate??t.getPredicate?.(e.config.namespace)}async findByIriViaExactResource(e,t){if(!isPodTable(e))return;const n=this.parseIri(t).documentUrl,i=await this.readPredicateObjectRowsFromDocument(n,t);if(i===null)return null;if(i!==void 0){const d=this.mapPredicateObjectRows(e,t,i);if(d!==void 0)return d}if(typeof this.dialect.executeOnResource!="function")return;const s={type:"SELECT",query:`SELECT ?p ?o WHERE { <${t}> ?p ?o . }`,prefixes:{}};let o;try{o=await this.dialect.executeOnResource(n,s)}catch(d){if(this.isMissingExactResourceError(d))return;throw d}const a=this.mapPredicateObjectRows(e,t,o);if(a!==void 0)return a}async readPredicateObjectRowsFromDocument(e,t){const n=this.dialect.getAuthenticatedFetch;if(typeof n!="function")return;let i;try{i=await n.call(this.dialect)(e,{method:"GET",headers:{Accept:"text/turtle, application/ld+json;q=0.8, */*;q=0.1"}})}catch(a){return this.isMissingExactResourceError(a)?null:void 0}if(i.status===404)return null;if(!i.ok)return;const s=i.headers.get("content-type")??"";if(s&&!s.includes("text/turtle")&&!s.includes("application/n-triples")&&!s.includes("application/trig")&&!s.includes("application/ld+json"))return;const o=await i.text();if(!o.trim())return null;try{return new N3Parser$1({baseIRI:e,format:s.includes("application/n-triples")?"N-Triples":"text/turtle"}).parse(o).filter(l=>l.subject.termType==="NamedNode"&&l.subject.value===t).map(l=>({p:l.predicate.value,o:this.convertRdfTermToValue(l.object)}))}catch{return}}convertRdfTermToValue(e){if(e.termType==="NamedNode")return e.value;if(e.termType==="BlankNode")return`_:${e.value}`;if(e.termType!=="Literal")return e.value;const t=e.datatype?.value??"";if(t.includes("#integer")||t.includes("#int"))return parseInt(e.value,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e.value);if(t.includes("#boolean"))return e.value==="true";if(t.includes("#dateTime"))return new Date(e.value);if(t.includes("#json"))try{return JSON.parse(e.value)}catch{return e.value}return e.value}isMissingExactResourceError(e){if(!isRecord$2(e))return!1;if((e.status??e.statusCode)===404)return!0;const n=e.message;return typeof n=="string"&&/\b(?:HTTP status )?404\b/.test(n)}mapPredicateObjectRows(e,t,n){if(!Array.isArray(n)||n.length===0)return null;const i={subject:t,"@id":t,uri:t},s=this.extractIdFromIri(e,t);s!==void 0&&(i.id=s);let o=!1,a=!1,d=!1;for(const l of n){if(!isRecord$2(l))continue;const h=l.p??l.predicate??l["?p"],p=l.o??l.object??l["?o"];if(typeof h=="string"){h==="http://www.w3.org/1999/02/22-rdf-syntax-ns#type"&&p===e.config.type&&(o=!0);for(const[g,S]of Object.entries(e.columns??{})){if(S._virtualId)continue;const y=this.getColumnPredicate(e,S);if(!y||y==="@id"||y!==h)continue;if(S.options?.isArray||S.dataType==="array"){const E=Array.isArray(i[g])?i[g]:i[g]===void 0?[]:[i[g]];i[g]=[...E,p]}else i[g]===void 0&&(i[g]=p);S.dataType==="object"&&typeof p=="string"&&isAbsoluteIri(p)&&(d=!0),a=!0}}}if(!o&&!a)return null;if(!d)return i}extractIdFromIri(e,t){const n=parsePodResourceRef(e,t);if(n)return n.templateValues.id??n.resourceId;try{const a=this.dialect.getResolver(e).parseId(e,t);if(a)return a}catch{}const i=e.getSubjectTemplate?.()??e.config?.subjectTemplate;if(!i)return;if(i==="{id}.ttl"){const a=t.split("/").pop()??"";return a.endsWith(".ttl")?a.slice(0,-4):a||void 0}if(i==="{id}.ttl#it"){const d=t.split("#")[0].split("/").pop()??"";return d.endsWith(".ttl")?d.slice(0,-4):d||void 0}const s=t.indexOf("#");if(s>=0&&i.includes("{id}")&&i.startsWith("#"))return decodeURIComponent(t.slice(s+1));const o=t.split("#")[0].split("/").pop()??"";return o.endsWith(".ttl")?o.slice(0,-4):void 0}parseIri(e){const t=e.indexOf("#");return t>=0?{documentUrl:e.substring(0,t),fragment:e.substring(t+1)}:{documentUrl:e,fragment:null}}async subscribeByIri(e,t,n){if(!t||typeof t!="string")throw new Error("subscribeByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`subscribeByIri requires an absolute IRI, got: ${t}`);if(!this.notificationsClient){const o=this.dialect.getAuthenticatedFetch(),a={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(o,a)}const{documentUrl:i}=this.parseIri(t),s=await this.notificationsClient.subscribe(i,{channel:n.channel,features:n.features,onNotification:async o=>{try{if(o.type==="Update"){const a=await this.findByIri(e,t);a&&await n.onUpdate(a)}else o.type==="Delete"&&await n.onDelete?.()}catch(a){n.onError?.(a)}},onError:n.onError});return()=>s.unsubscribe()}async updateByIri(e,t,n){if(!t||typeof t!="string")throw new Error("updateByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`updateByIri requires an absolute IRI, got: ${t}`);const i=n;return await this.session.update(e).set(i).whereByIri(t),await this.findByIri(e,t)}async updateById(e,t,n){const i=await this.resolveIdSubjectForExactOperation(e,t,"updateById");return i?await this.updateByIri(e,i,n):null}async updateByLocator(e,t,n){const i=this.resolveLocatorSubject(e,t,"updateByLocator");return await this.updateByIri(e,i,n)}async updateByResource(e,t,n){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.updateById(e,t,n);const i=this.resolveResourceTargetIri(e,t,"updateByResource");return await this.updateByIri(e,i,n)}async deleteByIri(e,t){if(!t||typeof t!="string")throw new Error("deleteByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`deleteByIri requires an absolute IRI, got: ${t}`);return await this.findByIri(e,t)?(await this.session.delete(e).whereByIri(t),!0):!1}async deleteById(e,t){const n=await this.resolveIdSubjectForExactOperation(e,t,"deleteById");return n?await this.deleteByIri(e,n):!1}async deleteByLocator(e,t){const n=this.resolveLocatorSubject(e,t,"deleteByLocator");return await this.deleteByIri(e,n)}async deleteByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.deleteById(e,t);const n=this.resolveResourceTargetIri(e,t,"deleteByResource");return await this.deleteByIri(e,n)}async transaction(e){return await this.session.transaction(async t=>{const n=new PodDatabase(this.dialect,t,this.schema);return await e(n)})}getDialect(){return this.dialect}getSession(){return this.session}getSchema(){return this.schema}get discovery(){return this.dialect.getDiscovery()}async connect(){return await this.dialect.connect()}async disconnect(){return this.notificationsClient&&this.notificationsClient.unsubscribeAll(),await this.dialect.disconnect()}async subscribe(e,t){if(!this.notificationsClient){const s=this.dialect.getAuthenticatedFetch(),o={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(s,o)}const n=this.resolveResourceTopic(e,t.iri),i={channel:t.channel,features:t.features,onNotification:s=>{if(t.onNotification?.(s),!!(t.onCreate||t.onUpdate||t.onDelete||t.onAdd||t.onRemove)){const a={id:s.id,type:s.type,object:s.object,published:s.published,state:s.state};switch(s.type){case"Create":t.onCreate?.(a);break;case"Update":t.onUpdate?.(a);break;case"Delete":t.onDelete?.(a);break;case"Add":t.onAdd?.(a);break;case"Remove":t.onRemove?.(a);break}}},onError:t.onError,onClose:t.onClose};return this.notificationsClient.subscribe(n,i)}resolveResourceTopic(e,t){if(t){if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`iri must be an absolute URL, got: ${t}`);return t}const n=e.config.base||"";if(n.startsWith("http://")||n.startsWith("https://"))return n;const i=this.dialect.getPodUrl(),s=i.endsWith("/")?i:`${i}/`,o=n.startsWith("/")?n.slice(1):n;return`${s}${o}`}getConfig(){return this.dialect.getConfig()}async discoverTable(e){const t=await this.dialect.discoverDataLocations(e);if(t.length===0)return console.log(`[discoverTable] No data locations found for ${e}`),null;const n=t[0],i=n.shapes[0]?.url;if(console.log(`[discoverTable] Found location: ${n.container}, shape: ${i||"none"}`),i){const l=this.dialect.getShapeManager(),h=await l.loadShape(i,this.dialect.getAuthenticatedFetch());if(h){console.log(`[discoverTable] Loaded shape with ${h.properties.length} properties`);const p=l.shapeToTable(h,n.container);return await this.init(p.table),p.table}}console.log("[discoverTable] No shape available, creating basic table");const{podTable:s,string:o}=await __vitePreload(async()=>{const{podTable:l,string:h}=await import("./index-CMigfjqD.js");return{podTable:l,string:h}},__vite__mapDeps([0,1,2,3,4,5,6])),a=this.extractClassName(e),d=s(a,{id:o("id").primaryKey()},{type:e,base:n.container});return await this.init(d),d}async discoverTables(e){const t=[];for(const n of e){const i=await this.discoverTable(n);i&&t.push(i)}return t}async discover(e,t){return this.dialect.discoverDataLocations(e,t)}async discoverAll(){return this.dialect.discoverAll()}async discoverByApp(e){return this.dialect.discoverByApp(e)}async locationToTable(e,t){const n=t??{};let i;if(n.shape)typeof n.shape=="string"?(i=e.shapes.find(l=>l.url===n.shape),i||(i={url:n.shape,source:"config"})):i=n.shape;else if(n.appId){if(i=e.shapes.find(l=>l.registeredBy===n.appId),!i)throw new Error(`[locationToTable] No shape found for appId: ${n.appId}`)}else i=e.shapes[0];if(i?.url){const l=this.dialect.getShapeManager(),h=await l.loadShape(i.url,this.dialect.getAuthenticatedFetch());if(h){console.log(`[locationToTable] Loaded shape: ${i.url} (${h.properties.length} properties)`),i.registeredBy&&console.log(`[locationToTable] -> registeredBy: ${i.registeredBy}`);const p=l.shapeToTable(h,e.container);return await this.init(p.table),p.table}}console.log(`[locationToTable] No shape available, creating basic table for container: ${e.container}`);const{podTable:s,string:o}=await __vitePreload(async()=>{const{podTable:l,string:h}=await import("./index-CMigfjqD.js");return{podTable:l,string:h}},__vite__mapDeps([0,1,2,3,4,5,6])),a=this.extractContainerName(e.container),d=s(a,{id:o("id").primaryKey()},{type:"http://www.w3.org/2000/01/rdf-schema#Resource",base:e.container});return await this.init(d),d}extractContainerName(e){const t=e.replace(/\/$/,""),n=t.lastIndexOf("/");return n>=0&&t.substring(n+1).toLowerCase()||"data"}async discoverTablesFor(e,t,n){const i=await this.discover(e,t),s=[];for(const o of i){const a=await this.locationToTable(o,n);s.push(a)}return s}extractClassName(e){const t=e.lastIndexOf("#");if(t>=0)return e.substring(t+1).toLowerCase();const n=e.lastIndexOf("/");return n>=0?e.substring(n+1).toLowerCase():e.toLowerCase()}addSource(e){this.dialect.addSource(e)}removeSource(e){this.dialect.removeSource(e)}getSources(){return this.dialect.getSources()}async addSourcesFromTypeIndex(){return await this.dialect.addSourcesFromTypeIndex()}async init(...e){let t,n;const i=e[e.length-1];i&&typeof i=="object"&&!Array.isArray(i)&&!("columns"in i)?(t=i,n=e.slice(0,-1)):n=e;const s=[];for(const o of n)if(o)if(Array.isArray(o))for(const a of o)a&&s.push(a);else s.push(o);for(const o of s)if(typeof o.init=="function"?await o.init(this.dialect):await this.dialect.registerTable(o),t?.generateShape||t?.saveShape){const a=this.dialect.getShapeManager(),d=a.generateShape(o);if(t?.saveShape){const l=this.dialect.getPodUrl();let h=t.shapeLocation;h?h.startsWith("http")||(h=`${l}${h.replace(/^\//,"")}`):h=`${l}shapes/`,h.endsWith("/")||(h+="/");const p=`${h}${o.config.name}Shape.ttl`;try{await a.saveShape(d,p),console.log(`[init] Shape saved to: ${p}`)}catch(g){console.warn(`[init] Failed to save Shape to ${p}:`,g)}}}}get query(){return this.queryProxy||(this.queryProxy=this.buildQueryProxy()),this.queryProxy}buildQueryProxy(){const e=this.schema&&typeof this.schema=="object"?Object.entries(this.schema):[],t=new Map;for(const[s,o]of e)isPodTable(o)&&t.set(s,o);const n=(s,o)=>{const a=I=>{let C=null;const O=()=>(C||(C=I()),C);return{then:(P,D)=>O().then(P,D),catch:P=>O().catch(P),finally:P=>O().finally(P),[Symbol.toStringTag]:"Promise"}},d=(I,C,O)=>{const P={};for(const[D,Y]of Object.entries(C)){if(Y instanceof PodColumnBase){P[D]=I[Y.name];continue}if(typeof Y=="string"){P[D]=I[Y]??I[Y.split(".").pop()??Y];continue}const re=Y?.name;if(typeof re=="string"){P[D]=I[re];continue}P[D]=I[D]}if(O)for(const D of Object.keys(O))P[D]=I[D]??[];return P},l=async I=>{this.clearFederatedErrors();let C=this.session.select().from(o);I?.where&&(C=C.where(I.where)),I?.orderBy&&(Array.isArray(I.orderBy)?I.orderBy:[I.orderBy]).forEach(Y=>{C=C.orderBy(Y.column,Y.direction??"asc")}),typeof I?.limit=="number"&&(C=C.limit(I.limit)),typeof I?.offset=="number"&&(C=C.offset(I.offset));let O=await C;I?.with&&Object.keys(I.with).length>0&&(O=await this.eagerLoadWith(O,o,I.with,t));const P=I?.columns;return P&&(O=O.map(D=>d(D,P,I.with))),O},h=I=>a(()=>l(I)),p=async(I,C)=>{if(!I)return null;let O=[I];C?.with&&Object.keys(C.with).length>0&&(O=await this.eagerLoadWith(O,o,C.with,t));const P=C?.columns;return P&&(O=O.map(D=>d(D,P,C.with))),O[0]??null},g=I=>a(async()=>(await l({...I,limit:1}))[0]??null),S=I=>a(async()=>(await l({where:I?.where,columns:void 0,limit:void 0,offset:void 0})).length),y=()=>(I,C)=>a(async()=>await p(await this.findByLocator(o,I),C)),v=()=>(I,C)=>a(async()=>await p(await this.findById(o,I),C)),E=()=>(I,C)=>a(async()=>await p(await this.findByIri(o,I),C)),w=()=>(I,C)=>a(async()=>await p(await this.findByResource(o,I),C));return{findMany:h,findFirst:g,find:(I,C)=>w()(I,C),findById:v(),findByLocator:y(),findByIri:E(),findByResource:w(),count:S}},i={};return new Proxy(i,{get:(s,o)=>{if(typeof o!="string")return;const a=t.get(o);if(a)return n(o,a)}})}async eagerLoadWith(e,t,n,i){if(!e||e.length===0)return e;const s=this.dedupeBySubject(e);for(const[o,a]of Object.entries(n)){if(!a)continue;const d=t.relations?.[o],l=typeof a=="object"&&a.table?a.table:d?.table??i.get(o);if(!l)continue;if(isSolidSchema(l)||d?.isFederated){if(d&&d.discover)try{const Y=await this.getFederatedExecutor().execute(s,{...d,relationName:o});Y.errors&&Y.errors.length>0&&this.lastFederatedErrors.push(...Y.errors)}catch(D){console.warn(`Federated relation "${o}" failed:`,D),s.forEach(Y=>{Y[o]=[]})}else console.warn(`Federated relation "${o}" missing discover function, skipping.`),s.forEach(D=>{D[o]=[]});continue}const h=l,p=h.config.type,g=d?.fields&&d.fields.length>0?d.fields:Object.values(h.columns??{}),S=D=>!!(D&&(D.options?.linkTarget===t.config.type||D.options?.linkTable===t||D.getLinkTable?.()===t)),y=D=>!!(D&&(D.options?.linkTarget===p||D.options?.linkTable===h||D.getLinkTable?.()===h)),v=d?.fields&&d.fields.length>0?g:g.filter(D=>S(D)&&!D.isInverse?.());if(v.length===0){const Y=(d?.references??[]).filter(ke=>!!(ke&&typeof ke.isInverse=="function"&&ke.isInverse()&&y(ke))),re=Object.values(t.columns??{}),$=(Y.length>0?Y:re).filter(ke=>typeof ke.isInverse=="function"&&ke.isInverse()&&y(ke));if($.length===0)continue;const te=s.map(ke=>this.collectInverseLinkValues(ke,$)),be=Array.from(new Set(te.flat().filter(ke=>typeof ke=="string"&&ke.length>0)));if(be.length===0){e.forEach(ke=>{ke[o]=[]});continue}let fe=this.session.select().from(h);fe=fe.whereByIri(be);const Pe=await fe,Ue=this.groupRowsByIri(Pe);s.forEach((ke,Ge)=>{const Ae=te[Ge],we=[];Ae.forEach(ie=>{const xe=Ue.get(ie);xe&&xe.length>0&&we.push(...xe)}),ke[o]=we});continue}const E=v[0],w=d?.references&&d.references[0],T=E.isLink(),I=s.map(D=>this.resolveParentKey(D,w,T)).filter(D=>typeof D=="string"&&D.length>0);if(I.length===0)continue;let C=this.session.select().from(h);T?C=C.where(inArray(E,I)):C=C.where({[E.name]:I});const O=await C,P=new Map;for(const D of O){const Y=D[E.name],re=this.normalizeLiteralValue(Y),$=T?this.collectLinkLookupKeys(Y):re?[re]:[];for(const te of $){const be=P.get(te)??[];be.push(D),P.set(te,be)}}s.forEach(D=>{const Y=T?Array.from(new Set([this.resolveParentKey(D,w,!0),this.resolveIdFromRow(D)].filter($=>typeof $=="string"&&$.length>0))):[this.resolveParentKey(D,w,!1)].filter($=>typeof $=="string"&&$.length>0),re=[];for(const $ of Y){const te=P.get($)??[];for(const be of te)re.includes(be)||re.push(be)}D[o]=re})}return s}dedupeBySubject(e){const t=new Map,n=[];for(const i of e){const s=this.resolveIriFromRow(i)??this.resolveIdFromRow(i);if(!s){n.push(`__anon_${n.length}`),t.set(n[n.length-1],{...i});continue}if(!t.has(s)){t.set(s,{...i}),n.push(s);continue}const o=t.get(s);if(o)for(const[a,d]of Object.entries(i)){if(d===void 0)continue;const l=o[a];if(l===void 0){o[a]=d;continue}const h=Array.isArray(l)?l:[l],p=Array.isArray(d)?d:[d],g=[...h];for(const S of p)g.some(y=>y===S)||g.push(S);o[a]=g.length===1?g[0]:g}}return n.map(i=>t.get(i)).filter(i=>i!==void 0)}resolveIdFromRow(e){if(!e)return;if(typeof e.id=="string"&&e.id.length>0)return e.id;const t=typeof e["@id"]=="string"?e["@id"]:void 0;if(t)return this.extractFragment(t)}resolveParentKey(e,t,n){if(t){const i=e[t.name];return n?this.normalizeLinkValue(i):this.normalizeLiteralValue(i)}return n?this.resolveIriFromRow(e):this.resolveIdFromRow(e)}resolveIriFromRow(e){if(e){if(typeof e["@id"]=="string"&&e["@id"].length>0)return e["@id"];if(typeof e.subject=="string"&&e.subject.length>0)return e.subject}}collectLinkLookupKeys(e){const t=[],n=this.normalizeLinkValue(e)??this.normalizeLiteralValue(e);if(n){t.push(n);const i=this.extractFragment(n);i&&!t.includes(i)&&t.push(i)}return t}normalizeLinkValue(e){if(e){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}normalizeLiteralValue(e){if(e!=null){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}collectInverseLinkValues(e,t){if(!t.length)return[];const n=[];for(const i of t){const s=e[i.name];if(s==null)continue;const o=a=>{const d=this.normalizeLinkValue(a)??(typeof a=="string"?a:void 0);d&&n.push(d)};Array.isArray(s)?s.forEach(o):o(s)}return n}groupRowsByIri(e){const t=new Map;for(const n of e){const i=this.normalizeLinkValue(n["@id"])??this.normalizeLinkValue(n.uri)??(typeof n["@id"]=="string"?n["@id"]:void 0);if(!i)continue;const s=t.get(i)??[];s.push(n),t.set(i,s)}return t}extractFragment(e){const t=e.includes("#")?e.split("#").pop():void 0;return t&&t.length>0?t:e.split("/").pop()??e}}_a$8=entityKind;PodDatabase[_a$8]="PodDatabase";PodDatabase.findByLocatorDeprecationWarned=!1;function isAggregateExpression(r){return!!r&&typeof r=="object"&&r.kind==="aggregate"}function inferSPARQLQueryType(r){const n=r.replace(/^\s*#.*$/gm,"").trim().replace(/^(?:\s*(?:PREFIX|BASE)\s+[^\n]+\n)*/i,"").trim().match(/^(SELECT|ASK|INSERT|DELETE|UPDATE|WITH|LOAD|CLEAR|CREATE|DROP|COPY|MOVE|ADD|CONSTRUCT|DESCRIBE)\b/i)?.[1]?.toUpperCase();switch(n){case"SELECT":case"ASK":case"INSERT":case"DELETE":case"UPDATE":return n;case"WITH":case"LOAD":case"CLEAR":case"CREATE":case"DROP":case"COPY":case"MOVE":case"ADD":return"UPDATE";default:return}}function createLiteralCondition(r,e,t){const n=r?`${r}.${e}`:e;return t==null?new UnaryExpression("IS NULL",n):Array.isArray(t)?new BinaryExpression(n,"IN",t):new BinaryExpression(n,"=",t)}function buildConditionTreeFromObject(r,e){if(!r)return;const t=Object.entries(r);if(t.length===0)return;const n=t.map(([i,s])=>createLiteralCondition(e,i,s));return n.length===1?n[0]:new LogicalExpression("AND",n)}function resolveRowSubject(r){if(!(!r||typeof r!="object")){if(typeof r["@id"]=="string"&&r["@id"].length>0)return r["@id"];if(typeof r.subject=="string"&&r.subject.length>0)return r.subject;if(typeof r.uri=="string"&&r.uri.length>0)return r.uri;if(typeof r.source=="string"&&r.source.length>0)return r.source;if(typeof r.id=="string"&&r.id.length>0)return r.id}}function orderRowsBySubjects(r,e){if(!r.length||!e.length)return r;const t=new Map,n=[];for(const s of r){const o=resolveRowSubject(s);if(!o){n.push(s);continue}const a=t.get(o)??[];a.push(s),t.set(o,a)}const i=[];for(const s of e){const o=t.get(s);o?.length&&(i.push(...o),t.delete(s))}for(const s of t.values())i.push(...s);return i.push(...n),i}function isSelectFieldMap(r){return!!r&&typeof r=="object"&&!(r instanceof PodColumnBase)&&!(r instanceof PodTable)&&!("aggregateType"in r)}function resolveFieldBindingCandidates(r,e){const t=new Set;if(typeof e=="string"){if(t.add(e),e.includes(".")){const[n,i]=e.split(".",2);i&&(t.add(`${n}.${i}`),t.add(i))}}else e instanceof PodColumnBase&&(e.table?.config?.name&&t.add(`${e.table.config.name}.${e.name}`),t.add(e.name));return Array.from(t)}function isEmptyProjectedValue(r){if(r==null)return!0;if(Array.isArray(r))return r.length===0;if(typeof r=="object"){const e=Object.values(r);return e.length>0&&e.every(t=>isEmptyProjectedValue(t))}return!1}function projectTableRow(r,e){const t=e.config.name,n={};let i=!1;for(const s of Object.keys(e.columns)){const a=(t?[`${t}.${s}`,s]:[s]).find(d=>r[d]!==void 0);n[s]=a?r[a]:void 0,n[s]!==void 0&&(i=!0)}return i?n:null}function projectFieldValue(r,e,t){if(t instanceof PodTable)return projectTableRow(r,t);if(isSelectFieldMap(t)){const n={};for(const[i,s]of Object.entries(t))n[i]=projectFieldValue(r,i,s);return isEmptyProjectedValue(n)?null:n}for(const n of resolveFieldBindingCandidates(e,t))if(r[n]!==void 0)return r[n];return r[e]}function projectReturningRow(r,e){if(!e||e===!0)return r;const t={};for(const[n,i]of Object.entries(e))t[n]=projectFieldValue(r,n,i);return t}function projectReturningRows(r,e){return!e||e===!0?r:r.map(t=>projectReturningRow(t,e))}const UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,SINGLETON_FRAGMENTS=new Set(["#me","#this","#profile","#card"]);class UriResolverImpl{constructor(e=""){this.podUrl=e.replace(/\/$/,"")}setPodUrl(e){this.podUrl=e.replace(/\/$/,"")}resolveSubject(e,t,n,i){const s=i?.strict??!0,o=t["@id"]??t.id??t.uri;if(typeof o=="string"){if(this.isAbsoluteUri(o))return o;const h=this.resolveBaseRelativeSubjectId(e,o);if(h)return h;o.startsWith("#")&&this.acceptsFragmentOnlyResourceId(e)&&(t={...t,id:o.slice(1)})}const a=this.getEffectivePattern(e),d=this.getSubjectBaseUrl(e);if(this.isSingleton(e))return this.combineBaseAndPattern(d,a);const l=this.applyTemplate(a,t,n,e,s);return l===null?this.generateFallbackUri(d,a,n):this.isAbsoluteUri(l)?l:this.combineBaseAndPattern(d,l)}parseSubject(e,t){if(!e)return null;const n=e.indexOf("#"),i=n!==-1,s=i?e.slice(0,n):e,o=i?e.slice(n+1):void 0,a=this.extractPublicId(e,t),d=this.getResourceMode(t);return{uri:e,resourceUrl:s,fragment:o,id:a,mode:d}}getResourceUrl(e){const t=e.indexOf("#");return t!==-1?e.slice(0,t):e}getResourceMode(e){if(!(e.hasCustomTemplate?.()??!1)){const i=e.config?.base??"";return/\.(ttl|jsonld|json)$/i.test(i)?"fragment":"document"}return(e.config?.subjectTemplate??this.getDefaultPattern(e)).startsWith("#")?"fragment":"document"}getDefaultPattern(e){return"{id}"}resolveInlineChild(e,t,n,i){const s=n["@id"]??n.id;return typeof s=="string"?s:buildInlineChildUri(e,t,i)}isSingleton(e){const t=e.config?.subjectTemplate;return t?!!(SINGLETON_FRAGMENTS.has(t)||!t.includes("{")):!1}resolveLink(e,t,n){const i=String(e??""),s=n?.record&&typeof n.record=="object"?n.record:void 0;if(this.isAbsoluteUri(i))return i;if(i.startsWith("/")||i.startsWith("#")){const h=n?.baseUri||this.podUrl;if(h)try{return new URL(i,h).toString()}catch{}throw new Error(`Cannot resolve relative URI "${i}": no baseUri configured`)}const o=t.getLinkTable?.();if(o){const h=this.getTableUriInfo(o);if(h)return this.buildFullUri(i,h.baseUrl,h.subjectTemplate,o,n,s);throw new Error(`Cannot resolve URI "${i}": linked table "${o.config?.name}" has no base configured.`)}const a=t.getLinkTableName?.();if(a){if(n?.tableNameRegistry){const p=n.tableNameRegistry.get(a);if(p){const g=this.getTableUriInfo(p);if(g)return this.buildFullUri(i,g.baseUrl,g.subjectTemplate,p,n,s)}}const h=n?.tableNameRegistry?Array.from(n.tableNameRegistry.keys()).join(", "):"(no tables registered)";throw new Error(`Cannot resolve URI "${i}": table "${a}" not found in schema. Available tables: ${h}`)}const d=t.getLinkTarget?.();if(d){if(!n?.tableRegistry)throw new Error(`Cannot resolve URI "${i}" (links to ${d}): tableRegistry not configured. Ensure the schema is properly registered.`);const h=n.tableRegistry.get(d);if(h&&h.length>0){if(h.length>1){const S=h.map(y=>y.config?.name||"unknown").join(", ");throw new Error(`Ambiguous link target: class "${d}" has multiple tables [${S}]. Use .link('tableName') or .link(tableObject) to specify which table to use.`)}const p=h[0],g=this.getTableUriInfo(p);if(g)return this.buildFullUri(i,g.baseUrl,g.subjectTemplate,p,n,s)}throw new Error(`Cannot resolve URI "${i}": class "${d}" not found in tableRegistry. Available classes: ${Array.from(n.tableRegistry.keys()).join(", ")||"(none)"}`)}const l=n?.baseUri||this.podUrl;if(l&&this.isAbsoluteUri(l)){const h=l.endsWith("/")?l:`${l}/`;return this.buildFullUri(i,h)}throw new Error(`Cannot resolve URI "${i}". Either provide a full URI (https://...), or configure baseUri.`)}isAbsoluteUri(e){return!e||typeof e!="string"?!1:e.includes(":")&&(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("urn:")||e.startsWith("did:")||e.startsWith("mailto:")||e.startsWith("tel:")||e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))}isLinkColumn(e){return e?e.dataType==="uri"||e.isLink?.()||!!e.options?.linkTarget||!!e.options?.linkTableName||!!e.options?.linkTable:!1}findTargetTable(e,t){const n=e.getLinkTable?.()||e.options?.linkTable;if(n)return n;const i=e.getLinkTableName?.()||e.options?.linkTableName;if(i&&t?.tableNameRegistry){const o=t.tableNameRegistry.get(i);if(o)return o}const s=e.getLinkTarget?.()||e.options?.linkTarget;if(s&&t?.tableRegistry){const o=t.tableRegistry.get(s);if(o&&o.length===1)return o[0]}}extractLinkId(e,t,n){if(e?.startsWith("/")){const o=n?.baseUri||this.podUrl;if(o){const a=o.endsWith("/")?o:`${o}/`;e=new URL(e.replace(/^\/+/,""),a).toString()}}if(!e||!this.isAbsoluteUri(e))return e;const i=this.findTargetTable(t,n);if(!i)return e;const s=this.extractTemplateIdFromSubject(e,i);return s||e}getTableUriInfo(e){const t=e.config?.base;if(!t)return;const n=e.config?.subjectTemplate;return{baseUrl:this.toAbsoluteUrl(t),subjectTemplate:n}}buildFullUri(e,t,n,i,s,o){const a=String(e??"");if(!n){const g=this.combineBaseAndResourceId(t,a);return this.assertNoUnresolvedTemplate(g,void 0,i),g}if(!UUID_REGEX.test(a)&&a.includes("/")&&!a.includes("{")){const g=`${t}${a}`;return this.assertNoUnresolvedTemplate(g,n,i),g}const d=this.buildTemplateRecord(a,n,i,s,o),l=this.applyTemplate(n,d,void 0,i,!0,s);if(l===null)throw new Error(`[UriResolver] Failed to resolve URI template "${n}" for table "${i?.config?.name??"unknown"}"`);if(this.isAbsoluteUri(l))return this.assertNoUnresolvedTemplate(l,n,i),l;if(l.startsWith("#")){const S=`${t.endsWith("/")?t.slice(0,-1):t}${l}`;return this.assertNoUnresolvedTemplate(S,n,i),S}const p=`${t.endsWith("/")?t:`${t}/`}${l}`;return this.assertNoUnresolvedTemplate(p,n,i),p}buildTemplateRecord(e,t,n,i,s){const o={...s??{}};o.id=e;for(const a of t.matchAll(/\{([^}]+)\}/g)){const l=this.parseTemplateVariable(a[1]).field;if(l==="id"||l==="index"||l in o)continue;const h=this.resolveTemplateVariable(l,n,i,s);h!=null&&h!==""&&(o[l]=h)}return o}resolveTemplateVariable(e,t,n,i){if(!i||typeof i!="object")return;if(e in i){const d=t?.columns?.[e];return this.normalizeValue(i[e],d,n)}const s=`${e}Id`;if(s in i)return String(i[s]);const o=t?.columns?.[e],a=o?this.findTargetTable(o,n):void 0;if(a)for(const[d,l]of Object.entries(i)){const h=n?.currentTable?.columns?.[d];if((h?this.findTargetTable(h,n):void 0)===a)return this.normalizeValue(l,o,n)}}assertNoUnresolvedTemplate(e,t,n){if(/\{[^}]+\}/.test(e)){const i=n?.config?.name||"unknown";throw new Error(`[UriResolver] Unresolved URI template variable while resolving table "${i}" with template "${t??"<exact-id>"}": ${e}`)}}getEffectivePattern(e){if(e.hasCustomTemplate?.()??!1){const n=e.config?.subjectTemplate;if(n&&n.trim().length>0)return n}return this.getDefaultPattern(e)}getSubjectBaseUrl(e){const t=e.config?.base??"";return this.toAbsoluteUrl(t)}isBaseRelativeSubjectId(e){return!e||this.isAbsoluteUri(e)||e.startsWith("/")?!1:e.startsWith("#")||e.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(e)}acceptsFragmentOnlyResourceId(e){const t=e.config?.subjectTemplate;if(!t)return!1;const n=Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>this.parseTemplateVariable(i[1]).field);return t==="#{id}"||t.startsWith("#")&&n.length===1&&n[0]==="id"}resolveBaseRelativeSubjectId(e,t){if(!this.isBaseRelativeSubjectId(t))return null;const n=this.getSubjectBaseUrl(e);if(t.startsWith("#"))return this.acceptsFragmentOnlyResourceId(e)?`${n}${t}`:null;if(n.endsWith("/"))return`${n}${t}`;const i=n.lastIndexOf("/");return`${i>=0?n.slice(0,i+1):`${n}/`}${t}`}toAbsoluteUrl(e){if(!e)return this.podUrl;if(this.isAbsoluteUri(e))return e;const t=e.startsWith("/")?e:`/${e}`;return`${this.podUrl}${t}`}combineBaseAndPattern(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:e.endsWith("/")?`${e}${t}`:(e.endsWith(".ttl")||e.endsWith(".jsonld"))&&t.startsWith("#")?`${e}${t}`:`${e}/${t}`}combineBaseAndResourceId(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:`${e.endsWith("/")?e:`${e}/`}${t}`}normalizeValue(e,t,n){return e==null?"":typeof e=="string"&&this.isAbsoluteUri(e)&&t&&this.isLinkColumn(t)?this.extractLinkId(e,t,n):String(e)}parseTemplateVariable(e){const[t,...n]=e.split("|").map(i=>i.trim()).filter(Boolean);return{raw:e,field:t||e,transforms:n}}slugifyValue(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu,"-").replace(/^-+|-+$/g,"")}applyTransforms(e,t,n,i){let s=this.normalizeValue(e,n,i);for(const o of t.transforms){if(o==="id"){s=n&&this.isLinkColumn(n)?this.extractLinkId(s,n,i):s;continue}o==="slug"&&(s=this.slugifyValue(s))}return s}applyTemplate(e,t,n,i,s=!0,o){if(!e.includes("{"))return e;const a=this.createTimeContext(t),d=[],l=e.replace(/(#?)\{([^}]+)\}/g,(h,p,g)=>{const S=this.parseTemplateVariable(g),y=S.field;if(y in a)return p+a[y];if(y==="index"&&n!==void 0)return p+String(n+1);let v=t[y];if(y==="id"&&v==null&&(v=t["@id"]??t.uri),v==null)return d.push(g),h;const E=i?.columns?.[y],w=o??(i?{tableRegistry:i[Symbol.for("drizzle:tableRegistry")],tableNameRegistry:i[Symbol.for("drizzle:tableNameRegistry")]}:void 0),T=this.applyTransforms(v,S,E,w);return p==="#"&&T.startsWith("#")?p+T.slice(1):p+T});if(d.length>0){if(s){const h=i?.config?.name||"unknown";throw new Error(`[UriResolver] Missing required fields for template "${e}" in table "${h}": [${d.join(", ")}]. Record keys: [${Object.keys(t).join(", ")}]. Record: ${JSON.stringify(t)}`)}return null}return l}createTimeContext(e){let t;const n=e.createdAt??e.created_at??e.dateCreated;n instanceof Date?t=n:typeof n=="string"||typeof n=="number"?t=new Date(n):t=new Date;const i=t.getUTCFullYear().toString(),s=(t.getUTCMonth()+1).toString().padStart(2,"0"),o=t.getUTCDate().toString().padStart(2,"0"),a=Math.floor(t.getTime()/1e3).toString();return{date:t,yyyy:i,MM:s,dd:o,timestamp:a}}generateFallbackUri(e,t,n){const i=n!==void 0?`row-${n+1}`:`row-${Date.now()}`;return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}#${i}`:`${e.endsWith("/")?e:`${e}/`}${i}.ttl`}extractRelativeSubjectId(e,t){const n=t.config?.base??"";let i="";if(n&&e.includes(n)){const s=e.indexOf(n);i=e.substring(s+n.length),i.startsWith("#")&&!(t.hasCustomTemplate?.()??!1)&&(i=`${n.split("/").filter(Boolean).pop()??""}${i}`),i.startsWith("/")&&(i=i.substring(1))}else if(!n)i=e;else return console.warn(`[UriResolver] Cannot extract ID: base "${n}" not found in URI "${e}"`),"";return i}extractPublicId(e,t){return this.extractTemplateIdFromSubject(e,t)??this.extractRelativeSubjectId(e,t)}extractTemplateIdFromSubject(e,t){const n=this.extractRelativeSubjectId(e,t),i=t.config?.subjectTemplate;return i?this.extractIdFromTemplate(n,i):n}extractIdFromTemplate(e,t){let n=t.replace(/[.+?^$[\]\\()]/g,"\\$&").replace(/\{id\}/g,"(?<id>.+?)").replace(/\{[^}]+\}/g,"(?:.+?)");n=`^${n}$`;try{const i=new RegExp(n),s=e.match(i);if(s&&s.groups?.id)return s.groups.id;if(s&&s[1])return s[1]}catch{}return null}}function buildInlineChildUri(r,e,t){const n=r.indexOf("#"),i=n>=0?r.slice(0,n):r,s=n>=0?r.slice(n+1):"",o=s?`${encodeURIComponent(s)}/`:"";return`${i}#${o}${encodeURIComponent(e)}-${t+1}`}function isOrderByExpression(r){if(!r||typeof r!="object")return!1;const e=r;return"column"in e&&(e.direction==="asc"||e.direction==="desc")}function isReservedIdentifierKey(r){return r==="id"||r==="@id"||r.endsWith(".id")||r.endsWith(".@id")}function isReservedIdentifierOperand(r){if(r instanceof PodColumnBase){const e=r;return r.name==="id"||r.options?.predicate==="@id"||e._virtualId===!0}return typeof r=="string"?isReservedIdentifierKey(r):!1}function conditionTargetsReservedIdentifier(r){return r.type==="binary_expr"?!!(isReservedIdentifierOperand(r.left)||isReservedIdentifierOperand(r.right)):r.type==="logical_expr"?r.expressions.some(e=>e!=null&&typeof e=="object"&&"type"in e&&conditionTargetsReservedIdentifier(e)):r.type==="unary_expr"?r.value!=null&&typeof r.value=="object"&&"type"in r.value&&conditionTargetsReservedIdentifier(r.value):!1}function createWhereIdentifierError(r){switch(r){case"select":return["Using 'id' or '@id' in where() is not supported.","Use findById(id) for base-relative resource ids,","or findByIri(iri) for full IRI exact lookups."].join(" ");case"update":return["Using 'id' or '@id' in where() is not supported.","Use updateById(id, data) for base-relative resource ids,","or updateByIri(iri, data) for full IRI exact updates."].join(" ");case"delete":return["Using 'id' or '@id' in where() is not supported.","Use deleteById(id) for base-relative resource ids,","or deleteByIri(iri) for full IRI exact deletes."].join(" ")}}function assertPublicWhereObject(r,e){if(e){for(const t of Object.keys(e))if(isReservedIdentifierKey(t))throw new Error(createWhereIdentifierError(r))}}function assertPublicWhereCondition(r,e){if(conditionTargetsReservedIdentifier(e))throw new Error(createWhereIdentifierError(r))}function assertPublicCursorCondition(r){let e=!1,t=!1;const n=i=>{if(i.type==="binary_expr"){if(isReservedIdentifierOperand(i.left)||isReservedIdentifierOperand(i.right)){if(![">",">=","<","<="].includes(i.operator))throw new Error("whereCursor() only supports range comparisons on 'id' or '@id'.");e=!0}else t=!0;return}if(i.type==="logical_expr"){for(const s of i.expressions)n(s);return}t=!0};if(n(r),!e||!t)throw new Error("whereCursor() requires a sort predicate plus an 'id' or '@id' range tie-breaker.")}var define_process_env_default$2={},_a$7;class SelectQueryBuilder{constructor(e,t){this.session=e,this.joins=[],this.orderByClauses=[],this.isDistinct=!1,this.tableAliases=new Map,this.aliasToTable=new Map,this.aliasUsage=new Map,this.joinFilters=[],this.groupByColumns=[],t&&this.setSelectedFields(t)}from(e){return this.selectedTable=e,this.primaryAlias=this.ensureAliasForTable(e),this}columns(e){return this.setSelectedFields(e),this}setSelectedFields(e){this.selectedFields={...e}}where(e){return e instanceof SQL?this.sql=e:this.isQueryCondition(e)?(assertPublicWhereCondition("select",e),this.processQueryCondition(e)):(assertPublicWhereObject("select",e),this.processWhereObject(e)),this}whereCursor(e){return assertPublicCursorCondition(e),this.processQueryCondition(e),this}whereByIri(e){return this.processWhereObject({"@id":e}),this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,n=e.right,i=e.operator,s=typeof t=="string"?t:t?.name;if(i==="="&&s&&n!==void 0)return{[s]:n}}if(e.type==="logical_expr"){const t=e.operator,n=e.expressions;if(t==="AND"&&n){const i={};for(const s of n){const o=this.convertQueryConditionToSimple(s);if(!o||Object.keys(o).length===0)return{};for(const[a,d]of Object.entries(o))i[a]=d}return i}}return{}}extractTableFromCondition(e){if(e.type==="binary_expr"){const t=e.left;if(t&&typeof t=="object"&&"table"in t){const n=t.table;if(n)return this.tableAliases.get(n)}if(typeof t=="string"&&t.includes("."))return t.split(".")[0]}}leftJoin(e,t){return this.addJoin("leftJoin",e,t)}rightJoin(e,t){return this.addJoin("rightJoin",e,t)}innerJoin(e,t){return this.addJoin("innerJoin",e,t)}fullJoin(e,t){return this.addJoin("fullJoin",e,t)}crossJoin(e){return this.addJoin("crossJoin",e)}groupBy(...e){const t=e.map(n=>this.resolveColumnReference(n));return this.groupByColumns.push(...t),this}having(e){return this.havingCondition=typeof e=="function"?e(this.createSelectedFieldAliases()):e,this}createSelectedFieldAliases(){const e={};for(const t of Object.keys(this.selectedFields??{}))e[t]=new SelectionAliasExpression(t);return e}addJoin(e,t,n){if(e==="rightJoin"||e==="fullJoin")throw new Error(`${e} is not yet supported in Solid dialect`);const i=this.ensureAliasForTable(t),s=e==="crossJoin"?void 0:this.resolveJoinConditions(n,i);return this.joins.push({type:e,table:t,alias:i,rawCondition:n,resolvedConditions:s}),this}ensureAliasForTable(e){const t=this.tableAliases.get(e);if(t)return t;const n=e.config.name||"table",i=this.aliasUsage.get(n)??0,s=i+1;this.aliasUsage.set(n,s);const o=i===0?n:`${n}_${s}`;return this.tableAliases.set(e,o),this.aliasToTable.set(o,e),o}resolveJoinConditions(e,t){if(this.isQueryCondition(e))return this.resolveJoinConditionExpression(e,t);if(!e||typeof e!="object")throw new Error("JOIN condition must be an equality expression or column mapping");const n=Object.entries(e);if(n.length===0)throw new Error("JOIN condition cannot be empty");return n.map(([i,s])=>{const o=this.resolveColumnReference(i),a=this.resolveColumnReference(s);if(o.alias!==t&&a.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return{left:o,right:a}})}resolveJoinConditionExpression(e,t){if(e.type==="logical_expr"){const s=(e.operator??"").toUpperCase(),o=e.expressions??[];if(s!=="AND"||o.length===0)throw new Error("JOIN condition only supports equality expressions combined with AND");return o.flatMap(a=>this.resolveJoinConditionExpression(a,t))}if(e.type!=="binary_expr"||e.operator!=="=")throw new Error("JOIN condition only supports equality expressions");const n=this.getConditionColumnReference(e.left),i=this.getConditionColumnReference(e.right);if(!n||!i)throw new Error("JOIN equality must compare two table columns");if(n.alias!==t&&i.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return[{left:n,right:i}]}getConditionColumnReference(e,t){if(e instanceof PodColumnBase)return this.resolveColumnReference(e,t);if(typeof e=="string"){if(e.includes("."))return this.resolveColumnReference(e,t);const n=t??this.primaryAlias,i=n?this.aliasToTable.get(n):void 0;if(i&&e in(i.columns??{}))return this.resolveColumnReference(e,t)}}resolveColumnReference(e,t){if(e instanceof PodColumnBase){const n=e.table;if(!n)throw new Error(`Column ${e.name} is not associated with a table`);const i=this.ensureAliasForTable(n);return{table:n,alias:i,column:e.name}}if(typeof e=="string"){const{alias:n,column:i}=this.parseColumnReferenceString(e),s=n??t??this.primaryAlias;if(!s)throw new Error(`Unable to resolve table alias for column reference "${e}"`);const o=this.aliasToTable.get(s);if(!o)throw new Error(`Unknown table alias "${s}" in column reference "${e}"`);return{table:o,alias:s,column:i}}throw new Error("Unsupported column link type")}parseColumnReferenceString(e){const t=e.trim();if(!t.includes("."))return{column:t};const[n,i]=t.split(".",2);return{alias:n,column:i}}processWhereObject(e){if(!e)return;const t={...this.whereConditions??{}};for(const[n,i]of Object.entries(e)){const{alias:s,column:o}=this.parseColumnReferenceString(n),a=s??this.primaryAlias;if(!a||a===this.primaryAlias||!this.aliasToTable.has(a)){t[o]=i;continue}this.joinFilters.push(createLiteralCondition(a,o,i))}this.whereConditions=Object.keys(t).length>0?t:void 0}processQueryCondition(e){const t=this.extractTableFromCondition(e);if(t&&t!==this.primaryAlias){this.joinFilters.push(e);return}this.conditionTree=e;const n=this.convertQueryConditionToSimple(e);Object.keys(n).length>0&&(this.whereConditions=n)}applyInternalQueryCondition(e){return this.processQueryCondition(e),this}normalizeWhereConditions(){if(this.conditionTree)return this.conditionTree;const e=this.primaryAlias??this.selectedTable?.config.name;return buildConditionTreeFromObject(this.whereConditions,e)}toIR(){const e=this.normalizeWhereConditions();return this.buildQueryPlan(e)}buildQueryPlan(e){if(!this.selectedTable)throw new Error("No table specified for SELECT query");const t=this.joins.map(n=>({type:n.type,table:n.table,alias:n.alias,conditions:(n.resolvedConditions??[]).map(({left:i,right:s})=>({left:i,right:s}))}));return{baseTable:this.selectedTable,baseAlias:this.primaryAlias??this.selectedTable.config.name,select:this.selectedFields,selectAll:!this.selectedFields,where:this.whereConditions,conditionTree:e,joins:t.length>0?t:void 0,joinFilters:this.joinFilters.length>0?[...this.joinFilters]:void 0,groupBy:this.groupByColumns.length>0?[...this.groupByColumns]:void 0,having:this.havingCondition,orderBy:this.orderByClauses.length>0?this.orderByClauses.map(n=>({rawColumn:n.column,direction:n.direction})):void 0,distinct:this.isDistinct||void 0,limit:this.limitCount,offset:this.offsetCount,aliasToTable:new Map(this.aliasToTable),tableToAlias:new Map(this.tableAliases)}}limit(e){if(!Number.isInteger(e)||e<0)throw new Error("LIMIT must be a non-negative integer");return this.limitCount=e,this}offset(e){if(!Number.isInteger(e)||e<0)throw new Error("OFFSET must be a non-negative integer");return this.offsetCount=e,this}addOrderByClause(e,t="asc"){const n=typeof e=="string"?e:e.name;if(!n)throw new Error("ORDER BY requires a valid column name");this.orderByClauses.push({column:n,direction:t})}orderBy(...e){if(e.length===0)throw new Error("ORDER BY requires at least one column or expression");if(e.length===2&&(e[0]instanceof PodColumnBase||typeof e[0]=="string")&&(e[1]==="asc"||e[1]==="desc"))return this.addOrderByClause(e[0],e[1]),this;for(const t of e){if(isOrderByExpression(t)){this.addOrderByClause(t.column,t.direction);continue}if(t instanceof PodColumnBase||typeof t=="string"){this.addOrderByClause(t,"asc");continue}throw new Error("ORDER BY received an unsupported argument")}return this}distinct(e=!0){return this.isDistinct=e,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const n=this.sql.queryChunks.join(""),i=inferSPARQLQueryType(n);if(!i)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:i,query:n,prefixes:{}}}if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.joins.length>0)throw new Error(`${e} is not yet supported for JOIN queries in Solid dialect`);if(this.shouldUseProjectionFallback())throw new Error(`${e} does not support structured selections in Solid dialect`);const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertSelectPlan(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.limitCount===0)return[];if(this.sql)return await this.session.executeSql(this.sql,this.selectedTable);{const e=this.toIR(),t=e.conditionTree,n=this.joins.length>0,i=this.shouldUseAggregateFallback(),s=this.shouldUseProjectionFallback(),o=n||i;(n||i||s)&&(e.select=void 0,e.selectAll=!0);const a=o?{...e,limit:void 0,offset:void 0,orderBy:void 0,...n?{joins:void 0,joinFilters:void 0}:{},...i?{groupBy:void 0,having:void 0}:{}}:n?{...e,joins:void 0,joinFilters:void 0}:e,d={type:"select",table:this.selectedTable,where:t,limit:o?void 0:this.limitCount,offset:o?void 0:this.offsetCount,orderBy:o||this.orderByClauses.length===0?void 0:this.orderByClauses,distinct:this.isDistinct||void 0};if(d.plan=a,this.groupByColumns.length===0&&this.hasMixedAggregateSelection())throw new Error("Mixed aggregate and non-aggregate selections require groupBy columns");let l;if(!n&&!i&&!s?(this.selectedFields&&(d.select=this.selectedFields),l=await this.session.execute(d),l=this.applySubjectMetadata(l)):(n?d.select=void 0:!i&&!s?d.select=this.selectedFields:d.select=void 0,l=await this.session.execute(d),n||(l=this.applySubjectMetadata(l)),n&&(l=this.normalizeBaseRows(l),l=this.mergeRowsBySubject(l),l=await this.applyJoinFallback(l),l=this.applyJoinFilters(l))),i){let p=this.handleAggregateFallback(l);return p=this.applyHavingFilter(p),o&&(p=this.applyDeferredOrderBy(p),p=this.applyDeferredOffsetAndLimit(p)),p}let h=l;return n||(h=this.mergeRowsBySubject(h)),this.selectedTable&&(h=await this.hydrateInlineColumns(h,this.selectedTable,!n)),n&&(h=this.applyDeferredOrderBy(h)),this.selectedFields&&(h=h.map(p=>this.projectSelectedRow(p))),h=this.applyDistinctRows(h),n||(h=this.mergeRowsBySubject(h)),n&&(h=this.applyDeferredOffsetAndLimit(h)),h}}projectSelectedRow(e){return this.selectedFields?this.projectFieldMap(e,this.selectedFields):e}projectFieldMap(e,t,n=!0){const i={};for(const[s,o]of Object.entries(t))i[s]=this.projectFieldValue(e,s,o,n);return i}projectFieldValue(e,t,n,i=!0){if(isAggregateExpression(n))return i?e[t]:void 0;if(n instanceof PodTable)return this.projectTableValue(e,n);if(this.isSelectFieldMap(n)){const s=this.collectSelectionAliases(n),o=s.size===1&&!s.has(this.primaryAlias??""),a=this.projectFieldMap(e,n,!o);if(s.size===1){const[d]=Array.from(s);if(d&&d!==this.primaryAlias&&this.isProjectedValueEmpty(a))return null}return a}for(const s of this.resolveFieldBindingCandidates(t,n))if(e[s]!==void 0)return e[s];return i?e[t]:void 0}projectTableValue(e,t){const n=this.tableAliases.get(t)??t.config.name,i={};let s=!1;for(const o of Object.keys(t.columns)){const d=(n===this.primaryAlias?[o,`${n}.${o}`]:[`${n}.${o}`]).find(l=>e[l]!==void 0);i[o]=d?e[d]:void 0,i[o]!==void 0&&(s=!0)}return n!==this.primaryAlias&&!s?null:i}isSelectFieldMap(e){return!!e&&typeof e=="object"&&!(e instanceof PodColumnBase)&&!(e instanceof PodTable)&&!isAggregateExpression(e)}collectSelectionAliases(e){if(typeof e=="string"){const{alias:n}=this.parseColumnReferenceString(e);return new Set(n?[n]:this.primaryAlias?[this.primaryAlias]:[])}if(e instanceof PodColumnBase)return new Set([this.resolveColumnReference(e).alias]);if(e instanceof PodTable)return new Set([this.tableAliases.get(e)??e.config.name]);if(!this.isSelectFieldMap(e))return new Set;const t=new Set;for(const n of Object.values(e))for(const i of this.collectSelectionAliases(n))t.add(i);return t}isProjectedValueEmpty(e){if(e==null)return!0;if(Array.isArray(e))return e.length===0;if(typeof e=="object"){const t=Object.values(e);return t.length>0&&t.every(n=>this.isProjectedValueEmpty(n))}return!1}resolveFieldBindingCandidates(e,t){const n=new Set;if(typeof t=="string"){const{alias:i,column:s}=this.parseColumnReferenceString(t);n.add(t),n.add(s),i&&n.add(`${i}.${s}`)}else if(t instanceof PodColumnBase){const i=this.resolveColumnReference(t);n.add(`${i.alias}.${i.column}`),(!i.alias||i.alias===this.primaryAlias)&&n.add(t.name)}else if(t&&typeof t=="object"){const i=t.name;typeof i=="string"&&n.add(i)}return Array.from(n)}shouldUseProjectionFallback(){if(!this.selectedFields)return!1;const e=t=>!!(t instanceof PodTable||this.isSelectFieldMap(t));return Object.values(this.selectedFields).some(t=>e(t))}shouldUseAggregateFallback(){if(this.havingCondition)return!0;if(this.joins.length>0)return this.groupByColumns.length>0||this.hasAggregateSelection();if(this.groupByColumns.length>0||!this.selectedFields)return!1;const e=Object.values(this.selectedFields);return e.length>0&&e.every(t=>isAggregateExpression(t))}buildAggregateRow(e){const t={};if(!this.selectedFields)return t;for(const[n,i]of Object.entries(this.selectedFields))isAggregateExpression(i)&&(t[n]=this.computeAggregateValue(i,e));return t}computeAggregateValue(e,t){const n=this.resolveAggregateColumnRef(e);if(!n)return e.func==="count"?e.distinct?this.countDistinctRows(t):t.length:null;switch(e.func){case"count":return this.collectValuesForCount(n,t,!!e.distinct).length;case"sum":{const i=this.collectNumericValues(n,t,!!e.distinct);return i.length===0?null:i.reduce((s,o)=>s+o,0)}case"avg":{const i=this.collectNumericValues(n,t,!!e.distinct);return i.length===0?null:i.reduce((o,a)=>o+a,0)/i.length}case"min":{const i=this.collectNumericValues(n,t,!!e.distinct);return i.length===0?null:Math.min(...i)}case"max":{const i=this.collectNumericValues(n,t,!!e.distinct);return i.length===0?null:Math.max(...i)}default:return null}}resolveAggregateColumnRef(e){const t=e.column;if(t){if(typeof t=="string")return this.resolveColumnReference(t);if(t instanceof PodColumnBase)return this.resolveColumnReference(t);if(typeof t=="object"&&"name"in t){const n=t.name;if(typeof n=="string")return this.resolveColumnReference(n)}}}collectValuesForCount(e,t,n){const i=t.map(a=>this.getRowValueForColumn(a,e)).filter(a=>a!=null);if(!n)return i;const s=new Set,o=[];for(const a of i){const d=this.serializeValueForKey(a);s.has(d)||(s.add(d),o.push(a))}return o}collectNumericValues(e,t,n){const i=[],s=new Set;for(const o of t){const a=this.getRowValueForColumn(o,e);if(a==null)continue;const d=Number(a);if(!Number.isNaN(d))if(n){const l=this.serializeValueForKey(d);s.has(l)||(s.add(l),i.push(d))}else i.push(d)}return i}countDistinctRows(e){const t=new Set;for(const n of e){const i=this.serializeValueForKey(n);t.add(i)}return t.size}handleAggregateFallback(e){if(!this.selectedFields){if(this.groupByColumns.length===0)return e;const t=new Map;for(const n of e){const i=this.groupByColumns.map(o=>this.serializeValueForKey(this.getRowValueForColumn(n,o))),s=JSON.stringify(i);t.has(s)||t.set(s,n)}return Array.from(t.values())}return this.groupByColumns.length===0?[this.buildAggregateRow(e)]:this.buildGroupedAggregateRows(e)}buildGroupedAggregateRows(e){if(!this.selectedFields)return e;this.ensureGroupByValidity();const t=new Map;for(const i of e){const s=this.groupByColumns.map(a=>this.serializeValueForKey(this.getRowValueForColumn(i,a))),o=JSON.stringify(s);t.has(o)||t.set(o,{rows:[],first:i}),t.get(o)?.rows.push(i)}const n=[];for(const{rows:i,first:s}of t.values()){const o=this.buildAggregateRow(i),a={};for(const[d,l]of Object.entries(this.selectedFields))if(isAggregateExpression(l))a[d]=o[d];else{const h=this.resolveSelectFieldColumn(l);a[d]=h?this.getRowValueForColumn(s,h):void 0}n.push(a)}return n}ensureGroupByValidity(){if(!this.selectedFields)return;const e=this.groupByColumns.map(t=>`${t.alias}.${t.column}`);for(const t of Object.values(this.selectedFields)){if(isAggregateExpression(t))continue;const n=this.resolveSelectFieldColumn(t);if(!n)continue;const i=`${n.alias}.${n.column}`;if(!e.includes(i))throw new Error(`Column ${i} must appear in GROUP BY clause when mixed with aggregates`)}}resolveSelectFieldColumn(e){if(e instanceof PodColumnBase)return this.resolveColumnReference(e);if(typeof e=="string")return this.resolveColumnReference(e)}hasAggregateSelection(){return this.selectedFields?Object.values(this.selectedFields).some(e=>isAggregateExpression(e)):!1}hasMixedAggregateSelection(){if(!this.selectedFields)return!1;const e=Object.values(this.selectedFields),t=e.some(i=>isAggregateExpression(i)),n=e.some(i=>!isAggregateExpression(i));return t&&n}applySubjectMetadata(e){return e.map(t=>this.attachSubjectMetadata(t))}extractSubjectValue(e){const t=e.subject??e["@id"]??e.uri;if(typeof t=="object"&&t&&"value"in t){const n=t.value;return typeof n=="string"&&n.length>0?n:void 0}if(typeof t=="string"&&t.length>0)return t}attachSubjectMetadata(e){const t=this.extractSubjectValue(e);if(typeof t=="string"&&t.length>0&&(e["@id"]===void 0&&(e["@id"]=t),e.uri===void 0&&(e.uri=t),e.id===void 0)){const n=this.extractIdFromSubject(t,this.selectedTable);n!==void 0&&(e.id=n)}return e}normalizeBaseRows(e){if(!e.length)return e;const t=this.primaryAlias||this.ensureAliasForTable(this.selectedTable);return e.map(n=>{const i={...n};for(const[o,a]of Object.entries(n))o!==`${t}.${o}`&&(i[`${t}.${o}`]=a);const s=this.extractSubjectValue(n);if(s){i.subject=s,i["@id"]=s,i.uri=s,i[`${t}.subject`]=s,i[`${t}.@id`]=s,i[`${t}.uri`]=s;const o=this.extractIdFromSubject(s,this.selectedTable);o!==void 0&&(i.id===void 0&&(i.id=o),(this.shouldUseSubjectIdentityColumn(this.selectedTable,"id")||i[`${t}.id`]===void 0)&&(i[`${t}.id`]=o))}return i})}async hydrateInlineColumns(e,t,n=!0){if(!e.length)return e;const i=Object.values(t.columns??{}).filter(E=>this.isInlineObjectColumn(E));if(i.length===0)return e;n&&(e=this.mergeRowsBySubject(e));const s=new Map;i.forEach(E=>{const w=E.getPredicate(t.config.namespace);s.set(w,E)});const o=Array.from(new Set(e.map(E=>this.normalizeInlineIri(E["@id"]??E.subject??E.uri??E.id)).filter(E=>!!E)));if(o.length===0||s.size===0)return e;const a=Array.from(s.keys()).map(E=>`<${E}>`).join(" "),d=this.session.getDialect().getSPARQLExecutor(),l=[],h=new Map;for(const E of o){const w=this.inferSourceFromChild(E,t),T=h.get(w)??[];T.push(E),h.set(w,T)}for(const[E,w]of h.entries()){const I={type:"SELECT",query:`SELECT ?parent ?linkPred ?child ?pred ?obj WHERE {
|
|
33
|
+
LIMIT 50`,prefixes:{}},l=i.kind==="sparql"?await this.dialect.executeOnResource(i.resourceUrl,d,i.descriptor):await this.dialect.getSPARQLExecutor().queryContainer(i.resourceUrl,d),h=Array.from(new Set(l.map(p=>this.extractSubjectFromLookupRow(p)).filter(p=>!!p).filter(p=>this.subjectMatchesShortId(e,p,t,s))));if(h.length>1)throw new Error(`${n} found multiple resources for short id '${t}' in '${e.config?.name??"resource"}'. Use a base-relative resource id or full IRI to disambiguate.`);return h[0]??this.getIndexedSubject(e,t)}async resolveIdSubjectForExactOperation(e,t,n){return this.needsShortIdSubjectLookup(e,t)?await this.lookupSubjectIriByShortId(e,t,n):this.resolveIdSubject(e,t,n)}async findById(e,t){const n=await this.resolveIdSubjectForExactOperation(e,t,"findById");return n?await this.findByIri(e,n):null}async findByLocator(e,t){this.warnFindByLocatorDeprecation();const n=this.resolveLocatorSubject(e,t,"findByLocator");return await this.findByIri(e,n)}async findByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.findById(e,t);const n=this.resolveResourceTargetIri(e,t,"findByResource");return await this.findByIri(e,n)}async findByIri(e,t){if(!t||typeof t!="string")throw new Error("findByIri requires a valid IRI string");const n=await this.findByIriViaExactResource(e,t);return n!==void 0?n:(await this.session.select().from(e).whereByIri(t).limit(1))[0]??null}getColumnPredicate(e,t){return t.options?.predicate??t.getPredicate?.(e.config.namespace)}async findByIriViaExactResource(e,t){if(!isPodTable(e))return;const n=this.parseIri(t).documentUrl,i=await this.readPredicateObjectRowsFromDocument(n,t);if(i===null)return null;if(i!==void 0){const d=this.mapPredicateObjectRows(e,t,i);if(d!==void 0)return d}if(typeof this.dialect.executeOnResource!="function")return;const s={type:"SELECT",query:`SELECT ?p ?o WHERE { <${t}> ?p ?o . }`,prefixes:{}};let o;try{o=await this.dialect.executeOnResource(n,s)}catch(d){if(this.isMissingExactResourceError(d))return;throw d}const a=this.mapPredicateObjectRows(e,t,o);if(a!==void 0)return a}async readPredicateObjectRowsFromDocument(e,t){const n=this.dialect.getAuthenticatedFetch;if(typeof n!="function")return;let i;try{i=await n.call(this.dialect)(e,{method:"GET",headers:{Accept:"text/turtle, application/ld+json;q=0.8, */*;q=0.1"}})}catch(a){return this.isMissingExactResourceError(a)?null:void 0}if(i.status===404)return null;if(!i.ok)return;const s=i.headers.get("content-type")??"";if(s&&!s.includes("text/turtle")&&!s.includes("application/n-triples")&&!s.includes("application/trig")&&!s.includes("application/ld+json"))return;const o=await i.text();if(!o.trim())return null;try{return new N3Parser$1({baseIRI:e,format:s.includes("application/n-triples")?"N-Triples":"text/turtle"}).parse(o).filter(l=>l.subject.termType==="NamedNode"&&l.subject.value===t).map(l=>({p:l.predicate.value,o:this.convertRdfTermToValue(l.object)}))}catch{return}}convertRdfTermToValue(e){if(e.termType==="NamedNode")return e.value;if(e.termType==="BlankNode")return`_:${e.value}`;if(e.termType!=="Literal")return e.value;const t=e.datatype?.value??"";if(t.includes("#integer")||t.includes("#int"))return parseInt(e.value,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e.value);if(t.includes("#boolean"))return e.value==="true";if(t.includes("#dateTime"))return new Date(e.value);if(t.includes("#json"))try{return JSON.parse(e.value)}catch{return e.value}return e.value}isMissingExactResourceError(e){if(!isRecord$2(e))return!1;if((e.status??e.statusCode)===404)return!0;const n=e.message;return typeof n=="string"&&/\b(?:HTTP status )?404\b/.test(n)}mapPredicateObjectRows(e,t,n){if(!Array.isArray(n)||n.length===0)return null;const i={subject:t,"@id":t,uri:t},s=this.extractIdFromIri(e,t);s!==void 0&&(i.id=s);let o=!1,a=!1,d=!1;for(const l of n){if(!isRecord$2(l))continue;const h=l.p??l.predicate??l["?p"],p=l.o??l.object??l["?o"];if(typeof h=="string"){h==="http://www.w3.org/1999/02/22-rdf-syntax-ns#type"&&p===e.config.type&&(o=!0);for(const[g,S]of Object.entries(e.columns??{})){if(S._virtualId)continue;const y=this.getColumnPredicate(e,S);if(!y||y==="@id"||y!==h)continue;if(S.options?.isArray||S.dataType==="array"){const E=Array.isArray(i[g])?i[g]:i[g]===void 0?[]:[i[g]];i[g]=[...E,p]}else i[g]===void 0&&(i[g]=p);S.dataType==="object"&&typeof p=="string"&&isAbsoluteIri(p)&&(d=!0),a=!0}}}if(!o&&!a)return null;if(!d)return i}extractIdFromIri(e,t){const n=parsePodResourceRef(e,t);if(n)return n.templateValues.id??n.resourceId;try{const a=this.dialect.getResolver(e).parseId(e,t);if(a)return a}catch{}const i=e.getSubjectTemplate?.()??e.config?.subjectTemplate;if(!i)return;if(i==="{id}.ttl"){const a=t.split("/").pop()??"";return a.endsWith(".ttl")?a.slice(0,-4):a||void 0}if(i==="{id}.ttl#it"){const d=t.split("#")[0].split("/").pop()??"";return d.endsWith(".ttl")?d.slice(0,-4):d||void 0}const s=t.indexOf("#");if(s>=0&&i.includes("{id}")&&i.startsWith("#"))return decodeURIComponent(t.slice(s+1));const o=t.split("#")[0].split("/").pop()??"";return o.endsWith(".ttl")?o.slice(0,-4):void 0}parseIri(e){const t=e.indexOf("#");return t>=0?{documentUrl:e.substring(0,t),fragment:e.substring(t+1)}:{documentUrl:e,fragment:null}}async subscribeByIri(e,t,n){if(!t||typeof t!="string")throw new Error("subscribeByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`subscribeByIri requires an absolute IRI, got: ${t}`);if(!this.notificationsClient){const o=this.dialect.getAuthenticatedFetch(),a={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(o,a)}const{documentUrl:i}=this.parseIri(t),s=await this.notificationsClient.subscribe(i,{channel:n.channel,features:n.features,onNotification:async o=>{try{if(o.type==="Update"){const a=await this.findByIri(e,t);a&&await n.onUpdate(a)}else o.type==="Delete"&&await n.onDelete?.()}catch(a){n.onError?.(a)}},onError:n.onError});return()=>s.unsubscribe()}async updateByIri(e,t,n){if(!t||typeof t!="string")throw new Error("updateByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`updateByIri requires an absolute IRI, got: ${t}`);const i=n;return await this.session.update(e).set(i).whereByIri(t),await this.findByIri(e,t)}async updateById(e,t,n){const i=await this.resolveIdSubjectForExactOperation(e,t,"updateById");return i?await this.updateByIri(e,i,n):null}async updateByLocator(e,t,n){const i=this.resolveLocatorSubject(e,t,"updateByLocator");return await this.updateByIri(e,i,n)}async updateByResource(e,t,n){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.updateById(e,t,n);const i=this.resolveResourceTargetIri(e,t,"updateByResource");return await this.updateByIri(e,i,n)}async deleteByIri(e,t){if(!t||typeof t!="string")throw new Error("deleteByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`deleteByIri requires an absolute IRI, got: ${t}`);return await this.findByIri(e,t)?(await this.session.delete(e).whereByIri(t),!0):!1}async deleteById(e,t){const n=await this.resolveIdSubjectForExactOperation(e,t,"deleteById");return n?await this.deleteByIri(e,n):!1}async deleteByLocator(e,t){const n=this.resolveLocatorSubject(e,t,"deleteByLocator");return await this.deleteByIri(e,n)}async deleteByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.deleteById(e,t);const n=this.resolveResourceTargetIri(e,t,"deleteByResource");return await this.deleteByIri(e,n)}async transaction(e){return await this.session.transaction(async t=>{const n=new PodDatabase(this.dialect,t,this.schema);return await e(n)})}getDialect(){return this.dialect}getSession(){return this.session}getSchema(){return this.schema}get discovery(){return this.dialect.getDiscovery()}async connect(){return await this.dialect.connect()}async disconnect(){return this.notificationsClient&&this.notificationsClient.unsubscribeAll(),await this.dialect.disconnect()}async subscribe(e,t){if(!this.notificationsClient){const s=this.dialect.getAuthenticatedFetch(),o={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(s,o)}const n=this.resolveResourceTopic(e,t.iri),i={channel:t.channel,features:t.features,onNotification:s=>{if(t.onNotification?.(s),!!(t.onCreate||t.onUpdate||t.onDelete||t.onAdd||t.onRemove)){const a={id:s.id,type:s.type,object:s.object,published:s.published,state:s.state};switch(s.type){case"Create":t.onCreate?.(a);break;case"Update":t.onUpdate?.(a);break;case"Delete":t.onDelete?.(a);break;case"Add":t.onAdd?.(a);break;case"Remove":t.onRemove?.(a);break}}},onError:t.onError,onClose:t.onClose};return this.notificationsClient.subscribe(n,i)}resolveResourceTopic(e,t){if(t){if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`iri must be an absolute URL, got: ${t}`);return t}const n=e.config.base||"";if(n.startsWith("http://")||n.startsWith("https://"))return n;const i=this.dialect.getPodUrl(),s=i.endsWith("/")?i:`${i}/`,o=n.startsWith("/")?n.slice(1):n;return`${s}${o}`}getConfig(){return this.dialect.getConfig()}async discoverTable(e){const t=await this.dialect.discoverDataLocations(e);if(t.length===0)return console.log(`[discoverTable] No data locations found for ${e}`),null;const n=t[0],i=n.shapes[0]?.url;if(console.log(`[discoverTable] Found location: ${n.container}, shape: ${i||"none"}`),i){const l=this.dialect.getShapeManager(),h=await l.loadShape(i,this.dialect.getAuthenticatedFetch());if(h){console.log(`[discoverTable] Loaded shape with ${h.properties.length} properties`);const p=l.shapeToTable(h,n.container);return await this.init(p.table),p.table}}console.log("[discoverTable] No shape available, creating basic table");const{podTable:s,string:o}=await __vitePreload(async()=>{const{podTable:l,string:h}=await import("./index-D6dB-UNq.js");return{podTable:l,string:h}},__vite__mapDeps([0,1,2,3,4,5,6])),a=this.extractClassName(e),d=s(a,{id:o("id").primaryKey()},{type:e,base:n.container});return await this.init(d),d}async discoverTables(e){const t=[];for(const n of e){const i=await this.discoverTable(n);i&&t.push(i)}return t}async discover(e,t){return this.dialect.discoverDataLocations(e,t)}async discoverAll(){return this.dialect.discoverAll()}async discoverByApp(e){return this.dialect.discoverByApp(e)}async locationToTable(e,t){const n=t??{};let i;if(n.shape)typeof n.shape=="string"?(i=e.shapes.find(l=>l.url===n.shape),i||(i={url:n.shape,source:"config"})):i=n.shape;else if(n.appId){if(i=e.shapes.find(l=>l.registeredBy===n.appId),!i)throw new Error(`[locationToTable] No shape found for appId: ${n.appId}`)}else i=e.shapes[0];if(i?.url){const l=this.dialect.getShapeManager(),h=await l.loadShape(i.url,this.dialect.getAuthenticatedFetch());if(h){console.log(`[locationToTable] Loaded shape: ${i.url} (${h.properties.length} properties)`),i.registeredBy&&console.log(`[locationToTable] -> registeredBy: ${i.registeredBy}`);const p=l.shapeToTable(h,e.container);return await this.init(p.table),p.table}}console.log(`[locationToTable] No shape available, creating basic table for container: ${e.container}`);const{podTable:s,string:o}=await __vitePreload(async()=>{const{podTable:l,string:h}=await import("./index-D6dB-UNq.js");return{podTable:l,string:h}},__vite__mapDeps([0,1,2,3,4,5,6])),a=this.extractContainerName(e.container),d=s(a,{id:o("id").primaryKey()},{type:"http://www.w3.org/2000/01/rdf-schema#Resource",base:e.container});return await this.init(d),d}extractContainerName(e){const t=e.replace(/\/$/,""),n=t.lastIndexOf("/");return n>=0&&t.substring(n+1).toLowerCase()||"data"}async discoverTablesFor(e,t,n){const i=await this.discover(e,t),s=[];for(const o of i){const a=await this.locationToTable(o,n);s.push(a)}return s}extractClassName(e){const t=e.lastIndexOf("#");if(t>=0)return e.substring(t+1).toLowerCase();const n=e.lastIndexOf("/");return n>=0?e.substring(n+1).toLowerCase():e.toLowerCase()}addSource(e){this.dialect.addSource(e)}removeSource(e){this.dialect.removeSource(e)}getSources(){return this.dialect.getSources()}async addSourcesFromTypeIndex(){return await this.dialect.addSourcesFromTypeIndex()}async init(...e){let t,n;const i=e[e.length-1];i&&typeof i=="object"&&!Array.isArray(i)&&!("columns"in i)?(t=i,n=e.slice(0,-1)):n=e;const s=[];for(const o of n)if(o)if(Array.isArray(o))for(const a of o)a&&s.push(a);else s.push(o);for(const o of s)if(typeof o.init=="function"?await o.init(this.dialect):await this.dialect.registerTable(o),t?.generateShape||t?.saveShape){const a=this.dialect.getShapeManager(),d=a.generateShape(o);if(t?.saveShape){const l=this.dialect.getPodUrl();let h=t.shapeLocation;h?h.startsWith("http")||(h=`${l}${h.replace(/^\//,"")}`):h=`${l}shapes/`,h.endsWith("/")||(h+="/");const p=`${h}${o.config.name}Shape.ttl`;try{await a.saveShape(d,p),console.log(`[init] Shape saved to: ${p}`)}catch(g){console.warn(`[init] Failed to save Shape to ${p}:`,g)}}}}get query(){return this.queryProxy||(this.queryProxy=this.buildQueryProxy()),this.queryProxy}buildQueryProxy(){const e=this.schema&&typeof this.schema=="object"?Object.entries(this.schema):[],t=new Map;for(const[s,o]of e)isPodTable(o)&&t.set(s,o);const n=(s,o)=>{const a=I=>{let C=null;const O=()=>(C||(C=I()),C);return{then:(P,D)=>O().then(P,D),catch:P=>O().catch(P),finally:P=>O().finally(P),[Symbol.toStringTag]:"Promise"}},d=(I,C,O)=>{const P={};for(const[D,Y]of Object.entries(C)){if(Y instanceof PodColumnBase){P[D]=I[Y.name];continue}if(typeof Y=="string"){P[D]=I[Y]??I[Y.split(".").pop()??Y];continue}const re=Y?.name;if(typeof re=="string"){P[D]=I[re];continue}P[D]=I[D]}if(O)for(const D of Object.keys(O))P[D]=I[D]??[];return P},l=async I=>{this.clearFederatedErrors();let C=this.session.select().from(o);I?.where&&(C=C.where(I.where)),I?.orderBy&&(Array.isArray(I.orderBy)?I.orderBy:[I.orderBy]).forEach(Y=>{C=C.orderBy(Y.column,Y.direction??"asc")}),typeof I?.limit=="number"&&(C=C.limit(I.limit)),typeof I?.offset=="number"&&(C=C.offset(I.offset));let O=await C;I?.with&&Object.keys(I.with).length>0&&(O=await this.eagerLoadWith(O,o,I.with,t));const P=I?.columns;return P&&(O=O.map(D=>d(D,P,I.with))),O},h=I=>a(()=>l(I)),p=async(I,C)=>{if(!I)return null;let O=[I];C?.with&&Object.keys(C.with).length>0&&(O=await this.eagerLoadWith(O,o,C.with,t));const P=C?.columns;return P&&(O=O.map(D=>d(D,P,C.with))),O[0]??null},g=I=>a(async()=>(await l({...I,limit:1}))[0]??null),S=I=>a(async()=>(await l({where:I?.where,columns:void 0,limit:void 0,offset:void 0})).length),y=()=>(I,C)=>a(async()=>await p(await this.findByLocator(o,I),C)),v=()=>(I,C)=>a(async()=>await p(await this.findById(o,I),C)),E=()=>(I,C)=>a(async()=>await p(await this.findByIri(o,I),C)),w=()=>(I,C)=>a(async()=>await p(await this.findByResource(o,I),C));return{findMany:h,findFirst:g,find:(I,C)=>w()(I,C),findById:v(),findByLocator:y(),findByIri:E(),findByResource:w(),count:S}},i={};return new Proxy(i,{get:(s,o)=>{if(typeof o!="string")return;const a=t.get(o);if(a)return n(o,a)}})}async eagerLoadWith(e,t,n,i){if(!e||e.length===0)return e;const s=this.dedupeBySubject(e);for(const[o,a]of Object.entries(n)){if(!a)continue;const d=t.relations?.[o],l=typeof a=="object"&&a.table?a.table:d?.table??i.get(o);if(!l)continue;if(isSolidSchema(l)||d?.isFederated){if(d&&d.discover)try{const Y=await this.getFederatedExecutor().execute(s,{...d,relationName:o});Y.errors&&Y.errors.length>0&&this.lastFederatedErrors.push(...Y.errors)}catch(D){console.warn(`Federated relation "${o}" failed:`,D),s.forEach(Y=>{Y[o]=[]})}else console.warn(`Federated relation "${o}" missing discover function, skipping.`),s.forEach(D=>{D[o]=[]});continue}const h=l,p=h.config.type,g=d?.fields&&d.fields.length>0?d.fields:Object.values(h.columns??{}),S=D=>!!(D&&(D.options?.linkTarget===t.config.type||D.options?.linkTable===t||D.getLinkTable?.()===t)),y=D=>!!(D&&(D.options?.linkTarget===p||D.options?.linkTable===h||D.getLinkTable?.()===h)),v=d?.fields&&d.fields.length>0?g:g.filter(D=>S(D)&&!D.isInverse?.());if(v.length===0){const Y=(d?.references??[]).filter(ke=>!!(ke&&typeof ke.isInverse=="function"&&ke.isInverse()&&y(ke))),re=Object.values(t.columns??{}),$=(Y.length>0?Y:re).filter(ke=>typeof ke.isInverse=="function"&&ke.isInverse()&&y(ke));if($.length===0)continue;const te=s.map(ke=>this.collectInverseLinkValues(ke,$)),be=Array.from(new Set(te.flat().filter(ke=>typeof ke=="string"&&ke.length>0)));if(be.length===0){e.forEach(ke=>{ke[o]=[]});continue}let fe=this.session.select().from(h);fe=fe.whereByIri(be);const Pe=await fe,Ue=this.groupRowsByIri(Pe);s.forEach((ke,Ge)=>{const Ae=te[Ge],we=[];Ae.forEach(ie=>{const xe=Ue.get(ie);xe&&xe.length>0&&we.push(...xe)}),ke[o]=we});continue}const E=v[0],w=d?.references&&d.references[0],T=E.isLink(),I=s.map(D=>this.resolveParentKey(D,w,T)).filter(D=>typeof D=="string"&&D.length>0);if(I.length===0)continue;let C=this.session.select().from(h);T?C=C.where(inArray(E,I)):C=C.where({[E.name]:I});const O=await C,P=new Map;for(const D of O){const Y=D[E.name],re=this.normalizeLiteralValue(Y),$=T?this.collectLinkLookupKeys(Y):re?[re]:[];for(const te of $){const be=P.get(te)??[];be.push(D),P.set(te,be)}}s.forEach(D=>{const Y=T?Array.from(new Set([this.resolveParentKey(D,w,!0),this.resolveIdFromRow(D)].filter($=>typeof $=="string"&&$.length>0))):[this.resolveParentKey(D,w,!1)].filter($=>typeof $=="string"&&$.length>0),re=[];for(const $ of Y){const te=P.get($)??[];for(const be of te)re.includes(be)||re.push(be)}D[o]=re})}return s}dedupeBySubject(e){const t=new Map,n=[];for(const i of e){const s=this.resolveIriFromRow(i)??this.resolveIdFromRow(i);if(!s){n.push(`__anon_${n.length}`),t.set(n[n.length-1],{...i});continue}if(!t.has(s)){t.set(s,{...i}),n.push(s);continue}const o=t.get(s);if(o)for(const[a,d]of Object.entries(i)){if(d===void 0)continue;const l=o[a];if(l===void 0){o[a]=d;continue}const h=Array.isArray(l)?l:[l],p=Array.isArray(d)?d:[d],g=[...h];for(const S of p)g.some(y=>y===S)||g.push(S);o[a]=g.length===1?g[0]:g}}return n.map(i=>t.get(i)).filter(i=>i!==void 0)}resolveIdFromRow(e){if(!e)return;if(typeof e.id=="string"&&e.id.length>0)return e.id;const t=typeof e["@id"]=="string"?e["@id"]:void 0;if(t)return this.extractFragment(t)}resolveParentKey(e,t,n){if(t){const i=e[t.name];return n?this.normalizeLinkValue(i):this.normalizeLiteralValue(i)}return n?this.resolveIriFromRow(e):this.resolveIdFromRow(e)}resolveIriFromRow(e){if(e){if(typeof e["@id"]=="string"&&e["@id"].length>0)return e["@id"];if(typeof e.subject=="string"&&e.subject.length>0)return e.subject}}collectLinkLookupKeys(e){const t=[],n=this.normalizeLinkValue(e)??this.normalizeLiteralValue(e);if(n){t.push(n);const i=this.extractFragment(n);i&&!t.includes(i)&&t.push(i)}return t}normalizeLinkValue(e){if(e){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}normalizeLiteralValue(e){if(e!=null){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}collectInverseLinkValues(e,t){if(!t.length)return[];const n=[];for(const i of t){const s=e[i.name];if(s==null)continue;const o=a=>{const d=this.normalizeLinkValue(a)??(typeof a=="string"?a:void 0);d&&n.push(d)};Array.isArray(s)?s.forEach(o):o(s)}return n}groupRowsByIri(e){const t=new Map;for(const n of e){const i=this.normalizeLinkValue(n["@id"])??this.normalizeLinkValue(n.uri)??(typeof n["@id"]=="string"?n["@id"]:void 0);if(!i)continue;const s=t.get(i)??[];s.push(n),t.set(i,s)}return t}extractFragment(e){const t=e.includes("#")?e.split("#").pop():void 0;return t&&t.length>0?t:e.split("/").pop()??e}}_a$8=entityKind;PodDatabase[_a$8]="PodDatabase";PodDatabase.findByLocatorDeprecationWarned=!1;function isAggregateExpression(r){return!!r&&typeof r=="object"&&r.kind==="aggregate"}function inferSPARQLQueryType(r){const n=r.replace(/^\s*#.*$/gm,"").trim().replace(/^(?:\s*(?:PREFIX|BASE)\s+[^\n]+\n)*/i,"").trim().match(/^(SELECT|ASK|INSERT|DELETE|UPDATE|WITH|LOAD|CLEAR|CREATE|DROP|COPY|MOVE|ADD|CONSTRUCT|DESCRIBE)\b/i)?.[1]?.toUpperCase();switch(n){case"SELECT":case"ASK":case"INSERT":case"DELETE":case"UPDATE":return n;case"WITH":case"LOAD":case"CLEAR":case"CREATE":case"DROP":case"COPY":case"MOVE":case"ADD":return"UPDATE";default:return}}function createLiteralCondition(r,e,t){const n=r?`${r}.${e}`:e;return t==null?new UnaryExpression("IS NULL",n):Array.isArray(t)?new BinaryExpression(n,"IN",t):new BinaryExpression(n,"=",t)}function buildConditionTreeFromObject(r,e){if(!r)return;const t=Object.entries(r);if(t.length===0)return;const n=t.map(([i,s])=>createLiteralCondition(e,i,s));return n.length===1?n[0]:new LogicalExpression("AND",n)}function resolveRowSubject(r){if(!(!r||typeof r!="object")){if(typeof r["@id"]=="string"&&r["@id"].length>0)return r["@id"];if(typeof r.subject=="string"&&r.subject.length>0)return r.subject;if(typeof r.uri=="string"&&r.uri.length>0)return r.uri;if(typeof r.source=="string"&&r.source.length>0)return r.source;if(typeof r.id=="string"&&r.id.length>0)return r.id}}function orderRowsBySubjects(r,e){if(!r.length||!e.length)return r;const t=new Map,n=[];for(const s of r){const o=resolveRowSubject(s);if(!o){n.push(s);continue}const a=t.get(o)??[];a.push(s),t.set(o,a)}const i=[];for(const s of e){const o=t.get(s);o?.length&&(i.push(...o),t.delete(s))}for(const s of t.values())i.push(...s);return i.push(...n),i}function isSelectFieldMap(r){return!!r&&typeof r=="object"&&!(r instanceof PodColumnBase)&&!(r instanceof PodTable)&&!("aggregateType"in r)}function resolveFieldBindingCandidates(r,e){const t=new Set;if(typeof e=="string"){if(t.add(e),e.includes(".")){const[n,i]=e.split(".",2);i&&(t.add(`${n}.${i}`),t.add(i))}}else e instanceof PodColumnBase&&(e.table?.config?.name&&t.add(`${e.table.config.name}.${e.name}`),t.add(e.name));return Array.from(t)}function isEmptyProjectedValue(r){if(r==null)return!0;if(Array.isArray(r))return r.length===0;if(typeof r=="object"){const e=Object.values(r);return e.length>0&&e.every(t=>isEmptyProjectedValue(t))}return!1}function projectTableRow(r,e){const t=e.config.name,n={};let i=!1;for(const s of Object.keys(e.columns)){const a=(t?[`${t}.${s}`,s]:[s]).find(d=>r[d]!==void 0);n[s]=a?r[a]:void 0,n[s]!==void 0&&(i=!0)}return i?n:null}function projectFieldValue(r,e,t){if(t instanceof PodTable)return projectTableRow(r,t);if(isSelectFieldMap(t)){const n={};for(const[i,s]of Object.entries(t))n[i]=projectFieldValue(r,i,s);return isEmptyProjectedValue(n)?null:n}for(const n of resolveFieldBindingCandidates(e,t))if(r[n]!==void 0)return r[n];return r[e]}function projectReturningRow(r,e){if(!e||e===!0)return r;const t={};for(const[n,i]of Object.entries(e))t[n]=projectFieldValue(r,n,i);return t}function projectReturningRows(r,e){return!e||e===!0?r:r.map(t=>projectReturningRow(t,e))}const UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,SINGLETON_FRAGMENTS=new Set(["#me","#this","#profile","#card"]);class UriResolverImpl{constructor(e=""){this.podUrl=e.replace(/\/$/,"")}setPodUrl(e){this.podUrl=e.replace(/\/$/,"")}resolveSubject(e,t,n,i){const s=i?.strict??!0,o=t["@id"]??t.id??t.uri;if(typeof o=="string"){if(this.isAbsoluteUri(o))return o;const h=this.resolveBaseRelativeSubjectId(e,o);if(h)return h;o.startsWith("#")&&this.acceptsFragmentOnlyResourceId(e)&&(t={...t,id:o.slice(1)})}const a=this.getEffectivePattern(e),d=this.getSubjectBaseUrl(e);if(this.isSingleton(e))return this.combineBaseAndPattern(d,a);const l=this.applyTemplate(a,t,n,e,s);return l===null?this.generateFallbackUri(d,a,n):this.isAbsoluteUri(l)?l:this.combineBaseAndPattern(d,l)}parseSubject(e,t){if(!e)return null;const n=e.indexOf("#"),i=n!==-1,s=i?e.slice(0,n):e,o=i?e.slice(n+1):void 0,a=this.extractPublicId(e,t),d=this.getResourceMode(t);return{uri:e,resourceUrl:s,fragment:o,id:a,mode:d}}getResourceUrl(e){const t=e.indexOf("#");return t!==-1?e.slice(0,t):e}getResourceMode(e){if(!(e.hasCustomTemplate?.()??!1)){const i=e.config?.base??"";return/\.(ttl|jsonld|json)$/i.test(i)?"fragment":"document"}return(e.config?.subjectTemplate??this.getDefaultPattern(e)).startsWith("#")?"fragment":"document"}getDefaultPattern(e){return"{id}"}resolveInlineChild(e,t,n,i){const s=n["@id"]??n.id;return typeof s=="string"?s:buildInlineChildUri(e,t,i)}isSingleton(e){const t=e.config?.subjectTemplate;return t?!!(SINGLETON_FRAGMENTS.has(t)||!t.includes("{")):!1}resolveLink(e,t,n){const i=String(e??""),s=n?.record&&typeof n.record=="object"?n.record:void 0;if(this.isAbsoluteUri(i))return i;if(i.startsWith("/")||i.startsWith("#")){const h=n?.baseUri||this.podUrl;if(h)try{return new URL(i,h).toString()}catch{}throw new Error(`Cannot resolve relative URI "${i}": no baseUri configured`)}const o=t.getLinkTable?.();if(o){const h=this.getTableUriInfo(o);if(h)return this.buildFullUri(i,h.baseUrl,h.subjectTemplate,o,n,s);throw new Error(`Cannot resolve URI "${i}": linked table "${o.config?.name}" has no base configured.`)}const a=t.getLinkTableName?.();if(a){if(n?.tableNameRegistry){const p=n.tableNameRegistry.get(a);if(p){const g=this.getTableUriInfo(p);if(g)return this.buildFullUri(i,g.baseUrl,g.subjectTemplate,p,n,s)}}const h=n?.tableNameRegistry?Array.from(n.tableNameRegistry.keys()).join(", "):"(no tables registered)";throw new Error(`Cannot resolve URI "${i}": table "${a}" not found in schema. Available tables: ${h}`)}const d=t.getLinkTarget?.();if(d){if(!n?.tableRegistry)throw new Error(`Cannot resolve URI "${i}" (links to ${d}): tableRegistry not configured. Ensure the schema is properly registered.`);const h=n.tableRegistry.get(d);if(h&&h.length>0){if(h.length>1){const S=h.map(y=>y.config?.name||"unknown").join(", ");throw new Error(`Ambiguous link target: class "${d}" has multiple tables [${S}]. Use .link('tableName') or .link(tableObject) to specify which table to use.`)}const p=h[0],g=this.getTableUriInfo(p);if(g)return this.buildFullUri(i,g.baseUrl,g.subjectTemplate,p,n,s)}throw new Error(`Cannot resolve URI "${i}": class "${d}" not found in tableRegistry. Available classes: ${Array.from(n.tableRegistry.keys()).join(", ")||"(none)"}`)}const l=n?.baseUri||this.podUrl;if(l&&this.isAbsoluteUri(l)){const h=l.endsWith("/")?l:`${l}/`;return this.buildFullUri(i,h)}throw new Error(`Cannot resolve URI "${i}". Either provide a full URI (https://...), or configure baseUri.`)}isAbsoluteUri(e){return!e||typeof e!="string"?!1:e.includes(":")&&(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("urn:")||e.startsWith("did:")||e.startsWith("mailto:")||e.startsWith("tel:")||e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))}isLinkColumn(e){return e?e.dataType==="uri"||e.isLink?.()||!!e.options?.linkTarget||!!e.options?.linkTableName||!!e.options?.linkTable:!1}findTargetTable(e,t){const n=e.getLinkTable?.()||e.options?.linkTable;if(n)return n;const i=e.getLinkTableName?.()||e.options?.linkTableName;if(i&&t?.tableNameRegistry){const o=t.tableNameRegistry.get(i);if(o)return o}const s=e.getLinkTarget?.()||e.options?.linkTarget;if(s&&t?.tableRegistry){const o=t.tableRegistry.get(s);if(o&&o.length===1)return o[0]}}extractLinkId(e,t,n){if(e?.startsWith("/")){const o=n?.baseUri||this.podUrl;if(o){const a=o.endsWith("/")?o:`${o}/`;e=new URL(e.replace(/^\/+/,""),a).toString()}}if(!e||!this.isAbsoluteUri(e))return e;const i=this.findTargetTable(t,n);if(!i)return e;const s=this.extractTemplateIdFromSubject(e,i);return s||e}getTableUriInfo(e){const t=e.config?.base;if(!t)return;const n=e.config?.subjectTemplate;return{baseUrl:this.toAbsoluteUrl(t),subjectTemplate:n}}buildFullUri(e,t,n,i,s,o){const a=String(e??"");if(!n){const g=this.combineBaseAndResourceId(t,a);return this.assertNoUnresolvedTemplate(g,void 0,i),g}if(!UUID_REGEX.test(a)&&a.includes("/")&&!a.includes("{")){const g=`${t}${a}`;return this.assertNoUnresolvedTemplate(g,n,i),g}const d=this.buildTemplateRecord(a,n,i,s,o),l=this.applyTemplate(n,d,void 0,i,!0,s);if(l===null)throw new Error(`[UriResolver] Failed to resolve URI template "${n}" for table "${i?.config?.name??"unknown"}"`);if(this.isAbsoluteUri(l))return this.assertNoUnresolvedTemplate(l,n,i),l;if(l.startsWith("#")){const S=`${t.endsWith("/")?t.slice(0,-1):t}${l}`;return this.assertNoUnresolvedTemplate(S,n,i),S}const p=`${t.endsWith("/")?t:`${t}/`}${l}`;return this.assertNoUnresolvedTemplate(p,n,i),p}buildTemplateRecord(e,t,n,i,s){const o={...s??{}};o.id=e;for(const a of t.matchAll(/\{([^}]+)\}/g)){const l=this.parseTemplateVariable(a[1]).field;if(l==="id"||l==="index"||l in o)continue;const h=this.resolveTemplateVariable(l,n,i,s);h!=null&&h!==""&&(o[l]=h)}return o}resolveTemplateVariable(e,t,n,i){if(!i||typeof i!="object")return;if(e in i){const d=t?.columns?.[e];return this.normalizeValue(i[e],d,n)}const s=`${e}Id`;if(s in i)return String(i[s]);const o=t?.columns?.[e],a=o?this.findTargetTable(o,n):void 0;if(a)for(const[d,l]of Object.entries(i)){const h=n?.currentTable?.columns?.[d];if((h?this.findTargetTable(h,n):void 0)===a)return this.normalizeValue(l,o,n)}}assertNoUnresolvedTemplate(e,t,n){if(/\{[^}]+\}/.test(e)){const i=n?.config?.name||"unknown";throw new Error(`[UriResolver] Unresolved URI template variable while resolving table "${i}" with template "${t??"<exact-id>"}": ${e}`)}}getEffectivePattern(e){if(e.hasCustomTemplate?.()??!1){const n=e.config?.subjectTemplate;if(n&&n.trim().length>0)return n}return this.getDefaultPattern(e)}getSubjectBaseUrl(e){const t=e.config?.base??"";return this.toAbsoluteUrl(t)}isBaseRelativeSubjectId(e){return!e||this.isAbsoluteUri(e)||e.startsWith("/")?!1:e.startsWith("#")||e.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(e)}acceptsFragmentOnlyResourceId(e){const t=e.config?.subjectTemplate;if(!t)return!1;const n=Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>this.parseTemplateVariable(i[1]).field);return t==="#{id}"||t.startsWith("#")&&n.length===1&&n[0]==="id"}resolveBaseRelativeSubjectId(e,t){if(!this.isBaseRelativeSubjectId(t))return null;const n=this.getSubjectBaseUrl(e);if(t.startsWith("#"))return this.acceptsFragmentOnlyResourceId(e)?`${n}${t}`:null;if(n.endsWith("/"))return`${n}${t}`;const i=n.lastIndexOf("/");return`${i>=0?n.slice(0,i+1):`${n}/`}${t}`}toAbsoluteUrl(e){if(!e)return this.podUrl;if(this.isAbsoluteUri(e))return e;const t=e.startsWith("/")?e:`/${e}`;return`${this.podUrl}${t}`}combineBaseAndPattern(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:e.endsWith("/")?`${e}${t}`:(e.endsWith(".ttl")||e.endsWith(".jsonld"))&&t.startsWith("#")?`${e}${t}`:`${e}/${t}`}combineBaseAndResourceId(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:`${e.endsWith("/")?e:`${e}/`}${t}`}normalizeValue(e,t,n){return e==null?"":typeof e=="string"&&this.isAbsoluteUri(e)&&t&&this.isLinkColumn(t)?this.extractLinkId(e,t,n):String(e)}parseTemplateVariable(e){const[t,...n]=e.split("|").map(i=>i.trim()).filter(Boolean);return{raw:e,field:t||e,transforms:n}}slugifyValue(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu,"-").replace(/^-+|-+$/g,"")}applyTransforms(e,t,n,i){let s=this.normalizeValue(e,n,i);for(const o of t.transforms){if(o==="id"){s=n&&this.isLinkColumn(n)?this.extractLinkId(s,n,i):s;continue}o==="slug"&&(s=this.slugifyValue(s))}return s}applyTemplate(e,t,n,i,s=!0,o){if(!e.includes("{"))return e;const a=this.createTimeContext(t),d=[],l=e.replace(/(#?)\{([^}]+)\}/g,(h,p,g)=>{const S=this.parseTemplateVariable(g),y=S.field;if(y in a)return p+a[y];if(y==="index"&&n!==void 0)return p+String(n+1);let v=t[y];if(y==="id"&&v==null&&(v=t["@id"]??t.uri),v==null)return d.push(g),h;const E=i?.columns?.[y],w=o??(i?{tableRegistry:i[Symbol.for("drizzle:tableRegistry")],tableNameRegistry:i[Symbol.for("drizzle:tableNameRegistry")]}:void 0),T=this.applyTransforms(v,S,E,w);return p==="#"&&T.startsWith("#")?p+T.slice(1):p+T});if(d.length>0){if(s){const h=i?.config?.name||"unknown";throw new Error(`[UriResolver] Missing required fields for template "${e}" in table "${h}": [${d.join(", ")}]. Record keys: [${Object.keys(t).join(", ")}]. Record: ${JSON.stringify(t)}`)}return null}return l}createTimeContext(e){let t;const n=e.createdAt??e.created_at??e.dateCreated;n instanceof Date?t=n:typeof n=="string"||typeof n=="number"?t=new Date(n):t=new Date;const i=t.getUTCFullYear().toString(),s=(t.getUTCMonth()+1).toString().padStart(2,"0"),o=t.getUTCDate().toString().padStart(2,"0"),a=Math.floor(t.getTime()/1e3).toString();return{date:t,yyyy:i,MM:s,dd:o,timestamp:a}}generateFallbackUri(e,t,n){const i=n!==void 0?`row-${n+1}`:`row-${Date.now()}`;return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}#${i}`:`${e.endsWith("/")?e:`${e}/`}${i}.ttl`}extractRelativeSubjectId(e,t){const n=t.config?.base??"";let i="";if(n&&e.includes(n)){const s=e.indexOf(n);i=e.substring(s+n.length),i.startsWith("#")&&!(t.hasCustomTemplate?.()??!1)&&(i=`${n.split("/").filter(Boolean).pop()??""}${i}`),i.startsWith("/")&&(i=i.substring(1))}else if(!n)i=e;else return console.warn(`[UriResolver] Cannot extract ID: base "${n}" not found in URI "${e}"`),"";return i}extractPublicId(e,t){return this.extractTemplateIdFromSubject(e,t)??this.extractRelativeSubjectId(e,t)}extractTemplateIdFromSubject(e,t){const n=this.extractRelativeSubjectId(e,t),i=t.config?.subjectTemplate;return i?this.extractIdFromTemplate(n,i):n}extractIdFromTemplate(e,t){let n=t.replace(/[.+?^$[\]\\()]/g,"\\$&").replace(/\{id\}/g,"(?<id>.+?)").replace(/\{[^}]+\}/g,"(?:.+?)");n=`^${n}$`;try{const i=new RegExp(n),s=e.match(i);if(s&&s.groups?.id)return s.groups.id;if(s&&s[1])return s[1]}catch{}return null}}function buildInlineChildUri(r,e,t){const n=r.indexOf("#"),i=n>=0?r.slice(0,n):r,s=n>=0?r.slice(n+1):"",o=s?`${encodeURIComponent(s)}/`:"";return`${i}#${o}${encodeURIComponent(e)}-${t+1}`}function isOrderByExpression(r){if(!r||typeof r!="object")return!1;const e=r;return"column"in e&&(e.direction==="asc"||e.direction==="desc")}function isReservedIdentifierKey(r){return r==="id"||r==="@id"||r.endsWith(".id")||r.endsWith(".@id")}function isReservedIdentifierOperand(r){if(r instanceof PodColumnBase){const e=r;return r.name==="id"||r.options?.predicate==="@id"||e._virtualId===!0}return typeof r=="string"?isReservedIdentifierKey(r):!1}function conditionTargetsReservedIdentifier(r){return r.type==="binary_expr"?!!(isReservedIdentifierOperand(r.left)||isReservedIdentifierOperand(r.right)):r.type==="logical_expr"?r.expressions.some(e=>e!=null&&typeof e=="object"&&"type"in e&&conditionTargetsReservedIdentifier(e)):r.type==="unary_expr"?r.value!=null&&typeof r.value=="object"&&"type"in r.value&&conditionTargetsReservedIdentifier(r.value):!1}function createWhereIdentifierError(r){switch(r){case"select":return["Using 'id' or '@id' in where() is not supported.","Use findById(id) for base-relative resource ids,","or findByIri(iri) for full IRI exact lookups."].join(" ");case"update":return["Using 'id' or '@id' in where() is not supported.","Use updateById(id, data) for base-relative resource ids,","or updateByIri(iri, data) for full IRI exact updates."].join(" ");case"delete":return["Using 'id' or '@id' in where() is not supported.","Use deleteById(id) for base-relative resource ids,","or deleteByIri(iri) for full IRI exact deletes."].join(" ")}}function assertPublicWhereObject(r,e){if(e){for(const t of Object.keys(e))if(isReservedIdentifierKey(t))throw new Error(createWhereIdentifierError(r))}}function assertPublicWhereCondition(r,e){if(conditionTargetsReservedIdentifier(e))throw new Error(createWhereIdentifierError(r))}function assertPublicCursorCondition(r){let e=!1,t=!1;const n=i=>{if(i.type==="binary_expr"){if(isReservedIdentifierOperand(i.left)||isReservedIdentifierOperand(i.right)){if(![">",">=","<","<="].includes(i.operator))throw new Error("whereCursor() only supports range comparisons on 'id' or '@id'.");e=!0}else t=!0;return}if(i.type==="logical_expr"){for(const s of i.expressions)n(s);return}t=!0};if(n(r),!e||!t)throw new Error("whereCursor() requires a sort predicate plus an 'id' or '@id' range tie-breaker.")}var define_process_env_default$2={},_a$7;class SelectQueryBuilder{constructor(e,t){this.session=e,this.joins=[],this.orderByClauses=[],this.isDistinct=!1,this.tableAliases=new Map,this.aliasToTable=new Map,this.aliasUsage=new Map,this.joinFilters=[],this.groupByColumns=[],t&&this.setSelectedFields(t)}from(e){return this.selectedTable=e,this.primaryAlias=this.ensureAliasForTable(e),this}columns(e){return this.setSelectedFields(e),this}setSelectedFields(e){this.selectedFields={...e}}where(e){return e instanceof SQL?this.sql=e:this.isQueryCondition(e)?(assertPublicWhereCondition("select",e),this.processQueryCondition(e)):(assertPublicWhereObject("select",e),this.processWhereObject(e)),this}whereCursor(e){return assertPublicCursorCondition(e),this.processQueryCondition(e),this}whereByIri(e){return this.processWhereObject({"@id":e}),this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,n=e.right,i=e.operator,s=typeof t=="string"?t:t?.name;if(i==="="&&s&&n!==void 0)return{[s]:n}}if(e.type==="logical_expr"){const t=e.operator,n=e.expressions;if(t==="AND"&&n){const i={};for(const s of n){const o=this.convertQueryConditionToSimple(s);if(!o||Object.keys(o).length===0)return{};for(const[a,d]of Object.entries(o))i[a]=d}return i}}return{}}extractTableFromCondition(e){if(e.type==="binary_expr"){const t=e.left;if(t&&typeof t=="object"&&"table"in t){const n=t.table;if(n)return this.tableAliases.get(n)}if(typeof t=="string"&&t.includes("."))return t.split(".")[0]}}leftJoin(e,t){return this.addJoin("leftJoin",e,t)}rightJoin(e,t){return this.addJoin("rightJoin",e,t)}innerJoin(e,t){return this.addJoin("innerJoin",e,t)}fullJoin(e,t){return this.addJoin("fullJoin",e,t)}crossJoin(e){return this.addJoin("crossJoin",e)}groupBy(...e){const t=e.map(n=>this.resolveColumnReference(n));return this.groupByColumns.push(...t),this}having(e){return this.havingCondition=typeof e=="function"?e(this.createSelectedFieldAliases()):e,this}createSelectedFieldAliases(){const e={};for(const t of Object.keys(this.selectedFields??{}))e[t]=new SelectionAliasExpression(t);return e}addJoin(e,t,n){if(e==="rightJoin"||e==="fullJoin")throw new Error(`${e} is not yet supported in Solid dialect`);const i=this.ensureAliasForTable(t),s=e==="crossJoin"?void 0:this.resolveJoinConditions(n,i);return this.joins.push({type:e,table:t,alias:i,rawCondition:n,resolvedConditions:s}),this}ensureAliasForTable(e){const t=this.tableAliases.get(e);if(t)return t;const n=e.config.name||"table",i=this.aliasUsage.get(n)??0,s=i+1;this.aliasUsage.set(n,s);const o=i===0?n:`${n}_${s}`;return this.tableAliases.set(e,o),this.aliasToTable.set(o,e),o}resolveJoinConditions(e,t){if(this.isQueryCondition(e))return this.resolveJoinConditionExpression(e,t);if(!e||typeof e!="object")throw new Error("JOIN condition must be an equality expression or column mapping");const n=Object.entries(e);if(n.length===0)throw new Error("JOIN condition cannot be empty");return n.map(([i,s])=>{const o=this.resolveColumnReference(i),a=this.resolveColumnReference(s);if(o.alias!==t&&a.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return{left:o,right:a}})}resolveJoinConditionExpression(e,t){if(e.type==="logical_expr"){const s=(e.operator??"").toUpperCase(),o=e.expressions??[];if(s!=="AND"||o.length===0)throw new Error("JOIN condition only supports equality expressions combined with AND");return o.flatMap(a=>this.resolveJoinConditionExpression(a,t))}if(e.type!=="binary_expr"||e.operator!=="=")throw new Error("JOIN condition only supports equality expressions");const n=this.getConditionColumnReference(e.left),i=this.getConditionColumnReference(e.right);if(!n||!i)throw new Error("JOIN equality must compare two table columns");if(n.alias!==t&&i.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return[{left:n,right:i}]}getConditionColumnReference(e,t){if(e instanceof PodColumnBase)return this.resolveColumnReference(e,t);if(typeof e=="string"){if(e.includes("."))return this.resolveColumnReference(e,t);const n=t??this.primaryAlias,i=n?this.aliasToTable.get(n):void 0;if(i&&e in(i.columns??{}))return this.resolveColumnReference(e,t)}}resolveColumnReference(e,t){if(e instanceof PodColumnBase){const n=e.table;if(!n)throw new Error(`Column ${e.name} is not associated with a table`);const i=this.ensureAliasForTable(n);return{table:n,alias:i,column:e.name}}if(typeof e=="string"){const{alias:n,column:i}=this.parseColumnReferenceString(e),s=n??t??this.primaryAlias;if(!s)throw new Error(`Unable to resolve table alias for column reference "${e}"`);const o=this.aliasToTable.get(s);if(!o)throw new Error(`Unknown table alias "${s}" in column reference "${e}"`);return{table:o,alias:s,column:i}}throw new Error("Unsupported column link type")}parseColumnReferenceString(e){const t=e.trim();if(!t.includes("."))return{column:t};const[n,i]=t.split(".",2);return{alias:n,column:i}}processWhereObject(e){if(!e)return;const t={...this.whereConditions??{}};for(const[n,i]of Object.entries(e)){const{alias:s,column:o}=this.parseColumnReferenceString(n),a=s??this.primaryAlias;if(!a||a===this.primaryAlias||!this.aliasToTable.has(a)){t[o]=i;continue}this.joinFilters.push(createLiteralCondition(a,o,i))}this.whereConditions=Object.keys(t).length>0?t:void 0}processQueryCondition(e){const t=this.extractTableFromCondition(e);if(t&&t!==this.primaryAlias){this.joinFilters.push(e);return}this.conditionTree=e;const n=this.convertQueryConditionToSimple(e);Object.keys(n).length>0&&(this.whereConditions=n)}applyInternalQueryCondition(e){return this.processQueryCondition(e),this}normalizeWhereConditions(){if(this.conditionTree)return this.conditionTree;const e=this.primaryAlias??this.selectedTable?.config.name;return buildConditionTreeFromObject(this.whereConditions,e)}toIR(){const e=this.normalizeWhereConditions();return this.buildQueryPlan(e)}buildQueryPlan(e){if(!this.selectedTable)throw new Error("No table specified for SELECT query");const t=this.joins.map(n=>({type:n.type,table:n.table,alias:n.alias,conditions:(n.resolvedConditions??[]).map(({left:i,right:s})=>({left:i,right:s}))}));return{baseTable:this.selectedTable,baseAlias:this.primaryAlias??this.selectedTable.config.name,select:this.selectedFields,selectAll:!this.selectedFields,where:this.whereConditions,conditionTree:e,joins:t.length>0?t:void 0,joinFilters:this.joinFilters.length>0?[...this.joinFilters]:void 0,groupBy:this.groupByColumns.length>0?[...this.groupByColumns]:void 0,having:this.havingCondition,orderBy:this.orderByClauses.length>0?this.orderByClauses.map(n=>({rawColumn:n.column,direction:n.direction})):void 0,distinct:this.isDistinct||void 0,limit:this.limitCount,offset:this.offsetCount,aliasToTable:new Map(this.aliasToTable),tableToAlias:new Map(this.tableAliases)}}limit(e){if(!Number.isInteger(e)||e<0)throw new Error("LIMIT must be a non-negative integer");return this.limitCount=e,this}offset(e){if(!Number.isInteger(e)||e<0)throw new Error("OFFSET must be a non-negative integer");return this.offsetCount=e,this}addOrderByClause(e,t="asc"){const n=typeof e=="string"?e:e.name;if(!n)throw new Error("ORDER BY requires a valid column name");this.orderByClauses.push({column:n,direction:t})}orderBy(...e){if(e.length===0)throw new Error("ORDER BY requires at least one column or expression");if(e.length===2&&(e[0]instanceof PodColumnBase||typeof e[0]=="string")&&(e[1]==="asc"||e[1]==="desc"))return this.addOrderByClause(e[0],e[1]),this;for(const t of e){if(isOrderByExpression(t)){this.addOrderByClause(t.column,t.direction);continue}if(t instanceof PodColumnBase||typeof t=="string"){this.addOrderByClause(t,"asc");continue}throw new Error("ORDER BY received an unsupported argument")}return this}distinct(e=!0){return this.isDistinct=e,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const n=this.sql.queryChunks.join(""),i=inferSPARQLQueryType(n);if(!i)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:i,query:n,prefixes:{}}}if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.joins.length>0)throw new Error(`${e} is not yet supported for JOIN queries in Solid dialect`);if(this.shouldUseProjectionFallback())throw new Error(`${e} does not support structured selections in Solid dialect`);const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertSelectPlan(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.limitCount===0)return[];if(this.sql)return await this.session.executeSql(this.sql,this.selectedTable);{const e=this.toIR(),t=e.conditionTree,n=this.joins.length>0,i=this.shouldUseAggregateFallback(),s=this.shouldUseProjectionFallback(),o=n||i;(n||i||s)&&(e.select=void 0,e.selectAll=!0);const a=o?{...e,limit:void 0,offset:void 0,orderBy:void 0,...n?{joins:void 0,joinFilters:void 0}:{},...i?{groupBy:void 0,having:void 0}:{}}:n?{...e,joins:void 0,joinFilters:void 0}:e,d={type:"select",table:this.selectedTable,where:t,limit:o?void 0:this.limitCount,offset:o?void 0:this.offsetCount,orderBy:o||this.orderByClauses.length===0?void 0:this.orderByClauses,distinct:this.isDistinct||void 0};if(d.plan=a,this.groupByColumns.length===0&&this.hasMixedAggregateSelection())throw new Error("Mixed aggregate and non-aggregate selections require groupBy columns");let l;if(!n&&!i&&!s?(this.selectedFields&&(d.select=this.selectedFields),l=await this.session.execute(d),l=this.applySubjectMetadata(l)):(n?d.select=void 0:!i&&!s?d.select=this.selectedFields:d.select=void 0,l=await this.session.execute(d),n||(l=this.applySubjectMetadata(l)),n&&(l=this.normalizeBaseRows(l),l=this.mergeRowsBySubject(l),l=await this.applyJoinFallback(l),l=this.applyJoinFilters(l))),i){let p=this.handleAggregateFallback(l);return p=this.applyHavingFilter(p),o&&(p=this.applyDeferredOrderBy(p),p=this.applyDeferredOffsetAndLimit(p)),p}let h=l;return n||(h=this.mergeRowsBySubject(h)),this.selectedTable&&(h=await this.hydrateInlineColumns(h,this.selectedTable,!n)),n&&(h=this.applyDeferredOrderBy(h)),this.selectedFields&&(h=h.map(p=>this.projectSelectedRow(p))),h=this.applyDistinctRows(h),n||(h=this.mergeRowsBySubject(h)),n&&(h=this.applyDeferredOffsetAndLimit(h)),h}}projectSelectedRow(e){return this.selectedFields?this.projectFieldMap(e,this.selectedFields):e}projectFieldMap(e,t,n=!0){const i={};for(const[s,o]of Object.entries(t))i[s]=this.projectFieldValue(e,s,o,n);return i}projectFieldValue(e,t,n,i=!0){if(isAggregateExpression(n))return i?e[t]:void 0;if(n instanceof PodTable)return this.projectTableValue(e,n);if(this.isSelectFieldMap(n)){const s=this.collectSelectionAliases(n),o=s.size===1&&!s.has(this.primaryAlias??""),a=this.projectFieldMap(e,n,!o);if(s.size===1){const[d]=Array.from(s);if(d&&d!==this.primaryAlias&&this.isProjectedValueEmpty(a))return null}return a}for(const s of this.resolveFieldBindingCandidates(t,n))if(e[s]!==void 0)return e[s];return i?e[t]:void 0}projectTableValue(e,t){const n=this.tableAliases.get(t)??t.config.name,i={};let s=!1;for(const o of Object.keys(t.columns)){const d=(n===this.primaryAlias?[o,`${n}.${o}`]:[`${n}.${o}`]).find(l=>e[l]!==void 0);i[o]=d?e[d]:void 0,i[o]!==void 0&&(s=!0)}return n!==this.primaryAlias&&!s?null:i}isSelectFieldMap(e){return!!e&&typeof e=="object"&&!(e instanceof PodColumnBase)&&!(e instanceof PodTable)&&!isAggregateExpression(e)}collectSelectionAliases(e){if(typeof e=="string"){const{alias:n}=this.parseColumnReferenceString(e);return new Set(n?[n]:this.primaryAlias?[this.primaryAlias]:[])}if(e instanceof PodColumnBase)return new Set([this.resolveColumnReference(e).alias]);if(e instanceof PodTable)return new Set([this.tableAliases.get(e)??e.config.name]);if(!this.isSelectFieldMap(e))return new Set;const t=new Set;for(const n of Object.values(e))for(const i of this.collectSelectionAliases(n))t.add(i);return t}isProjectedValueEmpty(e){if(e==null)return!0;if(Array.isArray(e))return e.length===0;if(typeof e=="object"){const t=Object.values(e);return t.length>0&&t.every(n=>this.isProjectedValueEmpty(n))}return!1}resolveFieldBindingCandidates(e,t){const n=new Set;if(typeof t=="string"){const{alias:i,column:s}=this.parseColumnReferenceString(t);n.add(t),n.add(s),i&&n.add(`${i}.${s}`)}else if(t instanceof PodColumnBase){const i=this.resolveColumnReference(t);n.add(`${i.alias}.${i.column}`),(!i.alias||i.alias===this.primaryAlias)&&n.add(t.name)}else if(t&&typeof t=="object"){const i=t.name;typeof i=="string"&&n.add(i)}return Array.from(n)}shouldUseProjectionFallback(){if(!this.selectedFields)return!1;const e=t=>!!(t instanceof PodTable||this.isSelectFieldMap(t));return Object.values(this.selectedFields).some(t=>e(t))}shouldUseAggregateFallback(){if(this.havingCondition)return!0;if(this.joins.length>0)return this.groupByColumns.length>0||this.hasAggregateSelection();if(this.groupByColumns.length>0||!this.selectedFields)return!1;const e=Object.values(this.selectedFields);return e.length>0&&e.every(t=>isAggregateExpression(t))}buildAggregateRow(e){const t={};if(!this.selectedFields)return t;for(const[n,i]of Object.entries(this.selectedFields))isAggregateExpression(i)&&(t[n]=this.computeAggregateValue(i,e));return t}computeAggregateValue(e,t){const n=this.resolveAggregateColumnRef(e);if(!n)return e.func==="count"?e.distinct?this.countDistinctRows(t):t.length:null;switch(e.func){case"count":return this.collectValuesForCount(n,t,!!e.distinct).length;case"sum":{const i=this.collectNumericValues(n,t,!!e.distinct);return i.length===0?null:i.reduce((s,o)=>s+o,0)}case"avg":{const i=this.collectNumericValues(n,t,!!e.distinct);return i.length===0?null:i.reduce((o,a)=>o+a,0)/i.length}case"min":{const i=this.collectNumericValues(n,t,!!e.distinct);return i.length===0?null:Math.min(...i)}case"max":{const i=this.collectNumericValues(n,t,!!e.distinct);return i.length===0?null:Math.max(...i)}default:return null}}resolveAggregateColumnRef(e){const t=e.column;if(t){if(typeof t=="string")return this.resolveColumnReference(t);if(t instanceof PodColumnBase)return this.resolveColumnReference(t);if(typeof t=="object"&&"name"in t){const n=t.name;if(typeof n=="string")return this.resolveColumnReference(n)}}}collectValuesForCount(e,t,n){const i=t.map(a=>this.getRowValueForColumn(a,e)).filter(a=>a!=null);if(!n)return i;const s=new Set,o=[];for(const a of i){const d=this.serializeValueForKey(a);s.has(d)||(s.add(d),o.push(a))}return o}collectNumericValues(e,t,n){const i=[],s=new Set;for(const o of t){const a=this.getRowValueForColumn(o,e);if(a==null)continue;const d=Number(a);if(!Number.isNaN(d))if(n){const l=this.serializeValueForKey(d);s.has(l)||(s.add(l),i.push(d))}else i.push(d)}return i}countDistinctRows(e){const t=new Set;for(const n of e){const i=this.serializeValueForKey(n);t.add(i)}return t.size}handleAggregateFallback(e){if(!this.selectedFields){if(this.groupByColumns.length===0)return e;const t=new Map;for(const n of e){const i=this.groupByColumns.map(o=>this.serializeValueForKey(this.getRowValueForColumn(n,o))),s=JSON.stringify(i);t.has(s)||t.set(s,n)}return Array.from(t.values())}return this.groupByColumns.length===0?[this.buildAggregateRow(e)]:this.buildGroupedAggregateRows(e)}buildGroupedAggregateRows(e){if(!this.selectedFields)return e;this.ensureGroupByValidity();const t=new Map;for(const i of e){const s=this.groupByColumns.map(a=>this.serializeValueForKey(this.getRowValueForColumn(i,a))),o=JSON.stringify(s);t.has(o)||t.set(o,{rows:[],first:i}),t.get(o)?.rows.push(i)}const n=[];for(const{rows:i,first:s}of t.values()){const o=this.buildAggregateRow(i),a={};for(const[d,l]of Object.entries(this.selectedFields))if(isAggregateExpression(l))a[d]=o[d];else{const h=this.resolveSelectFieldColumn(l);a[d]=h?this.getRowValueForColumn(s,h):void 0}n.push(a)}return n}ensureGroupByValidity(){if(!this.selectedFields)return;const e=this.groupByColumns.map(t=>`${t.alias}.${t.column}`);for(const t of Object.values(this.selectedFields)){if(isAggregateExpression(t))continue;const n=this.resolveSelectFieldColumn(t);if(!n)continue;const i=`${n.alias}.${n.column}`;if(!e.includes(i))throw new Error(`Column ${i} must appear in GROUP BY clause when mixed with aggregates`)}}resolveSelectFieldColumn(e){if(e instanceof PodColumnBase)return this.resolveColumnReference(e);if(typeof e=="string")return this.resolveColumnReference(e)}hasAggregateSelection(){return this.selectedFields?Object.values(this.selectedFields).some(e=>isAggregateExpression(e)):!1}hasMixedAggregateSelection(){if(!this.selectedFields)return!1;const e=Object.values(this.selectedFields),t=e.some(i=>isAggregateExpression(i)),n=e.some(i=>!isAggregateExpression(i));return t&&n}applySubjectMetadata(e){return e.map(t=>this.attachSubjectMetadata(t))}extractSubjectValue(e){const t=e.subject??e["@id"]??e.uri;if(typeof t=="object"&&t&&"value"in t){const n=t.value;return typeof n=="string"&&n.length>0?n:void 0}if(typeof t=="string"&&t.length>0)return t}attachSubjectMetadata(e){const t=this.extractSubjectValue(e);if(typeof t=="string"&&t.length>0&&(e["@id"]===void 0&&(e["@id"]=t),e.uri===void 0&&(e.uri=t),e.id===void 0)){const n=this.extractIdFromSubject(t,this.selectedTable);n!==void 0&&(e.id=n)}return e}normalizeBaseRows(e){if(!e.length)return e;const t=this.primaryAlias||this.ensureAliasForTable(this.selectedTable);return e.map(n=>{const i={...n};for(const[o,a]of Object.entries(n))o!==`${t}.${o}`&&(i[`${t}.${o}`]=a);const s=this.extractSubjectValue(n);if(s){i.subject=s,i["@id"]=s,i.uri=s,i[`${t}.subject`]=s,i[`${t}.@id`]=s,i[`${t}.uri`]=s;const o=this.extractIdFromSubject(s,this.selectedTable);o!==void 0&&(i.id===void 0&&(i.id=o),(this.shouldUseSubjectIdentityColumn(this.selectedTable,"id")||i[`${t}.id`]===void 0)&&(i[`${t}.id`]=o))}return i})}async hydrateInlineColumns(e,t,n=!0){if(!e.length)return e;const i=Object.values(t.columns??{}).filter(E=>this.isInlineObjectColumn(E));if(i.length===0)return e;n&&(e=this.mergeRowsBySubject(e));const s=new Map;i.forEach(E=>{const w=E.getPredicate(t.config.namespace);s.set(w,E)});const o=Array.from(new Set(e.map(E=>this.normalizeInlineIri(E["@id"]??E.subject??E.uri??E.id)).filter(E=>!!E)));if(o.length===0||s.size===0)return e;const a=Array.from(s.keys()).map(E=>`<${E}>`).join(" "),d=this.session.getDialect().getSPARQLExecutor(),l=[],h=new Map;for(const E of o){const w=this.inferSourceFromChild(E,t),T=h.get(w)??[];T.push(E),h.set(w,T)}for(const[E,w]of h.entries()){const I={type:"SELECT",query:`SELECT ?parent ?linkPred ?child ?pred ?obj WHERE {
|
|
34
34
|
VALUES ?parent { ${w.map(O=>`<${O}>`).join(" ")} }
|
|
35
35
|
VALUES ?linkPred { ${a} }
|
|
36
36
|
?parent ?linkPred ?child .
|