From 6f8eb99606779babb67a72fa0d20158007bff5eb Mon Sep 17 00:00:00 2001 From: "Snow Lee (Sungwon)" Date: Wed, 19 Aug 2026 10:58:33 -0700 Subject: [PATCH] fix(palette): the project you are in answers to its own name (#170) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The palette's placeholder and empty state both promise project search, but the switcher loop rightly excludes the project you are already inside — so typing `wiki` from inside `wiki` matched nothing at all. The destination was there the whole time, as the unconditional row labelled "Go to project root" and tagged ACTION, which no project name will ever match. Relabel that one row with the project's name and tag it `project`. One row, not two; still first and unconditional, so the BEA-52 dead-route escape hatch is literally the same row it always was. Closes BEA-105 Co-authored-by: Claude Opus 5 (1M context) --- internal/webapp/frontend/e2e/browse.spec.ts | 23 ++++++++++++++++++- internal/webapp/frontend/src/apps/Browser.tsx | 7 +++++- .../{index-CYEvhG3F.js => index-D8UAHgrJ.js} | 2 +- internal/webapp/static/index.html | 2 +- 4 files changed, 30 insertions(+), 4 deletions(-) rename internal/webapp/static/assets/{index-CYEvhG3F.js => index-D8UAHgrJ.js} (98%) diff --git a/internal/webapp/frontend/e2e/browse.spec.ts b/internal/webapp/frontend/e2e/browse.spec.ts index 8aa195a..83cbaa3 100644 --- a/internal/webapp/frontend/e2e/browse.spec.ts +++ b/internal/webapp/frontend/e2e/browse.spec.ts @@ -177,6 +177,27 @@ test("palette (⌘K) fuzzy-jumps to a file", async ({ page }) => { await expect(page.locator("#content h1")).toHaveText("Topic"); }); +// BEA-105: the switcher excludes the project you're in, so typing its own name +// used to match nothing while the palette copy promised project search. The +// root row carries the name now — one row, kind `project`, same destination. +test("palette finds the project you are inside by name", async ({ page }) => { + await login(page); + const pid = await wikiId(page); + await page.goto(`/${pid}`); + await page.waitForSelector("#sidebar"); + await page.keyboard.press("ControlOrMeta+k"); + await expect(page.locator("#palette")).toBeVisible(); + // with no query typed, at least one PROJECT row is on screen + expect(await page.locator("#palette [cmdk-item] .pkind", { hasText: "project" }).count()).toBeGreaterThan(0); + + await page.fill("#palette input", "wiki"); + const rows = page.locator("#palette [cmdk-item]", { hasText: "wiki" }); + await expect(rows).toHaveCount(1); // exactly one, no duplicate root action + await expect(rows.first().locator(".pkind")).toHaveText("project"); + await page.keyboard.press("Enter"); + await page.waitForURL(`/${pid}`); +}); + // BEA-52: on a path that doesn't resolve the tree entries are gone and the // switcher lists only other projects, so the palette used to offer no way // back. cmdk owns the list's id (it overwrites ours), hence [cmdk-list]. @@ -187,7 +208,7 @@ test("palette on a dead route still offers the way back", async ({ page }) => { await expect(page.locator(".notfound")).toBeVisible(); await page.keyboard.press("ControlOrMeta+k"); await expect(page.locator("#palette")).toBeVisible(); - for (const label of ["Go to project root", "Dashboard", "Installation", "Settings"]) { + for (const label of ["project root", "Dashboard", "Installation", "Settings"]) { await expect(page.locator("#palette [cmdk-list]")).toContainText(label); } // exactly one whole-project history entry, no duplicate diff --git a/internal/webapp/frontend/src/apps/Browser.tsx b/internal/webapp/frontend/src/apps/Browser.tsx index 52fc1ff..dcd1ee7 100644 --- a/internal/webapp/frontend/src/apps/Browser.tsx +++ b/internal/webapp/frontend/src/apps/Browser.tsx @@ -467,7 +467,12 @@ export default function Browser(props: { props.onClosePanel?.(); navigate(to); }; - add("folder", "Go to project root", "action", go("/" + pid)); + // Labelled with the project's name and tagged `project`, so typing the + // name of the project you are IN finds it: the switcher loop below + // rightly excludes the current project, which left nothing carrying its + // name while the palette copy promised project search (BEA-105). One row, + // not two — still the first, still unconditional, so BEA-52 holds. + add("folder", project.name + " — project root", "project", go("/" + pid)); add("dashboard", "Dashboard", "action", go(urlForView("dashboard", pid))); add("terminal", "Installation", "action", go(urlForView("install", pid))); add("gear", "Settings", "action", go(urlForView("settings", pid))); diff --git a/internal/webapp/static/assets/index-CYEvhG3F.js b/internal/webapp/static/assets/index-D8UAHgrJ.js similarity index 98% rename from internal/webapp/static/assets/index-CYEvhG3F.js rename to internal/webapp/static/assets/index-D8UAHgrJ.js index 2c14268..4f9959e 100644 --- a/internal/webapp/static/assets/index-CYEvhG3F.js +++ b/internal/webapp/static/assets/index-D8UAHgrJ.js @@ -119,4 +119,4 @@ bdrive init --project `+e.id;return f.jsxs("div",{className:"guide",children:[f. to set up a new BearDrive project on `+window.location.origin+". Ask me which folder to sync."}),f.jsx("p",{className:"ob-alt",children:f.jsx("a",{href:"https://docs.beardrive.ai/manual/setup-by-hand/",target:"_blank",rel:"noreferrer",children:"Or start a project manually →"})})]})]})}const qC="__existing__";function sI({templates:e,onCreate:t,onClose:r}){const i=[...e.map(x=>({value:x.name,title:x.title,blurb:x.blurb,rule:!1})),{value:qC,title:"I already have a folder",blurb:"nothing is seeded — connect it and your files stay as they are",rule:!0},{value:"",title:"Empty project",blurb:"just the folder",rule:!1}],[o,l]=S.useState(""),[u,d]=S.useState(i[0].value),[m,p]=S.useState(""),[y,v]=S.useState(!1),b=async()=>{if(!y){if(!o.trim()){p("Give it a name.");return}v(!0);try{await t(o.trim(),u)}finally{v(!1)}}};return f.jsx(Wu,{open:!0,onOpenChange:x=>!x&&r(),children:f.jsxs(ed,{className:"modal",showCloseButton:!1,children:[f.jsx(Cl,{asChild:!0,children:f.jsx("h3",{children:"New project"})}),f.jsx("label",{className:"modal-label",htmlFor:"modal-input",children:"Name"}),f.jsx("input",{className:"modal-input",type:"text",autoComplete:"off",id:"modal-input",autoFocus:!0,value:o,"aria-invalid":!!m,"aria-describedby":m?"modal-input-err":void 0,onChange:x=>{l(x.currentTarget.value),m&&p("")},onKeyDown:x=>x.key==="Enter"&&b()}),m&&f.jsx("span",{id:"modal-input-err",role:"alert",className:"field-err",children:m}),i.length>1&&f.jsxs("fieldset",{className:"start-points",children:[f.jsx("legend",{className:"modal-label",children:"Starting point"}),i.map((x,w)=>f.jsxs("label",{className:"start-point"+(u===x.value?" on":"")+(x.rule?" sp-rule":""),children:[f.jsx("input",{type:"radio",name:"template",value:x.value,checked:u===x.value,onChange:()=>d(x.value)}),f.jsxs("span",{className:"sp-text",children:[f.jsxs("span",{className:"sp-title",children:[x.title,w===0&&f.jsx("span",{className:"sp-rec",children:"Recommended"})]}),f.jsx("span",{className:"sp-blurb",children:x.blurb})]})]},x.value))]}),f.jsxs("div",{className:"modal-actions",children:[f.jsx(xt,{variant:"subtle",onClick:r,children:"Cancel"}),f.jsx(xt,{variant:"primary",onClick:b,disabled:y,children:"Create"})]})]})})}function am(e,t,r){if(!e)return null;if(!r)return e[t]||null;const i={human:0,agent:0,share:0};for(const[o,l]of Object.entries(e))o.startsWith(t+"/")&&(i.human+=l.human||0,i.agent+=l.agent||0,i.share+=l.share||0);return i.human||i.agent||i.share?i:null}function na(e){return(e.human||0)+(e.agent||0)+(e.share||0)}function el(e){const t=na(e);if(!t)return"";const r=t+(t===1?" read":" reads");if(!e.agent&&!e.share)return r;const i=[];return e.human&&i.push(e.human+" human"),e.agent&&i.push(e.agent+" agent"),e.share&&i.push(e.share+" shared"),r+" ("+i.join(", ")+")"}const Ci="Includes your own views. Repeat opens by the same reader inside 10 minutes count once.";function oI(e){const t=na(e);return t?t<3?1:t<10?2:t<30?3:4:0}function lI(e){const t=na(e);return t?{agent:(e.agent||0)/t,human:(e.human||0)/t,share:(e.share||0)/t}:{agent:0,human:0,share:0}}function cI(e,t){return e?Object.keys(e).filter(r=>!t.has(r)).sort():[]}const uI=7;function dI(e){if(!e.length)return null;let t=e[0],r=e[0];for(const i of e)ir&&(r=i);return{min:t,max:r}}const fI=(e,t)=>t-el.reads-o.reads).slice(0,mI)){const o=i.path.split("/").pop();let l=i.cx+i.r+4,u="start";l+o.length*pI>t.right&&(l=i.cx-i.r-4,u="end");const d=p=>r.every(y=>Math.abs(y.y-p)>=im);let m=i.cy;for(;m<=t.bottom&&!d(m);)m+=im;if(m>t.bottom)for(m=i.cy;m>=t.top&&!d(m);)m-=im;r.push({path:i.path,name:o,x:l,y:Math.min(t.bottom,Math.max(t.top,m)),anchor:u})}return r}const tl=3,Ms=30,GC=(e,t)=>e>=tl&&t>=Ms;function vI(e,t=Date.now()){if(!e)return null;const r=new Date(e).getTime();return Number.isFinite(r)?Math.max(0,(t-r)/864e5):null}function yI(e){const t=new Intl.RelativeTimeFormat("en",{numeric:"always"});return e<30?t.format(-Math.round(e),"day"):e<365?t.format(-Math.round(e/30),"month"):t.format(-Math.round(e/365),"year")}function ZC(e,t){const r=vI(t);return!e||r===null||!GC(na(e),r)?"":`stale · last changed ${yI(r)}`}function bI(e,t=!0){const r=Ft({queryKey:["tree",e],queryFn:()=>qt(e+"tree"),enabled:t,refetchInterval:15e3}),i=S.useMemo(()=>{const o=[],l=new Map,u=d=>{for(const m of d.children||[])m.dir?(l.set(m.path,m),u(m)):o.push(m)};return r.data&&u(r.data),{flatFiles:o,dirIndex:l}},[r.data]);return{tree:r.data,...i,loaded:!!r.data}}function xI(e,t){return Ft({queryKey:["heat",e],queryFn:()=>qt(e+"heat?days=30"),enabled:t,staleTime:6e4,refetchInterval:6e4}).data?.entries??null}function wI(e,t,r){return Ft({queryKey:["history",e,"prefix",t,20],queryFn:()=>qt(e+"history?prefix="+encodeURIComponent(t)+"&n=20"),enabled:r,staleTime:15e3}).data?.entries??null}function SI(e,t,r){const i=new Array(e);return new Proxy(i,{get(o,l,u){if(typeof l=="string"){const d=l.charCodeAt(0);if(d>=48&&d<=57){const m=+l;if(Number.isInteger(m)&&m>=0&&mi[y]!==p))&&(i=d,o=t(...d),r?.onChange&&!(l&&r.skipInitialOnChange)&&r.onChange(o),l=!1),o}return u.updateDeps=d=>{i=d},u}function lw(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _I=(e,t)=>Math.abs(e-t)<1.01,CI=(e,t,r)=>{let i;return function(...o){e.clearTimeout(i),i=e.setTimeout(()=>t.apply(this,o),r)}};let Ko;const sm=()=>{if(Ko!==void 0)return Ko;if(typeof navigator>"u")return Ko=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Ko=!0;const e=navigator.maxTouchPoints;return Ko=navigator.platform==="MacIntel"&&e!==void 0&&e>0},cw=e=>{const{offsetWidth:t,offsetHeight:r}=e;return{width:t,height:r}},EI=e=>e,RI=e=>{const t=Math.max(e.startIndex-e.overscan,0),i=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,o=new Array(i);for(let l=0;l{const r=e.scrollElement;if(!r)return;const i=e.targetWindow;if(!i)return;const o=u=>{const{width:d,height:m}=u;t({width:Math.round(d),height:Math.round(m)})};if(o(cw(r)),!i.ResizeObserver)return()=>{};const l=new i.ResizeObserver(u=>{const d=()=>{const m=u[0];if(m?.borderBoxSize){const p=m.borderBoxSize[0];if(p){o({width:p.inlineSize,height:p.blockSize});return}}o(cw(r))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(d):d()});return l.observe(r,{box:"border-box"}),()=>{l.unobserve(r)}},Au={passive:!0},TI=typeof window>"u"?!0:"onscrollend"in window,OI=(e,t,r)=>{const i=e.scrollElement;if(!i)return;const o=e.targetWindow;if(!o)return;const l=e.options.useScrollendEvent&&TI;let u=0;const d=l?null:CI(o,()=>t(u,!1),e.options.isScrollingResetDelay),m=v=>()=>{u=r(i),d?.(),t(u,v)},p=m(!0),y=m(!1);return i.addEventListener("scroll",p,Au),l&&i.addEventListener("scrollend",y,Au),()=>{i.removeEventListener("scroll",p),l&&i.removeEventListener("scrollend",y)}},AI=(e,t)=>OI(e,t,r=>{const{horizontal:i,isRtl:o}=e.options;return i?r.scrollLeft*(o&&-1||1):r.scrollTop}),MI=(e,t,r)=>{if(r.options.useCachedMeasurements){const i=r.indexFromElement(e),o=r.options.getItemKey(i);return r.itemSizeCache.get(o)??r.options.estimateSize(i)}if(t?.borderBoxSize){const i=t.borderBoxSize[0];if(i)return Math.round(i[r.options.horizontal?"inlineSize":"blockSize"])}if(!t){const i=r.indexFromElement(e),o=r.options.getItemKey(i),l=r.itemSizeCache.get(o);if(l!==void 0)return l}return e[r.options.horizontal?"offsetWidth":"offsetHeight"]},NI=(e,{adjustments:t=0,behavior:r},i)=>{var o,l;(l=(o=i.scrollElement)==null?void 0:o.scrollTo)==null||l.call(o,{[i.options.horizontal?"left":"top"]:e+t,behavior:r})},DI=NI;class kI{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var r,i,o;return((o=(i=(r=this.targetWindow)==null?void 0:r.performance)==null?void 0:i.now)==null?void 0:o.call(i))??Date.now()},this.observer=(()=>{let r=null;const i=()=>r||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:r=new this.targetWindow.ResizeObserver(o=>{o.forEach(l=>{const u=()=>{const d=l.target,m=this.indexFromElement(d);if(!d.isConnected){this.observer.unobserve(d);for(const[p,y]of this.elementsCache)if(y===d){this.elementsCache.delete(p);break}return}this.shouldMeasureDuringScroll(m)&&this.resizeItem(m,this.options.measureElement(d,l,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var o;(o=i())==null||o.disconnect(),r=null},observe:o=>{var l;return(l=i())==null?void 0:l.observe(o,{box:"border-box"})},unobserve:o=>{var l;return(l=i())==null?void 0:l.unobserve(o)}}})(),this.range=null,this.setOptions=r=>{var i,o;const l={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:EI,rangeExtractor:RI,onChange:()=>{},measureElement:MI,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const b in r){const x=r[b];x!==void 0&&(l[b]=x)}const u=this.options;let d=null,m=null,p=!1;if(u!==void 0&&u.enabled&&l.enabled&&l.anchorTo==="end"&&this.scrollElement!==null){const b=u.count,x=l.count,w=this.getMeasurements(),_=b>0?((i=w[0])==null?void 0:i.key)??u.getItemKey(0):null,E=b>0?((o=w[b-1])==null?void 0:o.key)??u.getItemKey(b-1):null;if(x!==b||b>0&&x>0&&(l.getItemKey(0)!==_||l.getItemKey(x-1)!==E)){p=!0;const O=b>0?this.getVirtualItemForOffset(this.getScrollOffset())??w[0]:null;O&&(d=[O.key,this.getScrollOffset()-O.start]);const N=l.followOnAppend===!0?"auto":l.followOnAppend||null;N&&x>b&&this.isAtEnd(u.scrollEndThreshold)&&(b===0||l.getItemKey(x-1)!==E)&&(m=N)}}this.options=l,p&&(this.pendingMin=0,this.itemSizeCacheVersion++);let y=!1,v=0;if(d&&this.scrollOffset!==null){const[b,x]=d,w=this.getMeasurements(),{count:_,getItemKey:E}=this.options;let R=0;for(;R<_&&E(R)!==b;)R++;if(R<_){const T=w[R];if(T){const O=T.start+x;O!==this.scrollOffset&&(v=O-this.scrollOffset,this.scrollOffset=O,y=!0)}}}(y||m)&&(this.pendingScrollAnchor=[y?d[0]:null,y?d[1]:0,m,v])},this.notify=r=>{var i,o;(o=(i=this.options).onChange)==null||o.call(i,this,r)},this.maybeNotify=As(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),r=>{this.notify(r)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(r=>r()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var r;const i=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==i){if(this.cleanup(),!i){this.maybeNotify();return}if(this.scrollElement=i,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((r=this.scrollElement)==null?void 0:r.window)??null,this.elementsCache.forEach(l=>{this.observer.observe(l)}),this.unsubs.push(this.options.observeElementRect(this,l=>{this.scrollRect=l,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(l,u)=>{if(u&&this._intendedScrollOffset===null&&l===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(l-this._intendedScrollOffset)<1.5&&(l=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const d=this.getScrollOffset();this.scrollDirection=u?d===l?this.scrollDirection:d{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},d=()=>{this._iosTouching=!1,!(!sm()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};l.addEventListener("touchstart",u,Au),l.addEventListener("touchend",d,Au),this.unsubs.push(()=>{l.removeEventListener("touchstart",u),l.removeEventListener("touchend",d),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const o=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,o&&this.scrollElement&&this.options.enabled){const[l,u,d,m]=o;l!==null&&!d&&(sm()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?m!==0&&(this._iosDeferredAdjustment+=m):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),d&&this.scrollToEnd({behavior:d})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const r=this.getScrollOffset(),i=this.getMaxScrollOffset();if(r<0||r>i)return;const o=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(r,{adjustments:this.scrollAdjustments+=o,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=As(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(r,i,o,l,u,d,m,p)=>(this.prevLanes!==void 0&&this.prevLanes!==d&&(this.lanesChangedFlag=!0),this.prevLanes=d,this.pendingMin=null,{count:r,paddingStart:i,scrollMargin:o,getItemKey:l,enabled:u,lanes:d,laneAssignmentMode:m,gap:p}),{key:!1}),this.getMeasurements=As(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:r,paddingStart:i,scrollMargin:o,getItemKey:l,enabled:u,lanes:d,laneAssignmentMode:m,gap:p},y)=>{const v=this.itemSizeCache;if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>r)for(const R of this.laneAssignments.keys())R>=r&&this.laneAssignments.delete(R);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(R=>{this.itemSizeCache.set(R.key,R.size)}));const b=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===r&&(this.lanesSettling=!1),d===1){const R=r*2;let T=this._flatMeasurements;if(!T||T.length0&&k.set(T.subarray(0,b*2)),T=k,this._flatMeasurements=T}let O;if(b===0)O=i+o;else{const k=b-1;O=T[k*2]+T[k*2+1]+p}for(let k=b;k1){N=O;const be=w[N],pe=be!==void 0?x[be]:void 0;k=pe?pe.end+p:i+o}else if(E===d){let be=0,pe=_[0],fe=w[0];for(let ue=1;uethis.options.debug}),this.calculateRange=As(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(r,i,o,l)=>r.length===0||i===0?(this.range=null,null):(this.range=LI(r,i,o,l,l===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=As(()=>{let r=null,i=null;const o=this.calculateRange();return o&&(r=o.startIndex,i=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,r,i]),[this.options.rangeExtractor,this.options.overscan,this.options.count,r,i]},(r,i,o,l,u)=>l===null||u===null?[]:r({startIndex:l,endIndex:u,overscan:i,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=r=>{const i=this.options.indexAttribute,o=r.getAttribute(i);return o?parseInt(o,10):(console.warn(`Missing attribute name '${i}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=r=>{var i;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const o=this.scrollState.index??((i=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:i.index);if(o!==void 0&&this.range){const l=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,o-l),d=Math.min(this.options.count-1,o+l);return r>=u&&r<=d}return!0},this.measureElement=r=>{if(!r){this.elementsCache.forEach((u,d)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(d))});return}const i=this.indexFromElement(r),o=this.options.getItemKey(i),l=this.elementsCache.get(o);l!==r&&(l&&this.observer.unobserve(l),this.observer.observe(r),this.elementsCache.set(o,r)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(i)&&this.resizeItem(i,this.options.measureElement(r,void 0,this))},this.resizeItem=(r,i)=>{var o,l;if(r<0||r>=this.options.count)return;let u,d,m;const p=this._flatMeasurements;if(this.options.lanes===1&&p!==null)m=this.options.getItemKey(r),d=p[r*2],u=p[r*2+1];else{const b=this.measurementsCache[r];if(!b)return;m=b.key,d=b.start,u=b.size}const y=this.itemSizeCache.get(m)??u,v=i-y;if(v!==0){const b=this.options.anchorTo==="end"&&((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=b?this.getTotalSize():0,w=((l=this.scrollState)==null?void 0:l.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[r]??{index:r,key:m,start:d,size:u,end:d+u,lane:0},v,this):d[this.getVirtualIndexes(),this.getMeasurements()],(r,i)=>{const o=[];for(let l=0,u=r.length;lthis.options.debug}),this.getVirtualItemForOffset=r=>{const i=this.getMeasurements();if(i.length===0)return;const o=this._flatMeasurements,l=this.options.lanes===1&&o!=null,u=KC(0,i.length-1,l?d=>o[d*2]:d=>lw(i[d]).start,r);return lw(i[u])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const r=this.scrollElement.document.documentElement;return this.options.horizontal?r.scrollWidth-this.scrollElement.innerWidth:r.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(r=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=r,this.getOffsetForAlignment=(r,i,o=0)=>{if(!this.scrollElement)return 0;const l=this.getSize(),u=this.getScrollOffset();i==="auto"&&(i=r>=u+l?"end":"start"),i==="center"?r+=(o-l)/2:i==="end"&&(r-=l);const d=this.getMaxScrollOffset();return Math.max(Math.min(d,r),0)},this.getOffsetForIndex=(r,i="auto")=>{r=Math.max(0,Math.min(r,this.options.count-1));const o=this.getSize(),l=this.getScrollOffset(),u=this.measurementsCache[r];if(!u)return;if(i==="auto")if(u.end>=l+o-this.options.scrollPaddingEnd)i="end";else if(u.start<=l+this.options.scrollPaddingStart)i="start";else return[l,i];if(i==="end"&&r===this.options.count-1)return[this.getMaxScrollOffset(),i];const d=i==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(d,i,u.size),i]},this.scrollToOffset=(r,{align:i="start",behavior:o="auto"}={})=>{const l=this.getOffsetForAlignment(r,i),u=this.now();this.scrollState={index:null,align:i,behavior:o,startedAt:u,lastTargetOffset:l,stableFrames:0},this._scrollToOffset(l,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollToIndex=(r,{align:i="auto",behavior:o="auto"}={})=>{r=Math.max(0,Math.min(r,this.options.count-1));const l=this.getOffsetForIndex(r,i);if(!l)return;const[u,d]=l,m=this.now();this.scrollState={index:r,align:d,behavior:o,startedAt:m,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollBy=(r,{behavior:i="auto"}={})=>{const o=this.getScrollOffset()+r,l=this.now();this.scrollState={index:null,align:"start",behavior:i,startedAt:l,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:r="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:r});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:r})},this.getTotalSize=()=>{var r;const i=this.getMeasurements();let o;if(i.length===0)o=this.options.paddingStart;else if(this.options.lanes===1){const l=i.length-1,u=this._flatMeasurements;u!=null?o=u[l*2]+u[l*2+1]:o=((r=i[l])==null?void 0:r.end)??0}else{const l=Array(this.options.lanes).fill(null);let u=i.length-1;for(;u>=0&&l.some(d=>d===null);){const d=i[u];l[d.lane]===null&&(l[d.lane]=d.end),u--}o=Math.max(...l.filter(d=>d!==null))}return Math.max(o-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const r=[];if(this.itemSizeCache.size===0)return r;const i=this.getMeasurements();for(const o of i)o&&this.itemSizeCache.has(o.key)&&r.push({index:o.index,key:o.key,start:o.start,size:o.size,end:o.end,lane:o.lane});return r},this._scrollToOffset=(r,{adjustments:i,behavior:o})=>{this._intendedScrollOffset=r+(i??0),this.options.scrollToFn(r,{behavior:o,adjustments:i},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,r){t!==0&&(sm()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:r}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const i=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,o=i?i[0]:this.scrollState.lastTargetOffset,l=1,u=o!==this.scrollState.lastTargetOffset;if(!u&&_I(o,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=l){this.getScrollOffset()!==o&&this._scrollToOffset(o,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,u){const d=this.getSize()||600,m=Math.abs(o-this.getScrollOffset()),p=this.scrollState.behavior==="smooth"&&m>d;this.scrollState.lastTargetOffset=o,p||(this.scrollState.behavior="auto"),this._scrollToOffset(o,{adjustments:void 0,behavior:p?"smooth":"auto"})}this.scheduleScrollReconcile()}}const KC=(e,t,r,i)=>{for(;e<=t;){const o=(e+t)/2|0,l=r(o);if(li)t=o-1;else return o}return e>0?e-1:0};function zI(e,t,r){let i=0;for(;i<=t;){const o=(i+t)/2|0,l=e[o*2];if(lr)t=o-1;else return o}return i>0?i-1:0}function LI(e,t,r,i,o){const l=e.length-1;if(e.length<=i)return{startIndex:0,endIndex:l};if(i===1&&o!==null){const p=zI(o,l,r);let y=p;const v=r+t;for(;ye[p].start,r),m=d;if(i===1)for(;m1){const p=Array(i).fill(0);for(;mv=0&&y.some(v=>v>=r);){const v=e[d];y[v.lane]=v.start,d--}d=Math.max(0,d-d%i),m=Math.min(l,m+(i-1-m%i))}return{startIndex:d,endIndex:m}}const om=typeof document<"u"?S.useLayoutEffect:S.useEffect;function $I({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:r="transform",...i}){const o=S.useReducer(p=>p+1,0)[1],l=S.useRef({enabled:t,mode:r,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});l.current.enabled=t,l.current.mode=r;const u=p=>{const y=l.current;if(!y.enabled||!y.container)return;const v=p.getTotalSize();if(v!==y.lastSize){y.lastSize=v;const R=p.options.horizontal?"width":"height";y.container.style[R]=`${v}px`}const b=!!p.options.horizontal,x=y.mode==="transform",w=b?"left":"top",_=p.options.scrollMargin,E=p.getVirtualItems();for(const R of E){const T=R.start-_,O=p.elementsCache.get(R.key);O&&y.lastPositions.get(O)!==T&&(y.lastPositions.set(O,T),x?O.style.transform=b?`translate3d(${T}px, 0, 0)`:`translate3d(0, ${T}px, 0)`:O.style[w]=`${T}px`)}},d={...i,onChange:(p,y)=>{var v;const b=l.current;let x=!0;if(b.enabled){u(p);const w=p.range,_=b.prevRange;x=!_||_.isScrolling!==p.isScrolling||_.startIndex!==w?.startIndex||_.endIndex!==w?.endIndex,x&&(b.prevRange=w?{startIndex:w.startIndex,endIndex:w.endIndex,isScrolling:p.isScrolling}:null)}x&&(e&&y?Di.flushSync(o):o()),(v=i.onChange)==null||v.call(i,p,y)}},[m]=S.useState(()=>{const p=new kI(d);return Object.assign(p,{containerRef:y=>{const v=l.current;if(v.container=y,v.lastSize=null,y&&v.enabled){const b=p.getTotalSize();v.lastSize=b;const x=p.options.horizontal?"width":"height";y.style[x]=`${b}px`}}})});return m.setOptions(d),om(()=>m._didMount(),[]),om(()=>m._willUpdate()),om(()=>{u(m)}),m}function II(e){return $I({observeElementRect:jI,observeElementOffset:AI,scrollToFn:DI,...e})}function PI(e,t){const r=[],i=(o,l)=>{for(const u of o)r.push({node:u,depth:l}),u.dir&&t.has(u.path)&&i(u.children||[],l+1)};return i(e?.children||[],0),r}function FI(e){const{root:t,expanded:r,onToggle:i,currentPath:o,listingShowing:l,onOpen:u}=e,d=S.useRef(null),m=S.useMemo(()=>PI(t,r),[t,r]),p=II({count:m.length,getScrollElement:()=>d.current,estimateSize:()=>window.matchMedia("(max-width: 768px)").matches?44:28,overscan:12,getItemKey:y=>m[y].node.path});return S.useEffect(()=>{if(!o)return;const y=m.findIndex(v=>v.node.path===o);y>=0&&p.scrollToIndex(y,{align:"auto"})},[o,m]),f.jsx("nav",{id:"tree","aria-label":"Files",ref:d,children:f.jsx("div",{style:{height:p.getTotalSize(),position:"relative"},children:p.getVirtualItems().map(y=>{const{node:v,depth:b}=m[y.index],x=v.dir?r.has(v.path):!1,w=()=>{if(v.dir&&o===v.path&&l){i(v.path);return}u(v.path),v.dir||hr()};return f.jsxs("div",{className:"row "+(v.dir?"dir":"file")+(o===v.path?" active":"")+(v.dir&&!x?" collapsed":""),"data-path":v.path,tabIndex:0,role:"button",title:v.name,"aria-expanded":v.dir?x:void 0,style:{position:"absolute",top:0,left:0,right:0,transform:`translateY(${y.start}px)`,paddingLeft:8+b*13},onClick:w,onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),w())},children:[Array.from({length:b},(_,E)=>f.jsx("span",{className:"tguide",style:{left:8+E*13+5},"aria-hidden":"true"},E)),f.jsx("span",{className:"chev",onClick:_=>{v.dir&&(_.stopPropagation(),i(v.path))},children:f.jsx(lt,{name:"chevd"})}),f.jsx("span",{className:"ticon",children:f.jsx(lt,{name:v.dir?"folder":"doc"})}),f.jsx("span",{className:"label",children:v.name})]},y.key)})})})}function VI(e){const t=e.split("/"),r=[];let i="";for(let o=0;o{i=i?i+"/"+o:o;const u=i,d=l===r.length-1;return f.jsxs("span",{children:[l>0&&f.jsx("span",{className:"crumb-sep",children:"/"}),d?f.jsx("span",{children:o}):f.jsx("span",{className:"crumb-seg",title:u,onClick:()=>t(u),children:o})]},u)})})}function uw(e){if(e==="")return[];const t=e.split(` `);return t[t.length-1]===""&&t.pop(),t}const HI=4e6;function BI(e,t){let r=0;for(;ro.push({op:"-",line:l[v],an:r+v+1}),y=v=>o.push({op:"+",line:u[v],bn:r+v+1});if(d*m>HI){for(let v=0;v=0;w--)for(let _=m-1;_>=0;_--)v[w][_]=l[w]===u[_]?v[w+1][_+1]+1:Math.max(v[w+1][_],v[w][_+1]);let b=0,x=0;for(;b=v[b][x+1]?p(b++):y(x++);for(;bi.op==="+").length,del:r.filter(i=>i.op==="-").length}}const YC=1<<20,GI=8192;function ZI(e){if(e.byteLength>YC)return{kind:"too-large",size:e.byteLength};if(e.subarray(0,GI).includes(0))return{kind:"binary"};try{return{kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(e)}}catch{return{kind:"binary"}}}function ep(e,t,r,i){let o=e+"blob?sha="+encodeURIComponent(t);return r&&(o+="&name="+encodeURIComponent(r)),i&&(o+="&download=1"),o}async function KI(e){const t=await wj(e),r=Number(t.headers.get("Content-Length"));return r>YC?{kind:"too-large",size:r}:ZI(new Uint8Array(await t.arrayBuffer()))}function QC(e,t,r,i){return Ft({queryKey:t,queryFn:()=>KI(e),enabled:r,...i?{staleTime:1/0,gcTime:1/0}:{},retry:!1})}function dw(e,t,r){return QC(t?ep(e,t):"",["blob",e,t],!!t,!0)}function YI(e){return e.slice(e.lastIndexOf("/")+1)}function QI({apiBase:e,path:t,prev:r,cur:i}){const o=YI(t);return f.jsxs("span",{className:"dv-dl",children:[f.jsx("a",{href:ep(e,r,o,!0),children:"download previous"}),f.jsx("a",{href:ep(e,i,o,!0),children:"download this version"})]})}function XI({apiBase:e,path:t,prev:r,cur:i}){const o=dw(e,r),l=dw(e,i),u=o.data?.kind==="text"&&l.data?.kind==="text",d=S.useMemo(()=>o.data?.kind==="text"&&l.data?.kind==="text"?qI(o.data.text,l.data.text):null,[o.data,l.data]);if(o.error||l.error)return f.jsx("div",{className:"dv dv-msg",children:"Could not load one of the versions."});if(!o.data||!l.data)return f.jsx("div",{className:"dv dv-msg",children:"Loading changes…"});if(!u){const v=o.data.kind==="too-large"||l.data.kind==="too-large";return f.jsxs("div",{className:"dv dv-msg",children:[v?"Too large to diff — download to compare.":"Binary file — no diff available.",f.jsx(QI,{apiBase:e,path:t,prev:r,cur:i})]})}const{lines:m,add:p,del:y}=d;return f.jsxs("div",{className:"dv",children:[f.jsxs("div",{className:"dv-head",children:[f.jsxs("span",{className:"dv-stat",children:[f.jsxs("span",{className:"dv-add",children:["+",p]})," ",f.jsxs("span",{className:"dv-del",children:["−",y]})]}),p===0&&y===0&&f.jsx("span",{className:"dv-same",children:"No line changes"})]}),f.jsx("div",{className:"dv-body",children:m.map((v,b)=>f.jsxs("div",{className:"dv-line dv-"+(v.op==="="?"ctx":v.op==="+"?"ins":"rm"),children:[f.jsx("span",{className:"dv-n",children:v.an??""}),f.jsx("span",{className:"dv-n",children:v.bn??""}),f.jsx("span",{className:"dv-mark",children:v.op==="="?" ":v.op}),f.jsx("span",{className:"dv-text",children:v.line||" "})]},b))})]})}const JI={add:"added",edit:"edited",delete:"deleted"};function XC({text:e}){return f.jsx(f.Fragment,{children:e.split(/(https?:\/\/\S+)/).map((t,r)=>/^https?:\/\//.test(t)?f.jsx("a",{href:t,target:"_blank",rel:"noopener",children:t},r):t)})}function vg({entry:e,apiBase:t,onOpen:r,diff:i,restore:o,remove:l,restoreSha:u,recreates:d,inRun:m,read:p}){const[y,v]=S.useState(!1),[b,x]=S.useState(!1),w=e.kind==="put"?"edit":e.kind,_=fd(e),E=[e.device.name||e.device.id,e.device.os].filter(Boolean).join(" · "),R=w!=="delete",T=!!i&&w!=="delete"&&!!e.blob,O=!!m&&w==="add",N=!!o&&!!u&&!O,k=!!l&&O,B=!!o?.busy&&o.busy===e.path+u,H=!!l?.busy&&l.busy===e.path,$=R&&!!e.blob,he=e.path.split("/").pop()||e.path,be=new Date(e.time).toLocaleString(),pe=t+"blob?sha="+e.blob+"&name="+encodeURIComponent(he)+"&download=1",fe=()=>x(!b),ue=W=>{W.target.tagName!=="A"&&R&&r(e.path,e.blob)};return f.jsxs("div",{className:"hentry "+w+(R?" clickable":""),tabIndex:R?0:void 0,role:R?"button":void 0,onClick:ue,onKeyDown:W=>{R&&(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),r(e.path,e.blob))},children:[f.jsxs("div",{className:"hline",children:[f.jsx("span",{className:"hkind",children:JI[w]||w}),p&&f.jsx("span",{className:"hread",title:"This run read this file before changing it",children:"read"}),f.jsx("span",{className:"hpath",children:e.path}),f.jsx("span",{className:"htime",children:be})]}),f.jsxs("div",{className:"hmeta",children:[f.jsx("span",{className:"hwho",children:_}),f.jsx("span",{className:"hdev",children:E}),f.jsx("span",{className:"hsize",children:e.size?gg(e.size):""}),N&&f.jsxs("button",{type:"button",className:"hrestore-btn",disabled:B,title:"Put this version of "+e.path+" back as a new change",onClick:W=>{W.stopPropagation(),o.onRestore(e.path,u,!!d)},onKeyDown:W=>W.stopPropagation(),children:[f.jsx(lt,{name:"hist"}),B?"restoring…":"restore"]}),k&&f.jsxs("button",{type:"button",className:"hremove-btn",disabled:H,title:"Remove "+e.path+" — this run created it",onClick:W=>{W.stopPropagation(),l.onRemove(e.path)},onKeyDown:W=>W.stopPropagation(),children:[f.jsx(lt,{name:"trash"}),H?"removing…":"undo — remove file"]})]}),e.note&&!m&&f.jsx("div",{className:"hnote"+(y?" open":""),tabIndex:0,role:"button",title:y?"Collapse note":"Show full note","aria-expanded":y,onClick:W=>{W.stopPropagation(),W.target.tagName!=="A"&&v(!y)},onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),W.stopPropagation(),v(!y))},children:f.jsx(XC,{text:e.note})}),(T||$)&&f.jsxs("div",{className:"hactions",children:[T&&(i.prev?f.jsxs("button",{type:"button",className:"hdiff-btn"+(b?" open":""),"aria-expanded":b,onClick:W=>{W.stopPropagation(),fe()},onKeyDown:W=>W.stopPropagation(),children:[f.jsx(lt,{name:b?"chevd":"chev"}),b?"hide changes":"show changes"]}):f.jsx("div",{className:"hdiff-none",children:"First version — nothing to compare against"})),$&&f.jsxs(f.Fragment,{children:[f.jsxs("button",{type:"button",className:"hver-btn","aria-label":`Open ${he} as of ${be}`,onClick:W=>{W.stopPropagation(),r(e.path,e.blob)},onKeyDown:W=>W.stopPropagation(),children:[f.jsx(lt,{name:"clock"}),"Open this version"]}),f.jsxs("a",{className:"hver-btn",download:!0,href:pe,"aria-label":`Download ${he} as of ${be}`,onClick:W=>W.stopPropagation(),onKeyDown:W=>{W.stopPropagation(),W.key===" "&&(W.preventDefault(),W.currentTarget.click())},children:[f.jsx(lt,{name:"download"}),"Download"]})]})]}),T&&i.prev&&b&&f.jsx("div",{onClick:W=>W.stopPropagation(),children:f.jsx(XI,{apiBase:i.apiBase,path:e.path,prev:i.prev,cur:e.blob})})]})}function WI(e){const{node:t,heatMap:r,onOpen:i}=e,o=(t.children||[]).slice().sort((y,v)=>Number(v.dir||!1)-Number(y.dir||!1)||y.name.localeCompare(v.name)),l=o.filter(y=>y.dir).length,u=o.length-l,d=[];l&&d.push(l+(l===1?" folder":" folders")),u&&d.push(u+(u===1?" file":" files"));const m=am(r,t.path,!0);m&&d.push(el(m)+" in 30 days");const p=!!m||o.some(y=>am(r,y.path,!!y.dir));return f.jsxs("div",{className:"dirlist",children:[f.jsxs("h1",{className:"dl-title",children:[f.jsx("span",{className:"dl-title-icon",children:f.jsx(lt,{name:"folder"})}),f.jsx("span",{children:t.name})]}),f.jsx("p",{className:"dl-sub",children:d.join(" · ")||"Empty folder"}),p&&f.jsx("p",{className:"dl-heatnote",children:Ci}),o.length===0?f.jsx("div",{className:"dl-empty",children:"Nothing in this folder yet."}):f.jsx("div",{className:"dl-items",children:o.map(y=>{let v="";if(y.dir){const w=(y.children||[]).length;v=w+(w===1?" item":" items")}else v=[y.size?gg(y.size):"",y.time?new Date(y.time).toLocaleDateString():""].filter(Boolean).join(" · ");const b=am(r,y.path,!!y.dir);b&&(v=el(b)+(v?" · "+v:""));const x=y.dir?"":ZC(b,y.time);return f.jsxs("div",{className:"dl-row",tabIndex:0,role:"button",title:y.path,onClick:()=>i(y.path),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),i(y.path))},children:[f.jsx("span",{className:"ticon",children:f.jsx(lt,{name:y.dir?"folder":"doc"})}),f.jsx("span",{className:"dl-name",children:y.name}),x&&f.jsx("span",{className:"stalemark",role:"img","aria-label":"Warning: "+x,title:"Read often, but "+x,children:"⚠"}),b&&f.jsx("span",{className:"heatdot lvl"+oI(b),role:"img","aria-label":el(b)+" in 30 days. "+Ci,title:el(b)+" in 30 days. "+Ci}),f.jsx("span",{className:"dl-meta",children:v})]},y.path)})}),e.hub&&f.jsx(eP,{apiBase:e.apiBase,prefix:t.path+"/",onOpen:i,onFullHistory:()=>e.onFullHistory(t.path+"/"),onRendered:e.onRendered})]})}function eP(e){const t=wI(e.apiBase,e.prefix,!0),{onRendered:r}=e;return S.useEffect(()=>{t&&t.length&&r&&r()},[t,r]),!t||t.length===0?null:f.jsxs("div",{className:"dl-history",children:[f.jsx("h3",{className:"dl-h3",children:"Recent changes"}),f.jsx("div",{className:"history dl-hlist",children:t.map((i,o)=>f.jsx(vg,{entry:i,apiBase:e.apiBase,onOpen:e.onOpen},o))}),f.jsx("button",{className:"ai-btn dl-more",onClick:e.onFullHistory,children:"Full history"})]})}const JC=5e3;function tP(e,t,r=JC){const i=[];let o=[],l="",u=!1,d=0;const m=()=>{o.push(l),l="",i.length()=>o(""),[r,o]),C$.test(r)?f.jsx(iP,{...e}):AC.test(r)?f.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts",src:l,title:r,onLoad:e.onRendered}):MC.test(r)?f.jsx("iframe",{className:"pdfview",src:l,title:r,onLoad:e.onRendered}):E$.test(r)?f.jsx(lP,{src:l,alt:r,version:i,onRendered:e.onRendered}):R$.test(r)?f.jsx(fw,{...e,fileURL:l,delim:/\.tsv$/i.test(r)?" ":","}):j$.test(r)?f.jsx(fw,{...e,fileURL:l}):f.jsx(rP,{...e,fileURL:l})}function rP(e){const{apiBase:t,path:r,version:i,fileURL:o,onRendered:l}=e,{data:u,error:d}=QC(o,["text",o],!0,!!i);return S.useEffect(()=>{u&&l?.()},[u,l]),d?f.jsx(hd,{version:i,err:d}):u?u.kind==="text"?f.jsx("pre",{className:"plain",children:u.text},r):f.jsx(aP,{apiBase:t,path:r,version:i,fileURL:o,children:u.kind==="too-large"?`Too large to preview (${gg(u.size)}).`:"No preview for this file type."}):null}function aP(e){const{apiBase:t,path:r,version:i,fileURL:o}=e;return f.jsxs("div",{className:"filecard",children:[f.jsx("div",{className:"name",children:r.split("/").pop()}),f.jsx("p",{children:e.children}),f.jsx("a",{className:"btn",download:!0,href:i?o+"&download=1":t+"download?path="+encodeURIComponent(r),children:"Download"})]})}function iP(e){const{apiBase:t,path:r,version:i,heatMap:o,flatFiles:l,projectId:u,onOpenFile:d,onMeta:m,onRendered:p}=e,{data:y,error:v}=Ft({queryKey:["render",t,r,i||""],queryFn:()=>qt(t+"render?path="+encodeURIComponent(r)+(i?"&sha="+i:"")),retry:i?!1:void 0}),b=S.useMemo(()=>y?oP(y.html,r,t,l,u):"",[y,r,t,l,u]),[x,w]=S.useState(null);return S.useEffect(()=>{if(w(null),!w2(b))return;let _=!1;return S2(b).then(E=>{_||w(E)}),()=>{_=!0}},[b]),S.useEffect(()=>{if(!y)return;const _=[],E=i?null:o&&o[y.path],R=ZC(E||null,y.time);(y.user_name||y.user||y.author)&&_.push(fd(y)+(y.device?" on "+y.device:"")),y.time&&_.push(new Date(y.time).toLocaleString());const T=E&&na(E)?el(E)+" / 30d":"",O=R?f.jsxs("span",{className:"meta-stale",title:R,children:[f.jsx("span",{"aria-hidden":"true",children:"⚠ "}),R]}):null;m(T?f.jsxs(f.Fragment,{children:[O,O?" · ":"",_.length?_.join(" · ")+" · ":"",f.jsxs("span",{title:Ci,children:[T,f.jsxs("span",{className:"sr-only",children:[" — ",Ci]})]})]}):O?f.jsxs(f.Fragment,{children:[O,_.length?" · "+_.join(" · "):""]}):_.join(" · ")),p?.()},[y,i,o,m,p]),v?f.jsx(hd,{version:i,err:v}):y?f.jsx("div",{dangerouslySetInnerHTML:{__html:x??b},onClick:_=>sP(_,r,d)}):null}function sP(e,t,r){const i=e.target.closest("a");if(!i||!e.currentTarget.contains(i)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const o=i.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=i.getAttribute("data-wiki");u!==null?(e.preventDefault(),r(u)):/^([a-z]+:|\/|#)/i.test(o)||(e.preventDefault(),r(NC(l,decodeURIComponent(o))))}function oP(e,t,r,i,o){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=m=>r+"file?path="+encodeURIComponent(m),d=new DOMParser().parseFromString(e,"text/html");for(const m of d.querySelectorAll("img")){const p=m.getAttribute("src")||"";/^\s*data:image\/svg/i.test(p)?m.removeAttribute("src"):/^([a-z]+:|\/)/i.test(p)||m.setAttribute("src",u(NC(l,p)))}for(const m of d.querySelectorAll("a")){const p=m.getAttribute("href")||"";if(p.startsWith("wiki:")){const y=T$(decodeURIComponent(p.slice(5)),i);y?(m.setAttribute("href",qs(y.path,o)),m.setAttribute("data-wiki",y.path)):(m.removeAttribute("href"),m.classList.add("wiki-missing"),m.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(p)?m.removeAttribute("href"):/^https?:/i.test(p)&&(m.setAttribute("target","_blank"),m.setAttribute("rel","noopener"))}return d.body.innerHTML}function lP(e){const[t,r]=S.useState(!1);return t?f.jsx(hd,{version:e.version,err:new Error("could not be loaded")}):f.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>r(!0)})}function hd({version:e,err:t}){return f.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function fw(e){const{path:t,version:r,fileURL:i,delim:o,onRendered:l}=e,{data:u,error:d}=Ft({queryKey:["text",i],queryFn:async()=>{const p=await fetch(i);if(!p.ok)throw new Error(await p.text());return p.text()},retry:r?!1:void 0});S.useEffect(()=>{u!=null&&l?.()},[u,l]);const m=S.useMemo(()=>o&&u!=null?tP(u,o,JC):null,[u,o]);return d?f.jsx(hd,{version:r,err:d}):u==null?null:m?f.jsx(cP,{csv:m},t):f.jsx("pre",{className:"plain",children:u},t)}function cP({csv:e}){const[t,...r]=e.rows,i=e.rows.reduce((l,u)=>Math.max(l,u.length),0),o=Array.from({length:i},(l,u)=>u);return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"csvbox",children:f.jsxs("table",{className:"csvview",children:[f.jsx("thead",{children:f.jsx("tr",{children:o.map(l=>f.jsx("th",{children:t[l]??""},l))})}),f.jsx("tbody",{children:r.map((l,u)=>f.jsx("tr",{children:o.map(d=>f.jsx("td",{children:l[d]??""},d))},u))})]})}),e.truncated>0&&f.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}const uP=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}];function dP({url:e,copied:t,onClose:r}){const i=e.split("/s/")[1],[o,l]=S.useState(""),[u,d]=S.useState(),[m,p]=S.useState(!1),y=S.useRef(null);async function v(b){const x=o;l(b),p(!0);try{const w=await Wn("PATCH","/api/shares/"+i,{expires_in:b});d(w.expires)}catch(w){Ge(w.message,!0),l(x)}finally{p(!1)}}return f.jsx(Wu,{open:!0,onOpenChange:b=>!b&&r(),children:f.jsxs(ed,{className:"modal",showCloseButton:!1,onOpenAutoFocus:b=>{b.preventDefault(),y.current?.focus()},children:[f.jsx(Cl,{asChild:!0,children:f.jsx("h3",{children:"Public link"})}),f.jsxs("p",{children:[f.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until it expires or you revoke it."]}),f.jsx("div",{className:"modal-url",children:e}),f.jsxs("div",{className:"modal-expiry",children:[f.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),f.jsx("select",{id:"share-expiry",value:o,disabled:m,onChange:b=>v(b.target.value),children:uP.map(b=>f.jsx("option",{value:b.value,children:b.label},b.value))}),f.jsx("span",{className:"modal-expiry-note",children:zC(u)})]}),f.jsxs("div",{className:"modal-actions",children:[f.jsx(xt,{ref:y,variant:"primary",onClick:()=>Zs(e).then(b=>Ge(b?"Copied.":"Select and copy the link above.")),children:t?"Copied ✓":"Copy link"}),f.jsx(xt,{variant:"subtle",onClick:()=>window.open(e,"_blank"),children:"Open"}),f.jsx(xt,{variant:"subtle",onClick:r,children:"Done"})]})]})})}function fP({shares:e,canRevoke:t,onChanged:r}){return e.length===0?null:f.jsxs("div",{className:"share-banner",role:"status",children:[f.jsxs("div",{className:"sb-head",children:[f.jsx(lt,{name:"share"}),f.jsx("b",{children:"Publicly shared"}),f.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),f.jsxs("p",{className:"sb-note",children:[f.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(i=>i.opens!==void 0)&&f.jsxs(f.Fragment,{children:[" ",$C]})]}),e.map(i=>f.jsxs("div",{className:"sb-link",children:[f.jsx("span",{className:"sb-url mono",title:i.url,children:i.url}),f.jsx("span",{className:"sb-meta",children:LC(i,!1)}),f.jsxs("span",{className:"sb-actions",children:[f.jsx(xt,{variant:"subtle",onClick:()=>Zs(i.url).then(o=>Ge(o?"Copied.":"Select and copy the link.")),children:"Copy link"}),f.jsx(xt,{variant:"subtle",onClick:()=>window.open(i.url,"_blank"),children:"Open"}),t&&f.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${i.path}`,onClick:()=>PC(i,r),children:"Revoke"})]})]},i.token))]})}var hw=1,hP=.9,mP=.8,pP=.17,lm=.1,cm=.999,gP=.9999,vP=.99,yP=/[\\\/_+.#"@\[\(\{&]/,bP=/[\\\/_+.#"@\[\(\{&]/g,xP=/[\s-]/,WC=/[\s-]/g;function tp(e,t,r,i,o,l,u){if(l===t.length)return o===e.length?hw:vP;var d=`${o},${l}`;if(u[d]!==void 0)return u[d];for(var m=i.charAt(l),p=r.indexOf(m,o),y=0,v,b,x,w;p>=0;)v=tp(e,t,r,i,p+1,l+1,u),v>y&&(p===o?v*=hw:yP.test(e.charAt(p-1))?(v*=mP,x=e.slice(o,p-1).match(bP),x&&o>0&&(v*=Math.pow(cm,x.length))):xP.test(e.charAt(p-1))?(v*=hP,w=e.slice(o,p-1).match(WC),w&&o>0&&(v*=Math.pow(cm,w.length))):(v*=pP,o>0&&(v*=Math.pow(cm,p-o))),e.charAt(p)!==t.charAt(l)&&(v*=gP)),(vv&&(v=b*lm)),v>y&&(y=v),p=r.indexOf(m,p+1);return u[d]=y,y}function mw(e){return e.toLowerCase().replace(WC," ")}function wP(e,t,r){return e=r&&r.length>0?`${e+" "+r.join(" ")}`:e,tp(e,t,mw(e),mw(t),0,0,{})}var Yo='[cmdk-group=""]',um='[cmdk-group-items=""]',SP='[cmdk-group-heading=""]',eE='[cmdk-item=""]',pw=`${eE}:not([aria-disabled="true"])`,np="cmdk-item-select",Ns="data-value",_P=(e,t,r)=>wP(e,t,r),tE=S.createContext(void 0),Tl=()=>S.useContext(tE),nE=S.createContext(void 0),yg=()=>S.useContext(nE),rE=S.createContext(void 0),aE=S.forwardRef((e,t)=>{let r=Ds(()=>{var M,U;return{search:"",value:(U=(M=e.value)!=null?M:e.defaultValue)!=null?U:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),i=Ds(()=>new Set),o=Ds(()=>new Map),l=Ds(()=>new Map),u=Ds(()=>new Set),d=iE(e),{label:m,children:p,value:y,onValueChange:v,filter:b,shouldFilter:x,loop:w,disablePointerSelection:_=!1,vimBindings:E=!0,...R}=e,T=fn(),O=fn(),N=fn(),k=S.useRef(null),B=kP();Mi(()=>{if(y!==void 0){let M=y.trim();r.current.value=M,H.emit()}},[y]),Mi(()=>{B(6,ue)},[]);let H=S.useMemo(()=>({subscribe:M=>(u.current.add(M),()=>u.current.delete(M)),snapshot:()=>r.current,setState:(M,U,Q)=>{var K,de,re,xe;if(!Object.is(r.current[M],U)){if(r.current[M]=U,M==="search")fe(),be(),B(1,pe);else if(M==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let we=document.getElementById(N);we?we.focus():(K=document.getElementById(T))==null||K.focus()}if(B(7,()=>{var we;r.current.selectedItemId=(we=W())==null?void 0:we.id,H.emit()}),Q||B(5,ue),((de=d.current)==null?void 0:de.value)!==void 0){let we=U??"";(xe=(re=d.current).onValueChange)==null||xe.call(re,we);return}}H.emit()}},emit:()=>{u.current.forEach(M=>M())}}),[]),$=S.useMemo(()=>({value:(M,U,Q)=>{var K;U!==((K=l.current.get(M))==null?void 0:K.value)&&(l.current.set(M,{value:U,keywords:Q}),r.current.filtered.items.set(M,he(U,Q)),B(2,()=>{be(),H.emit()}))},item:(M,U)=>(i.current.add(M),U&&(o.current.has(U)?o.current.get(U).add(M):o.current.set(U,new Set([M]))),B(3,()=>{fe(),be(),r.current.value||pe(),H.emit()}),()=>{l.current.delete(M),i.current.delete(M),r.current.filtered.items.delete(M);let Q=W();B(4,()=>{fe(),Q?.getAttribute("id")===M&&pe(),H.emit()})}),group:M=>(o.current.has(M)||o.current.set(M,new Set),()=>{l.current.delete(M),o.current.delete(M)}),filter:()=>d.current.shouldFilter,label:m||e["aria-label"],getDisablePointerSelection:()=>d.current.disablePointerSelection,listId:T,inputId:N,labelId:O,listInnerRef:k}),[]);function he(M,U){var Q,K;let de=(K=(Q=d.current)==null?void 0:Q.filter)!=null?K:_P;return M?de(M,r.current.search,U):0}function be(){if(!r.current.search||d.current.shouldFilter===!1)return;let M=r.current.filtered.items,U=[];r.current.filtered.groups.forEach(K=>{let de=o.current.get(K),re=0;de.forEach(xe=>{let we=M.get(xe);re=Math.max(we,re)}),U.push([K,re])});let Q=k.current;ve().sort((K,de)=>{var re,xe;let we=K.getAttribute("id"),Me=de.getAttribute("id");return((re=M.get(Me))!=null?re:0)-((xe=M.get(we))!=null?xe:0)}).forEach(K=>{let de=K.closest(um);de?de.appendChild(K.parentElement===de?K:K.closest(`${um} > *`)):Q.appendChild(K.parentElement===Q?K:K.closest(`${um} > *`))}),U.sort((K,de)=>de[1]-K[1]).forEach(K=>{var de;let re=(de=k.current)==null?void 0:de.querySelector(`${Yo}[${Ns}="${encodeURIComponent(K[0])}"]`);re?.parentElement.appendChild(re)})}function pe(){let M=ve().find(Q=>Q.getAttribute("aria-disabled")!=="true"),U=M?.getAttribute(Ns);H.setState("value",U||void 0)}function fe(){var M,U,Q,K;if(!r.current.search||d.current.shouldFilter===!1){r.current.filtered.count=i.current.size;return}r.current.filtered.groups=new Set;let de=0;for(let re of i.current){let xe=(U=(M=l.current.get(re))==null?void 0:M.value)!=null?U:"",we=(K=(Q=l.current.get(re))==null?void 0:Q.keywords)!=null?K:[],Me=he(xe,we);r.current.filtered.items.set(re,Me),Me>0&&de++}for(let[re,xe]of o.current)for(let we of xe)if(r.current.filtered.items.get(we)>0){r.current.filtered.groups.add(re);break}r.current.filtered.count=de}function ue(){var M,U,Q;let K=W();K&&(((M=K.parentElement)==null?void 0:M.firstChild)===K&&((Q=(U=K.closest(Yo))==null?void 0:U.querySelector(SP))==null||Q.scrollIntoView({block:"nearest"})),K.scrollIntoView({block:"nearest"}))}function W(){var M;return(M=k.current)==null?void 0:M.querySelector(`${eE}[aria-selected="true"]`)}function ve(){var M;return Array.from(((M=k.current)==null?void 0:M.querySelectorAll(pw))||[])}function L(M){let U=ve()[M];U&&H.setState("value",U.getAttribute(Ns))}function Z(M){var U;let Q=W(),K=ve(),de=K.findIndex(xe=>xe===Q),re=K[de+M];(U=d.current)!=null&&U.loop&&(re=de+M<0?K[K.length-1]:de+M===K.length?K[0]:K[de+M]),re&&H.setState("value",re.getAttribute(Ns))}function ne(M){let U=W(),Q=U?.closest(Yo),K;for(;Q&&!K;)Q=M>0?NP(Q,Yo):DP(Q,Yo),K=Q?.querySelector(pw);K?H.setState("value",K.getAttribute(Ns)):Z(M)}let X=()=>L(ve().length-1),ee=M=>{M.preventDefault(),M.metaKey?X():M.altKey?ne(1):Z(1)},D=M=>{M.preventDefault(),M.metaKey?L(0):M.altKey?ne(-1):Z(-1)};return S.createElement(Pe.div,{ref:t,tabIndex:-1,...R,"cmdk-root":"",onKeyDown:M=>{var U;(U=R.onKeyDown)==null||U.call(R,M);let Q=M.nativeEvent.isComposing||M.keyCode===229;if(!(M.defaultPrevented||Q))switch(M.key){case"n":case"j":{E&&M.ctrlKey&&ee(M);break}case"ArrowDown":{ee(M);break}case"p":case"k":{E&&M.ctrlKey&&D(M);break}case"ArrowUp":{D(M);break}case"Home":{M.preventDefault(),L(0);break}case"End":{M.preventDefault(),X();break}case"Enter":{M.preventDefault();let K=W();if(K){let de=new Event(np);K.dispatchEvent(de)}}}}},S.createElement("label",{"cmdk-label":"",htmlFor:$.inputId,id:$.labelId,style:LP},m),pd(e,M=>S.createElement(nE.Provider,{value:H},S.createElement(tE.Provider,{value:$},M))))}),CP=S.forwardRef((e,t)=>{var r,i;let o=fn(),l=S.useRef(null),u=S.useContext(rE),d=Tl(),m=iE(e),p=(i=(r=m.current)==null?void 0:r.forceMount)!=null?i:u?.forceMount;Mi(()=>{if(!p)return d.item(o,u?.id)},[p]);let y=sE(o,l,[e.value,e.children,l],e.keywords),v=yg(),b=Za(B=>B.value&&B.value===y.current),x=Za(B=>p||d.filter()===!1?!0:B.search?B.filtered.items.get(o)>0:!0);S.useEffect(()=>{let B=l.current;if(!(!B||e.disabled))return B.addEventListener(np,w),()=>B.removeEventListener(np,w)},[x,e.onSelect,e.disabled]);function w(){var B,H;_(),(H=(B=m.current).onSelect)==null||H.call(B,y.current)}function _(){v.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:R,onSelect:T,forceMount:O,keywords:N,...k}=e;return S.createElement(Pe.div,{ref:Vs(l,t),...k,id:o,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!b,"data-disabled":!!E,"data-selected":!!b,onPointerMove:E||d.getDisablePointerSelection()?void 0:_,onClick:E?void 0:w},e.children)}),EP=S.forwardRef((e,t)=>{let{heading:r,children:i,forceMount:o,...l}=e,u=fn(),d=S.useRef(null),m=S.useRef(null),p=fn(),y=Tl(),v=Za(x=>o||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);Mi(()=>y.group(u),[]),sE(u,d,[e.value,e.heading,m]);let b=S.useMemo(()=>({id:u,forceMount:o}),[o]);return S.createElement(Pe.div,{ref:Vs(d,t),...l,"cmdk-group":"",role:"presentation",hidden:v?void 0:!0},r&&S.createElement("div",{ref:m,"cmdk-group-heading":"","aria-hidden":!0,id:p},r),pd(e,x=>S.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?p:void 0},S.createElement(rE.Provider,{value:b},x))))}),RP=S.forwardRef((e,t)=>{let{alwaysRender:r,...i}=e,o=S.useRef(null),l=Za(u=>!u.search);return!r&&!l?null:S.createElement(Pe.div,{ref:Vs(o,t),...i,"cmdk-separator":"",role:"separator"})}),jP=S.forwardRef((e,t)=>{let{onValueChange:r,...i}=e,o=e.value!=null,l=yg(),u=Za(p=>p.search),d=Za(p=>p.selectedItemId),m=Tl();return S.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),S.createElement(Pe.input,{ref:t,...i,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":m.listId,"aria-labelledby":m.labelId,"aria-activedescendant":d,id:m.inputId,type:"text",value:o?e.value:u,onChange:p=>{o||l.setState("search",p.target.value),r?.(p.target.value)}})}),TP=S.forwardRef((e,t)=>{let{children:r,label:i="Suggestions",...o}=e,l=S.useRef(null),u=S.useRef(null),d=Za(p=>p.selectedItemId),m=Tl();return S.useEffect(()=>{if(u.current&&l.current){let p=u.current,y=l.current,v,b=new ResizeObserver(()=>{v=requestAnimationFrame(()=>{let x=p.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return b.observe(p),()=>{cancelAnimationFrame(v),b.unobserve(p)}}},[]),S.createElement(Pe.div,{ref:Vs(l,t),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":d,"aria-label":i,id:m.listId},pd(e,p=>S.createElement("div",{ref:Vs(u,m.listInnerRef),"cmdk-list-sizer":""},p)))}),OP=S.forwardRef((e,t)=>{let{open:r,onOpenChange:i,overlayClassName:o,contentClassName:l,container:u,...d}=e;return S.createElement(pp,{open:r,onOpenChange:i},S.createElement(vp,{container:u},S.createElement(yp,{"cmdk-overlay":"",className:o}),S.createElement(bp,{"aria-label":e.label,"cmdk-dialog":"",className:l},S.createElement(aE,{ref:t,...d}))))}),AP=S.forwardRef((e,t)=>Za(r=>r.filtered.count===0)?S.createElement(Pe.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),MP=S.forwardRef((e,t)=>{let{progress:r,children:i,label:o="Loading...",...l}=e;return S.createElement(Pe.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},pd(e,u=>S.createElement("div",{"aria-hidden":!0},u)))}),md=Object.assign(aE,{List:TP,Item:CP,Input:jP,Group:EP,Separator:RP,Dialog:OP,Empty:AP,Loading:MP});function NP(e,t){let r=e.nextElementSibling;for(;r;){if(r.matches(t))return r;r=r.nextElementSibling}}function DP(e,t){let r=e.previousElementSibling;for(;r;){if(r.matches(t))return r;r=r.previousElementSibling}}function iE(e){let t=S.useRef(e);return Mi(()=>{t.current=e}),t}var Mi=typeof window>"u"?S.useEffect:S.useLayoutEffect;function Ds(e){let t=S.useRef();return t.current===void 0&&(t.current=e()),t}function Za(e){let t=yg(),r=()=>e(t.snapshot());return S.useSyncExternalStore(t.subscribe,r,r)}function sE(e,t,r,i=[]){let o=S.useRef(),l=Tl();return Mi(()=>{var u;let d=(()=>{var p;for(let y of r){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(p=y.current.textContent)==null?void 0:p.trim():o.current}})(),m=i.map(p=>p.trim());l.value(e,d,m),(u=t.current)==null||u.setAttribute(Ns,d),o.current=d}),o}var kP=()=>{let[e,t]=S.useState(),r=Ds(()=>new Map);return Mi(()=>{r.current.forEach(i=>i()),r.current=new Map},[e]),(i,o)=>{r.current.set(i,o),t({})}};function zP(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function pd({asChild:e,children:t},r){return e&&S.isValidElement(t)?S.cloneElement(zP(t),{ref:t.ref},r(t.props.children)):r(t)}var LP={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function $P({className:e,...t}){return f.jsx(md,{"data-slot":"command",className:We("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function IP({className:e,...t}){return f.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[f.jsx(x_,{className:"size-4 shrink-0 opacity-50"}),f.jsx(md.Input,{"data-slot":"command-input",className:We("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function PP({className:e,...t}){return f.jsx(md.List,{"data-slot":"command-list",className:We("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function FP({className:e,...t}){return f.jsx(md.Item,{"data-slot":"command-item",className:We("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}function gw(e,t){if(!e)return{score:0,hits:[]};const r=e.toLowerCase(),i=t.toLowerCase();let o=0,l=0,u=0;const d=[];for(let m=0;m3&&i.endsWith("ies")?o=i.slice(0,-3)+"y":i.length>3&&i.endsWith("es")?o=i.slice(0,-2):i.length>2&&i.endsWith("s")&&(o=i.slice(0,-1)),o?gw(o,t):null}function UP({text:e,hits:t}){const r=[];let i=0;return t.forEach((o,l)=>{o>i&&r.push(e.slice(i,o)),r.push(f.jsx("b",{children:e[o]},l)),i=o+1}),r.push(e.slice(i)),f.jsx("span",{className:"plabel",children:r})}function HP({open:e,onClose:t,candidates:r}){const[i,o]=S.useState(""),l=S.useMemo(()=>{if(!e)return[];const d=[];for(const m of r()){const p=VP(i,m.label);p&&d.push({...m,score:p.score,hits:p.hits})}return d.sort((m,p)=>p.score-m.score),d.slice(0,40)},[e,i,r]);S.useEffect(()=>{e&&o("")},[e]);const u=d=>{t(),d.run()};return f.jsx(Wu,{open:e,onOpenChange:d=>!d&&t(),children:f.jsxs(ed,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[f.jsx(Cl,{className:"sr-only",children:"Search and quick actions"}),f.jsxs($P,{shouldFilter:!1,loop:!0,children:[f.jsxs("div",{id:"palette-inputwrap",children:[f.jsx(lt,{name:"search"}),f.jsx(IP,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:i,onValueChange:o})]}),f.jsx(PP,{children:l.length===0?f.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):l.map(d=>f.jsxs(FP,{value:d.kind+":"+d.label,onSelect:()=>u(d),children:[f.jsx("span",{className:"picon",children:f.jsx(lt,{name:d.icon})}),f.jsx(UP,{text:d.label,hits:d.hits}),f.jsx("span",{className:"pkind",children:d.kind})]},d.kind+":"+d.label))}),f.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ⏎ select · esc close"})]})]})})}function BP(e,t){return Ft({queryKey:["heatDevices",e],queryFn:()=>qt(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const qP=["all","human","agent","share"],GP={all:"All reads",human:"Human reads",agent:"Agent reads",share:"Shared reads"},ZP={agent:{agent:1,human:0,share:0},human:{agent:0,human:1,share:0},share:{agent:0,human:0,share:1}};function vw(e){const[t,r]=S.useState("all"),{flatFiles:i,heatMap:o,devices:l,scope:u}=e,d=w=>!u||w===u||w.startsWith(u+"/"),m=u?i.filter(w=>d(w.path)):i;if(!e.loading&&!m.length)return f.jsxs("div",{className:"insights",children:[f.jsxs("h1",{className:"in-title",children:["Knowledge insights",u?f.jsxs("span",{className:"in-scope",children:[" · ",u]}):null]}),f.jsxs("div",{className:"dl-empty in-blank",children:[f.jsx("p",{children:u?`Nothing in ${u} to chart yet.`:"Nothing to chart yet."}),f.jsx("p",{children:u?`No files under ${u} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&f.jsx("a",{className:"pbtn",...Gs(e.installHref),children:"Set up a device →"})]})]});const p=l&&u?l.map(w=>{const _=Object.create(null);for(const[E,R]of Object.entries(w.folders||{}))d(E)&&(_[E]=R);return{...w,folders:_}}).filter(w=>Object.keys(w.folders).length>0):l,y=Date.now(),v=m.map(w=>{const _=o&&o[w.path]||{},E=w.time?Math.max(0,(y-new Date(w.time).getTime())/864e5):0,R=t==="all"?na(_):_[t]||0;return{path:w.path,reads:R,agent:_.agent||0,human:_.human||0,share:_.share||0,total:na(_),days:E,danger:GC(R,E)}}),b=cI(o,new Set(i.map(w=>w.path))).filter(d).map(w=>{const _=o[w];return{path:w,reads:t==="all"?na(_):_[t]||0,agent:_.agent||0,human:_.human||0,share:_.share||0,total:na(_),days:0,danger:!1,orphan:!0}}).filter(w=>w.reads>0),x=b.length>0?f.jsxs("p",{className:"in-legend in-orphan-note",children:[rp(b.length,"file")," with reads ",b.length===1?"is":"are"," no longer in the project — see Hot path."]}):null;return f.jsxs("div",{className:"insights",children:[f.jsxs("h1",{className:"in-title",children:["Knowledge insights",u?f.jsxs("span",{className:"in-scope",children:[" · ",u]}):null]}),f.jsx("p",{className:"dl-sub",children:u?`Reads over the last 30 days × freshness, for ${u} and everything in it. ${Ci}`:"Reads over the last 30 days × how long since each file changed. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ci}),f.jsx("div",{className:"in-lens",children:qP.map(w=>f.jsx("button",{className:"in-lens-btn"+(w===t?" active":""),onClick:()=>r(w),children:GP[w]},w))}),f.jsx("h3",{className:"dl-h3",children:"Map — cell size = reads, color = freshness (scale below)"}),f.jsx(YP,{pts:v,onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),x,f.jsxs("h3",{className:"dl-h3 in-h3-row",children:["Reads × freshness",f.jsx("span",{className:"in-cap",children:"dot size = agent share of reads"})]}),f.jsx(XP,{pts:v,onOpenFile:e.onOpenFile}),x,f.jsx("h3",{className:"dl-h3",children:"Hot path — top files by reads"}),f.jsx(JP,{pts:[...v,...b],lens:t,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),p&&p.length>0&&f.jsxs(f.Fragment,{children:[f.jsx("h3",{className:"dl-h3",children:"Agent coverage — which agents read which areas"}),f.jsx(WP,{devices:p})]})]})}const KP="rgb(150,156,164)";function oE(e){const t=[[76,195,138],[232,196,84],[224,93,93]],r=Math.min(1,Math.max(0,e/300))*(t.length-1),i=Math.min(t.length-2,Math.floor(r)),o=r-i,l=t[i].map((u,d)=>Math.round(u+(t[i+1][d]-u)*o));return`rgb(${l[0]},${l[1]},${l[2]})`}function yw(e,t,r,i,o){const l=e.reduce((p,y)=>p+y.value,0);if(!l||i<=0||o<=0)return[];const u=e.slice().sort((p,y)=>y.value-p.value).map(p=>({it:p,a:p.value/l*i*o})),d=(p,y)=>{const b=p.reduce((w,_)=>w+_.a,0)/y;let x=0;for(const w of p){const _=w.a/b;x=Math.max(x,_/b,b/_)}return x},m=[];for(;u.length;){const p=i>=o,y=p?o:i,v=[u.shift()];for(;u.length&&d(v.concat(u[0]),y)<=d(v,y);)v.push(u.shift());const b=v.reduce((w,_)=>w+_.a,0)/y;let x=0;for(const w of v){const _=w.a/b;p?m.push({item:w.it,x:t,y:r+x,w:b,h:_}):m.push({item:w.it,x:t+x,y:r,w:_,h:b}),x+=_}p?(t+=b,i-=b):(r+=b,o-=b)}return m}const dm=15;function bw(e,t,r){const i=Math.floor((r-8)/6),o=`${e} · ${t}`;return o.length<=i?{label:o,fit:i}:{label:e.length>i?e.slice(0,Math.max(1,i-1))+"…":e,fit:i}}const rp=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function YP({pts:e,onOpenFile:t,onOpenFolder:r,isFolder:i}){const u=dI(e.map(y=>y.days)),d=!!u&&fI(u.min,u.max),m=new Map;for(const y of e){const v=y.path.includes("/")?y.path.split("/")[0]:"/";let b=m.get(v);b||m.set(v,b={name:v,files:[],value:0,reads:0}),b.files.push(y),b.value+=y.reads+1,b.reads+=y.reads}const p=[];for(const y of yw([...m.values()],0,0,720,480)){const v=y.item,b=v.name==="/"?"":v.name,x=v.name==="/"?"(root)":v.name;if(p.push(f.jsx("rect",{x:y.x+1,y:y.y+1,width:Math.max(0,y.w-2),height:Math.max(0,y.h-2),rx:3,className:"in-tm-group","data-dir":b,children:f.jsx("title",{children:`${v.name==="/"?"(root)":v.name+"/"} — ${rp(v.reads,"read")}/30d · ${rp(v.files.length,"file")}`})},"g"+v.name)),y.w>46&&y.h>dm+10){const{label:_}=bw(x,v.reads,y.w);p.push(f.jsx("text",{x:y.x+5,y:y.y+12,className:"in-tm-glabel","data-dir":b,children:_},"gl"+v.name))}const w=yw(v.files.map(_=>({..._,name:_.path.split("/").pop(),value:_.reads+1})),y.x+2,y.y+dm,Math.max(0,y.w-4),Math.max(0,y.h-dm-2));for(const _ of w)if(p.push(f.jsx("rect",{x:_.x+.6,y:_.y+.6,width:Math.max(.4,_.w-1.2),height:Math.max(.4,_.h-1.2),rx:1.5,fill:d?KP:oE(_.item.days),className:"in-tm-cell","data-path":_.item.path,children:f.jsx("title",{children:`${_.item.path} — ${_.item.reads} read${_.item.reads===1?"":"s"}/30d · changed ${Math.round(_.item.days)}d ago`})},_.item.path)),_.w>54&&_.h>16){const{label:E,fit:R}=bw((_.item.danger?"⚠ ":"")+_.item.name,_.item.reads,_.w);R>=5&&p.push(f.jsx("text",{x:_.x+4.5,y:_.y+12.5,className:"in-tm-label","data-path":_.item.path,children:E},"l"+_.item.path))}}return f.jsxs(f.Fragment,{children:[f.jsx("svg",{viewBox:"0 0 720 480",className:"in-chart in-treemap",onClick:y=>{const v=y.target.closest("[data-path], [data-dir]");if(!v)return;const b=v.getAttribute("data-path");if(b)return t(b);const x=v.getAttribute("data-dir");x&&i(x)&&r(x)},children:p}),f.jsx(QP,{range:u,flat:d})]})}function QP({range:e,flat:t}){if(!e)return null;const r=hI(e.min,e.max);return f.jsxs("p",{className:"in-legend in-tm-legend",children:["freshness 0d",f.jsx("span",{className:"in-sw in-sw-age"+(t?" in-sw-flat":""),style:{background:`linear-gradient(to right, ${[0,60,150,300].map(oE).join(", ")})`}}),"300d+",f.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old`})]})}function XP({pts:e,onOpenFile:t}){const o={l:44,r:16,t:20,b:34},l=Math.max(Ms*2,...e.map(w=>w.days)),u=Math.max(tl*2,...e.map(w=>w.reads)),d=w=>Math.log10(w+1)/Math.log10(l+1),m=w=>Math.log10(w+1)/Math.log10(u+1),p=w=>3+4*w,y=p(1),v=w=>o.l+y+d(w)*(720-o.l-o.r-2*y),b=w=>360-o.b-y-m(w)*(360-o.t-o.b-2*y),x=gI(e.filter(w=>w.danger).map(w=>({path:w.path,reads:w.reads,cx:v(w.days),cy:b(w.reads),r:p(w.total?(w.agent||0)/w.total:0)})),{right:720-o.r,top:o.t+8,bottom:360-o.b-4});return f.jsxs("svg",{viewBox:"0 0 720 360",className:"in-chart",children:[f.jsx("rect",{x:v(Ms),y:o.t,width:720-o.r-v(Ms),height:b(tl)-o.t,className:"in-danger-zone"}),f.jsx("line",{x1:v(Ms),y1:o.t,x2:v(Ms),y2:360-o.b,className:"in-threshold"}),f.jsx("line",{x1:o.l,y1:b(tl),x2:720-o.r,y2:b(tl),className:"in-threshold"}),f.jsx("line",{x1:o.l,y1:360-o.b,x2:720-o.r,y2:360-o.b,className:"in-axis"}),f.jsx("line",{x1:o.l,y1:o.t,x2:o.l,y2:360-o.b,className:"in-axis"}),f.jsx("text",{x:(o.l+720-o.r)/2,y:352,className:"in-label",children:"days since last change →"}),f.jsx("text",{x:12,y:(o.t+360-o.b)/2,className:"in-label",transform:`rotate(-90 12 ${(o.t+360-o.b)/2})`,children:"reads / 30d →"}),f.jsx("text",{x:720-o.r-6,y:o.t+14,className:"in-quad in-quad-danger",textAnchor:"end",children:"hot + stale"}),f.jsx("text",{x:o.l+6,y:o.t+14,className:"in-quad",children:"hot + fresh"}),f.jsx("text",{x:720-o.r-6,y:360-o.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),f.jsx("text",{x:o.l+6,y:360-o.b-8,className:"in-quad",children:"cold + fresh"}),e.map(w=>{const _=w.total?(w.agent||0)/w.total:0;return f.jsx("circle",{cx:Number(v(w.days).toFixed(1)),cy:Number(b(w.reads).toFixed(1)),r:Number(p(_).toFixed(1)),className:"in-pt"+(w.danger?" danger":w.reads?"":" cold"),onClick:()=>t(w.path),children:f.jsx("title",{children:`${w.path} — ${w.reads} read${w.reads===1?"":"s"} / 30d · changed ${Math.round(w.days)}d ago`})},w.path)}),x.map(w=>f.jsx("text",{x:Number(w.x.toFixed(1)),y:Number(w.y.toFixed(1)),textAnchor:w.anchor,className:"in-pt-label",children:w.name},w.path))]})}function JP({pts:e,lens:t,onOpenFile:r,onOpenHistory:i}){const o=e.filter(d=>d.reads>0).sort((d,m)=>m.reads-d.reads||m.days-d.days).slice(0,20);if(!o.length)return f.jsx("div",{className:"dl-empty",children:"No reads in the window yet."});const l=o[0].reads,u=o.some(d=>d.share>0);return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"in-hotpath",children:o.map(d=>{const m=ZP[t]??lI(d),p=d.reads/l*100,y=()=>d.orphan?i(d.path):r(d.path);return f.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:d.orphan?`${d.reads} read${d.reads===1?"":"s"}/30d · no longer in the project — open its history`:d.danger?`${d.reads} read${d.reads===1?"":"s"}/30d · unchanged ${Math.round(d.days)}d — review this file`:d.path,onClick:y,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),y())},children:[f.jsx("span",{className:"in-hp-name"+(d.danger?" danger":""),children:d.path+(d.danger?" ⚠":"")}),d.orphan&&f.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),f.jsxs("span",{className:"in-hp-bar",children:[f.jsx("span",{className:"in-hp-agent",style:{width:(p*m.agent).toFixed(1)+"%"}}),f.jsx("span",{className:"in-hp-human",style:{width:(p*m.human).toFixed(1)+"%"}}),f.jsx("span",{className:"in-hp-share",style:{width:(p*m.share).toFixed(1)+"%"}})]}),f.jsx("span",{className:"in-hp-count",children:d.reads})]},d.path)})}),f.jsxs("p",{className:"in-legend",children:[f.jsx("span",{className:"in-sw agent"})," agent reads ",f.jsx("span",{className:"in-sw human"})," human reads",u&&f.jsxs(f.Fragment,{children:[" ",f.jsx("span",{className:"in-sw share"})," shared reads"]})]})]})}function WP({devices:e}){const t=new Map;for(const b of e)for(const[x,w]of Object.entries(b.folders||{}))t.set(x,(t.get(x)||0)+w);const r=[...t.entries()].sort((b,x)=>x[1]-b[1]).slice(0,12).map(b=>b[0]),i=e.slice(0,12),o=140,l=6,u=Math.min(76,Math.max(34,(720-o-8)/r.length)),d=26,m=720,p=l+i.length*d+58,y=Math.max(1,...i.flatMap(b=>r.map(x=>(b.folders||{})[x]||0))),v=b=>{const x=[23,25,31],w=[245,166,35],_=x.map((E,R)=>Math.round(E+(w[R]-E)*b));return`rgb(${_[0]},${_[1]},${_[2]})`};return f.jsxs("svg",{viewBox:`0 0 ${m} ${p}`,className:"in-chart in-matrix",children:[i.map((b,x)=>{let w=b.name||b.id||"";return w.length>20&&(w=w.slice(0,19)+"…"),f.jsxs("g",{children:[f.jsx("text",{x:o-8,y:l+x*d+17,textAnchor:"end",className:"in-label",children:w}),r.map((_,E)=>{const R=(b.folders||{})[_]||0;return f.jsx("rect",{x:o+E*u,y:l+x*d,width:u-4,height:d-4,rx:3,fill:v(Math.sqrt(R/y)),children:f.jsx("title",{children:`${b.name||b.id} × ${_||"(root)"}: ${R} read${R===1?"":"s"}/30d`})},_)})]},b.id||x)}),r.map((b,x)=>{const w=o+x*u+(u-4)/2,_=l+i.length*d+14;return f.jsx("text",{x:w,y:_,className:"in-label",textAnchor:"end",transform:`rotate(-28 ${w} ${_})`,children:b||"(root)"},b)})]})}function lE(e){return new Set(e.entries.map(t=>t.path)).size}function eF(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),r=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const d=r.get(t(l));if(d){d.entries.push(l),d.idx.push(u);return}r.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const i=[],o=new Set;return e.forEach((l,u)=>{const d=l.note||l.session?r.get(t(l)):void 0;if(!d||lE(d)<2){i.push({i:u});return}o.has(d)||(o.add(d),i.push({run:d,i:u}))}),i}function tF(e){const{filters:t,authors:r,onChange:i}=e,o=(y,v)=>i({...t,[y]:v||void 0}),[l,u]=S.useState(t?.q??""),d=S.useRef(!1);S.useEffect(()=>{d.current||u(t?.q??"")},[t?.q]),S.useEffect(()=>{if(!d.current)return;const y=setTimeout(()=>{d.current=!1,l!==(t?.q??"")&&o("q",l)},250);return()=>clearTimeout(y)},[l]);const m=t?.user&&!r.includes(t.user)?[t.user,...r]:r,p=Yp(t);return f.jsxs("div",{className:"hfilters",children:[f.jsxs("label",{className:"hf-search",children:[f.jsx(lt,{name:"search"}),f.jsx(fu,{type:"search",value:l,placeholder:"path contains…","aria-label":"Filter by path",onChange:y=>{d.current=!0,u(y.target.value)}})]}),f.jsxs("select",{className:"hf-user",value:t?.user??"","aria-label":"Filter by author",onChange:y=>o("user",y.target.value),children:[f.jsx("option",{value:"",children:"Anyone"}),m.map(y=>f.jsx("option",{value:y,children:y},y))]}),f.jsxs("span",{className:"hf-dates",children:[f.jsx("span",{className:"hf-lbl",children:"UTC"}),f.jsx(fu,{type:"date",className:"hf-date",value:t?.since??"","aria-label":"From date (UTC)",onChange:y=>o("since",y.target.value)}),f.jsx("span",{className:"hf-dash",children:"–"}),f.jsx(fu,{type:"date",className:"hf-date",value:t?.until??"","aria-label":"To date (UTC)",onChange:y=>o("until",y.target.value)})]}),p&&f.jsx("button",{type:"button",className:"hf-clear",onClick:()=>i({}),children:"Clear"})]})}function nF(e){const t=new Set;for(const r of e)r.user&&t.add(r.user);return[...t].sort()}function rF(e){const{apiBase:t,target:r,isFolder:i,onMeta:o,onRendered:l,restore:u,remove:d,undoRun:m,filters:p}=e,y=r?i(r)?{prefix:r+"/"}:{path:r}:{prefix:""},v=("path"in y&&y.path!==void 0?"path="+encodeURIComponent(y.path):"prefix="+encodeURIComponent(y.prefix??""))+D_(p).replace("?","&"),{data:b,error:x,fetchNextPage:w,hasNextPage:_,isFetchingNextPage:E}=vj({queryKey:["history",t,v],queryFn:({pageParam:$})=>qt(t+"history?"+v+"&n=100"+($?"&cursor="+encodeURIComponent($):"")),initialPageParam:"",getNextPageParam:$=>$.next_cursor,staleTime:15e3}),R=S.useRef(new Set);S.useEffect(()=>{x&&o("History unavailable: "+x.message)},[x,o]),S.useEffect(()=>{b&&l?.()},[b,l]);const T=b?b.pages.flatMap($=>$.entries||[]):[];for(const $ of nF(T))R.current.add($);const O=e.onFilters&&f.jsx(tF,{filters:p,authors:[...R.current].sort(),onChange:e.onFilters});if(!b)return O?f.jsx("div",{className:"history",children:O}):null;const N=$=>{for(let he=$+1;he{const he=T[$].kind==="delete"?N($):T[$].blob;return he&&he===k.get(T[$].path)?void 0:he},H=$=>k.get(T[$].path)==="";return f.jsxs("div",{className:"history",children:[O,T.length===0&&(Yp(p)?f.jsxs("div",{className:"empty",children:["No changes match these filters.",f.jsx("br",{}),f.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"})]}):f.jsx("div",{className:"empty",children:"No history yet."})),eF(T).map(($,he)=>$.run?f.jsx(aF,{run:$.run,onOpen:e.onOpen,apiBase:t,prevBlob:N,restoreSha:B,recreates:H,restore:u,remove:d,undoRun:m},"g"+he):f.jsx(vg,{entry:T[$.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:N($.i)},restore:u,restoreSha:B($.i),recreates:H($.i)},"r"+$.i)),_&&f.jsx("button",{type:"button",className:"btn hmore",onClick:()=>w(),disabled:E,children:E?"Loading…":"Load more"})]})}function aF({run:e,onOpen:t,apiBase:r,prevBlob:i,restoreSha:o,recreates:l,restore:u,remove:d,undoRun:m}){const[p,y]=S.useState(!0),v=e.entries[0],b=fd(v),x=[v.device.name||v.device.id,v.device.os].filter(Boolean).join(" · "),w=v.session,_=v.device?.id,{data:E}=Ft({queryKey:["session-reads",r,w,_],queryFn:()=>qt(r+"heat?session="+encodeURIComponent(w)+"&device="+encodeURIComponent(_)),enabled:!!w&&!!_,staleTime:3e4}),R=new Set(E?.paths??[]),T=new Set(e.entries.map($=>$.path)),O=[...R].filter($=>!T.has($)).sort(),N=e.entries.map($=>new Date($.time).getTime()),k=iF(Math.min(...N),Math.max(...N)),B=lE(e),H=!!m?.busy&&m.busy===(e.session||e.note);return f.jsxs("div",{className:"hrun"+(p?" open":""),children:[f.jsxs("div",{className:"hrun-head",children:[f.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":p,title:p?"Collapse this run":"Expand this run",onClick:()=>y(!p),children:f.jsx(lt,{name:p?"chevd":"chev"})}),f.jsx("span",{className:"hrun-note",children:f.jsx(XC,{text:e.note})}),f.jsxs("span",{className:"hrun-meta",children:[R.size>0?`read ${R.size} · changed ${B}`:`${B} file${B===1?"":"s"}`," ·"," ",b,x?" · "+x:""]}),f.jsx("span",{className:"hrun-time",children:k}),m&&f.jsxs("button",{type:"button",className:"hrun-undo",disabled:H,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[f.jsx(lt,{name:"hist"}),H?"undoing…":"undo this run"]})]}),p&&f.jsxs("div",{className:"hrun-body",children:[e.entries.map(($,he)=>f.jsx(vg,{entry:$,apiBase:r,onOpen:t,diff:{apiBase:r,prev:i(e.idx[he])},restore:u,remove:d,restoreSha:o(e.idx[he]),recreates:l(e.idx[he]),inRun:!0,read:R.has($.path)},he)),O.length>0&&f.jsxs("div",{className:"hrun-reads",children:[f.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),O.map($=>f.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>t($),children:[f.jsx("span",{className:"hkind",children:"read"}),f.jsx("span",{className:"hpath",children:$})]},$))]}),w&&f.jsx("div",{className:"hrun-foot",children:"Reads shown only for files the project still has."})]})]})}function iF(e,t){const r=new Date(e),i=new Date(t),o=u=>u.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r.toDateString()!==i.toDateString())return r.toLocaleString()+" – "+i.toLocaleString();const l=i.toLocaleDateString();return e===t?l+" "+o(i):l+" "+o(r)+" – "+o(i)}function sF(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}function oF(e){const{apiBase:t,path:r,version:i}=e,o="path="+encodeURIComponent(r),{data:l}=Ft({queryKey:["history",t,o,200],queryFn:()=>qt(t+"history?"+o+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===i),d=u?fd(u):"",m=u?.time?new Date(u.time).toLocaleString():"",p=t+"blob?sha="+i+"&name="+encodeURIComponent(r.split("/").pop()||r)+"&download=1";return f.jsxs("div",{className:"vbanner",role:"status",children:[f.jsx("span",{className:"vb-icon",children:f.jsx(lt,{name:"clock"})}),f.jsxs("div",{className:"vb-text",children:[f.jsx("b",{children:[m&&"Version from "+m,d&&"by "+d].filter(Boolean).join(" ")||"Earlier version"}),f.jsx("span",{children:"This is not the current file."})]}),f.jsxs("div",{className:"vb-actions",children:[f.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),f.jsx("a",{className:"ai-btn",download:!0,href:p,children:"Download this version"})]})]})}const lF={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function cF(e=[]){const t=e.map(i=>`${lF[i.rule]??i.rule} (line ${i.line})`);return`BearDrive found ${t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function cE(e){const{config:t,apiBase:r,route:i,hub:o,project:l}=e,u=Xp(),d=Ni(),{tree:m,flatFiles:p,dirIndex:y,loaded:v}=bI(r,!o||!!l),b=xI(r,o&&!!l&&!!t.reads?.enabled),x=o&&!!l&&!i.path&&!i.view,w=i.view==="dashboard"||x,_=BP(r,w);S.useEffect(()=>{w&&d.invalidateQueries({queryKey:["heat",r]})},[w,r,d]);const E=i.path,R=i.view?void 0:i.version,T=E||(i.view==="dashboard"||i.view==="history")&&i.viewTarget||"",O=!!E&&y.has(E),N=!!E&&v&&!O&&p.some(te=>te.path===E),k=!!E&&v&&!O&&!N,B=O&&!i.view,{data:H}=Ft({queryKey:["resolve",r,E],queryFn:()=>qt(r+"resolve?path="+encodeURIComponent(E)),enabled:k,retry:!1,staleTime:6e4}),[$,he]=S.useState(null);S.useEffect(()=>{!k||!H?.to||(he({from:E,to:H.to}),Yt(qs(H.to,l?.id),{replace:!0}))},[k,H,E,l?.id]);const[be,pe]=S.useState(()=>new Set),fe=S.useRef(!0);S.useEffect(()=>{if(!m||!fe.current)return;fe.current=!1;const te=(m.children||[]).filter(oe=>oe.dir);te.length===1&&pe(oe=>new Set(oe).add(te[0].path))},[m]),S.useEffect(()=>{!T||!v||pe(te=>{const oe=new Set(te);for(const Re of VI(T))oe.add(Re);return y.has(T)&&oe.add(T),oe})},[T,v,y]);const ue=S.useCallback(te=>{pe(oe=>{const Re=new Set(oe);return Re.has(te)?Re.delete(te):Re.add(te),Re})},[]),W=S.useRef(null),ve=S.useRef(new Map),L=S.useRef({key:"",want:0,attempts:0});S.useEffect(()=>{L.current={key:u,want:$3()==="POP"?ve.current.get(u)??0:0,attempts:0}},[u]);const Z=S.useCallback(()=>{const te=W.current,oe=L.current;!te||oe.key!==u||oe.attempts>=3||(oe.attempts++,te.scrollTo({top:oe.want,behavior:"instant"}))},[u]),ne=S.useCallback(()=>{W.current&&ve.current.set(u,W.current.scrollTop)},[u]),X=S.useCallback((te,oe)=>{Yt(qs(te,l?.id,oe)),hr()},[l?.id]),ee=S.useCallback(te=>Yt(Pn("history",l?.id,te)),[l?.id]),[D,M]=S.useState(""),[U,Q]=S.useState(null),[K,de]=S.useState(!1),[re,xe]=S.useState(!1);S.useEffect(()=>GD(()=>xe(!0)),[]);const we=S.useRef(null),Me=e.panel??null,Fe=!Me&&o&&!!l&&N&&_i(l.perm,"write"),{data:He}=T_(l?.id,o&&!!l),ct=S.useCallback(()=>{d.invalidateQueries({queryKey:["shares",l?.id]})},[d,l?.id]),Je=N?(He||[]).filter(te=>te.path===E):[],hn=!Me&&o&&!!l,mn=!Me&&N,Xt=!Me&&(N||o&&!!l&&O),yr=R?r+"blob?sha="+R+"&name="+encodeURIComponent(E)+"&download=1":r+"download?path="+encodeURIComponent(E),At=S.useCallback(async()=>{const te=oe=>fetch(r+"shares",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(oe?{path:E,confirm:!0}:{path:E})});try{let oe=await te(!1);if(oe.status===409){const{findings:at}=await oe.json();if(!await za("This file may contain credentials",cF(at),"Share anyway",!0))return;oe=await te(!0)}if(!oe.ok)throw new Error(await oe.text());const Re=await oe.json();zw("share_created");const ze=await Zs(Re.url);Q({url:Re.url,copied:ze}),ct()}catch(oe){Ge("Share failed: "+oe.message,!0)}},[r,E,ct]),[rr,br]=S.useState(""),Rt=o&&!!l&&_i(l?.perm,"write"),Vn=S.useCallback(async(te,oe,Re)=>{if(await za("Restore this version of "+te+"?","It syncs to every device as a new change. "+(Re?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){br(te+oe);try{await ea(r+"restore",{path:te,sha:oe}),d.invalidateQueries({queryKey:["history",r]}),d.invalidateQueries({queryKey:["tree",r]}),d.invalidateQueries({queryKey:["render",r,te]}),d.invalidateQueries({queryKey:["text"]}),Ge("Restored "+te+" — it syncs to every device like any other change.")}catch(ze){Ge("Restore failed: "+ze.message,!0)}finally{br("")}}},[r,d]),[zt,Dr]=S.useState(""),ar=S.useCallback(async te=>{if(await za("Remove "+te+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Dr(te);try{await ea(r+"remove",{path:te}),d.invalidateQueries({queryKey:["history",r]}),d.invalidateQueries({queryKey:["tree",r]}),d.invalidateQueries({queryKey:["render",r,te]}),d.invalidateQueries({queryKey:["text"]}),Ge("Removed "+te+" — it syncs to every device like any other change.")}catch(oe){Ge("Remove failed: "+oe.message,!0)}finally{Dr("")}}},[r,d]),[oa,ir]=S.useState(""),la=S.useCallback(async te=>{const oe=te.session||te.note,Re=te.session?{session:te.session,device:te.entries[0]?.device?.id}:{note:te.note,device:te.entries[0]?.device?.id};ir(oe);try{const ze=await ea(r+"undo-run",{...Re,preview:!0}),at=new Set(ze.changed_after);if(!ze.undone.length){Ge("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await za("Undo this run?",f.jsxs(f.Fragment,{children:[f.jsxs("div",{children:[te.note||oe," — ",ze.undone.length," file",ze.undone.length===1?"":"s"]}),f.jsx("div",{className:"undo-list",children:ze.undone.map(it=>f.jsxs("div",{className:"undo-row",children:[f.jsx("span",{className:"undo-path",children:it.path}),at.has(it.path)&&f.jsx("span",{className:"undo-after",children:"changed after this run"}),f.jsx("span",{className:"undo-what",children:it.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},it.path))}),at.size>0&&f.jsxs("div",{className:"undo-warn",children:[at.size," file",at.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",at.size===1?"that change":"those changes"," too."]}),ze.skipped.length>0&&f.jsxs("div",{children:[ze.skipped.length," already hold",ze.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),ze.refused.length>0&&f.jsxs("div",{children:[ze.refused.length," path",ze.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",ze.refused.join(", "),"."]})]}),"Undo run",!0))return;const Ae=await ea(r+"undo-run",Re);d.invalidateQueries({queryKey:["history",r]}),d.invalidateQueries({queryKey:["tree",r]}),d.invalidateQueries({queryKey:["render",r]}),d.invalidateQueries({queryKey:["text"]});const ut=Ae.skipped.length?`, skipped ${Ae.skipped.length} (already current)`:"";Ge(`Undid ${Ae.undone.length} file${Ae.undone.length===1?"":"s"}${ut}.`)}catch(ze){Ge("Undo failed: "+ze.message,!0)}finally{ir("")}},[r,d]),Jt=S.useCallback(()=>{if(!E)return ee("");ee(O?E+"/":E)},[E,O,ee]);S.useEffect(()=>{const te=oe=>{(oe.metaKey||oe.ctrlKey)&&oe.key.toLowerCase()==="k"&&(oe.preventDefault(),xe(Re=>!Re))};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[]);const A=S.useCallback(()=>{const te=[],oe=(Re,ze,at,_t)=>te.push({icon:Re,label:ze,kind:at,run:_t});if(o&&l){const Re=l.id,ze=at=>()=>{e.onClosePanel?.(),Yt(at)};oe("folder","Go to project root","action",ze("/"+Re)),oe("dashboard","Dashboard","action",ze(Pn("dashboard",Re))),oe("terminal","Installation","action",ze(Pn("install",Re))),oe("gear","Settings","action",ze(Pn("settings",Re)))}if(o&&l&&E&&(N&&oe("share","Share: "+E,"action",At),oe("hist","History: "+E,"action",Jt),N&&oe("download","Download: "+E,"action",()=>we.current?.click())),o&&l&&oe("hist","History: whole project","action",()=>ee("")),o)for(const Re of e.projects||[])(!l||Re.id!==l.id)&&oe("folder","Switch to project: "+Re.name,"project",()=>Yt("/"+Re.id));t.auth?.enabled&&oe("power","Sign out","action",()=>window.location.href="/auth/logout");for(const Re of y.keys())oe("folder",Re,"folder",()=>X(Re));for(const Re of p)oe("doc",Re.path,"file",()=>X(Re.path));return te},[o,l,E,N,t.auth?.enabled,y,p,e.projects,e.onClosePanel,At,Jt,ee,X]);S.useEffect(()=>{if(!K)return;const te=()=>de(!1);return document.addEventListener("click",te),()=>document.removeEventListener("click",te)},[K]);const P=S.useCallback(te=>y.has(te),[y]);let F="app",ce,se;Me?se=Me.body:i.view==="dashboard"?se=f.jsx(vw,{flatFiles:p,heatMap:b,devices:_,scope:i.viewTarget||"",loading:!v,installHref:l?Pn("install",l.id):void 0,onOpenFile:X,onOpenFolder:X,onOpenHistory:ee,isFolder:P}):i.view==="history"?se=f.jsx(rF,{apiBase:r,target:i.viewTarget||"",isFolder:P,onOpen:X,onMeta:M,onRendered:Z,restore:Rt?{onRestore:Vn,busy:rr}:void 0,remove:Rt?{onRemove:ar,busy:zt}:void 0,undoRun:Rt?{onUndoRun:la,busy:oa}:void 0,filters:i.filters,onFilters:te=>Yt(Pn("history",l?.id,i.viewTarget||"",te))}):E?v?k?se=f.jsxs("div",{className:"notfound",children:[f.jsx("h1",{children:"Couldn't find that"}),f.jsxs("p",{children:[f.jsx("code",{children:E})," isn't in this project right now."]}),f.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),f.jsx("button",{className:"pbtn",onClick:()=>d.invalidateQueries({queryKey:["tree",r]}),children:"Check again"})]}):O?se=f.jsx(WI,{node:y.get(E),heatMap:b,hub:o&&!!l,apiBase:r,onOpen:X,onFullHistory:ee,onRendered:Z}):(F=AC.test(E)||MC.test(E)?"wide":"read",ce="markdown",se=f.jsxs(f.Fragment,{children:[R&&f.jsx(oF,{apiBase:r,path:E,version:R,onViewCurrent:()=>X(E)}),f.jsx(nP,{apiBase:r,path:E,version:R,heatMap:b,flatFiles:p,projectId:l?.id,onOpenFile:X,onMeta:M,onRendered:Z})]})):se=f.jsx("div",{className:"empty",children:"Loading…"}):x?se=f.jsxs(f.Fragment,{children:[f.jsx(BC,{project:l,existing:i.connect==="existing"}),f.jsx("div",{className:"home-insights",children:f.jsx(vw,{flatFiles:p,heatMap:b,devices:_,loading:!v,onOpenFile:X,onOpenFolder:X,onOpenHistory:ee,isFolder:P})})]}):se=f.jsx("div",{className:"empty",children:"Select a file to read it."}),$&&$.to===E&&(se=f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"vbanner",role:"status",children:[f.jsx("span",{className:"vb-icon",children:f.jsx(lt,{name:"link"})}),f.jsxs("div",{className:"vb-text",children:[f.jsxs("b",{children:["Moved from ",$.from]}),f.jsx("span",{children:"The URL has been updated."})]})]}),se]}));const ye=Me?Me.crumb:E?f.jsx(UI,{path:E,onOpenFolder:X}):i.view==="dashboard"?"Dashboard — "+(i.viewTarget||l?.name||""):i.view==="history"?"History — "+sF(i.viewTarget||"",P):x?l.name:null,Se=f.jsx(hl,{crumb:ye,meta:D,actions:f.jsxs(f.Fragment,{children:[Fe&&f.jsx(xt,{id:"share-btn",variant:"toolbar",className:"icon-only",title:"Share","aria-label":"Share",onClick:At,children:f.jsx(lt,{name:"share"})}),hn&&!E&&!i.view&&f.jsxs(xt,{id:"history-btn",variant:"toolbar",onClick:Jt,children:[f.jsx(lt,{name:"hist"})," ",f.jsx("span",{className:"lbl",children:"History"})]}),mn&&f.jsx("a",{id:"download",hidden:!0,download:!0,href:yr,ref:we,children:"Download"}),Xt&&f.jsx(xt,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:te=>{te.stopPropagation(),de(!K)},children:f.jsx(lt,{name:"dots"})}),K&&f.jsxs("div",{id:"more-menu",role:"menu",children:[hn&&f.jsx("button",{className:"more-item",onClick:Jt,children:"History"}),mn&&f.jsx("button",{className:"more-item",onClick:()=>we.current?.click(),children:"Download"}),o&&!!l&&f.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),Yt(Pn("dashboard",l?.id,E))},children:"Dashboard"})]})]})});return f.jsxs(f.Fragment,{children:[f.jsx(fl,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,tree:f.jsx(FI,{root:m,expanded:be,onToggle:ue,currentPath:T,listingShowing:B,onOpen:X}),topbar:Se,contentRef:W,onContentScroll:ne,children:f.jsxs(_u,{width:F,className:ce,children:[!Me&&N&&f.jsx(fP,{shares:Je,canRevoke:!!l&&_i(l.perm,"write"),onChanged:ct}),se]})}),U&&f.jsx(dP,{url:U.url,copied:U.copied,onClose:()=>{Q(null),ct()}}),f.jsx(HP,{open:re,onClose:()=>xe(!1),candidates:A})]})}function uF({config:e}){const t=Xp(),r=A_(),[i,o]=S.useState(null),[l,u]=S.useState(null);S.useEffect(()=>u(null),[t]);const d=S.useMemo(()=>{const ve=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return ve?ve[1]:null},[t]),{data:m}=A3(!d),{data:p}=M3(!d),y=!!e.auth.admin,{data:v}=O_(y),b=S.useMemo(()=>k_(t,"hub"),[t]),[x,w]=S.useState(!1),_=e.upload.enabled,E=async(ve,L)=>{const Z=L===qC;try{const ne=await ea("/api/projects",{name:ve,template:Z?"":L});w(!1),await r(),Yt("/"+ne.project.id+(Z?"?connect=existing":"")),Ge(`Created “${ne.project.name}”.`)}catch(ne){Ge("Could not create the project: "+ne.message,!0)}},R=x?f.jsx(sI,{templates:e.templates??[],onCreate:E,onClose:()=>w(!1)}):null,T=S.useMemo(()=>m&&(m.find(ve=>ve.id===b.project)||i&&m.find(ve=>ve.org===i)||m.find(ve=>ve.id===O$())||m[0])||null,[m,b.project,i]);if(S.useEffect(()=>{document.title=T?T.name+" — BearDrive":e.brand||"BearDrive",T&&A$(T.id)},[T,e]),d)return f.jsx(dF,{token:d,onDone:async ve=>{o(ve),await r(),Yt("/",{replace:!0})}});const O=e.brand||"BearDrive",N=T&&p?.find(ve=>ve.id===T.org)||null,k=f.jsx(Ju,{name:O,onHome:()=>Yt("/"),search:!!T,beta:O==="BearDrive"}),B=e.me?f.jsx(X$,{me:e.me,org:N,orgActive:!!b.org,billing:e.billing,admin:y?{pending:v?.length||0,onClick:()=>{u({kind:"hub"}),hr()}}:void 0}):void 0;if(!m||!p)return f.jsx(fl,{vault:k,topbar:f.jsx(hl,{}),children:f.jsx(_u,{children:f.jsx("div",{className:"empty",children:"Loading…"})})});if(!T)return f.jsxs(fl,{vault:k,projectsNav:f.jsx(sw,{projects:m,onNew:()=>w(!0)}),orgBar:B,topbar:f.jsx(hl,{}),children:[f.jsx(_u,{children:f.jsx(iI,{onNew:()=>w(!0),canCreate:_})}),R]});const H=l?.kind==="hub"?{crumb:"Signup & access",body:f.jsx(V$,{})}:null,$=b.org?p.find(ve=>ve.id===b.org):null,be=b.org&&!$?{crumb:"Organization",body:f.jsxs("div",{className:"empty",children:[f.jsx("h3",{children:"Organization not found"}),f.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),f.jsx("p",{children:f.jsxs("a",{...Gs("/"+T.id),children:["Back to ",T.name]})})]})}:$?{crumb:"Organization",body:f.jsx(I$,{org:$,projects:m,myEmail:e.me?.email||""})}:null,pe=!!b.project&&!m.some(ve=>ve.id===b.project),fe=pe?{crumb:"Project",body:f.jsxs("div",{className:"empty",children:[f.jsx("h3",{children:"Project not found"}),f.jsx("p",{children:"This project doesn't exist, or you're no longer a member."}),f.jsx("p",{children:f.jsxs("a",{...Gs("/"+T.id),children:["Back to ",T.name]})})]})}:null,ue=b.billing?{crumb:"Billing",body:e.billing?f.jsx(J$,{url:e.billing.url}):f.jsxs("div",{className:"empty",children:[f.jsx("h3",{children:"No billing on this hub"}),f.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,W=b.view==="settings"?{crumb:"Project settings",body:f.jsx(tI,{project:T,org:N,onDeleted:async()=>{await r(),Yt("/")}})}:b.view==="install"?{crumb:"Installation",body:f.jsx(BC,{project:T,existing:b.connect==="existing"})}:null;if(!pe){if(!b.org&&!b.billing&&b.project!==T.id)return f.jsx(Jo,{to:"/"+T.id});if(b.legacyView&&b.view)return f.jsx(Jo,{to:Pn(b.view,T.id,b.viewTarget,b.filters)});if(b.queryTarget&&b.view)return f.jsx(Jo,{to:Pn(b.view,T.id,b.viewTarget,b.filters)});if(b.trailingSlash&&b.path)return f.jsx(Jo,{to:qs(b.path,T.id,b.version)})}return f.jsxs(f.Fragment,{children:[f.jsx(cE,{config:e,apiBase:"/api/p/"+T.id+"/",route:b,hub:!0,project:T,projects:m,sidebar:{vault:k,projectsNav:f.jsx(sw,{projects:m,currentId:T.id,onNew:()=>w(!0),menu:{active:l?null:b.view==="dashboard"&&!b.viewTarget?"dashboard":b.view==="install"?"install":b.view==="history"&&!b.viewTarget?"history":b.view==="settings"?"settings":null,onDashboard:()=>{u(null),Yt(Pn("dashboard",T.id)),hr()},onInstall:()=>{u(null),Yt(Pn("install",T.id)),hr()},onHistory:()=>{u(null),Yt(Pn("history",T.id)),hr()},onSettings:()=>{u(null),Yt(Pn("settings",T.id)),hr()}}}),orgBar:B},panel:H||be||fe||ue||W,onClosePanel:()=>u(null)},T.id),R]})}function dF({token:e,onDone:t}){return S.useEffect(()=>{let r=!1;return ea("/api/invites/"+e).then(i=>{r||(Ge(`Welcome — you joined the “${i.org.name}” team. Opening its projects…`),t(i.org.id))}).catch(i=>{r||String(i.message).includes("signing in")||(Ge("Could not accept the invite: "+i.message,!0),t(null))}),()=>{r=!0}},[e]),f.jsx(fl,{vault:f.jsx(Ju,{name:"BearDrive",beta:!0}),topbar:f.jsx(hl,{}),children:f.jsx(_u,{children:f.jsx("div",{className:"empty",children:"Joining…"})})})}function fF({config:e}){const t=Xp(),r=e.volume||"BearDrive";S.useEffect(()=>{document.title=e.brand||r},[e,r]);const i=S.useMemo(()=>k_(t,"volume"),[t]);return i.trailingSlash&&i.path?f.jsx(Jo,{to:qs(i.path)}):f.jsx(cE,{config:e,apiBase:"/api/",route:i,hub:!1,sidebar:{vault:f.jsx(Ju,{name:r,showSignout:e.auth.enabled,search:!0})}})}function hF(){const{data:e}=Sj();return f.jsxs(UD,{delayDuration:150,children:[e?e.mode==="hub"?f.jsx(uF,{config:e}):f.jsx(fF,{config:e}):f.jsx(fl,{vault:f.jsx(Ju,{name:"…",showSignout:!1}),topbar:f.jsx(hl,{}),children:f.jsx("div",{className:"empty",children:"Loading…"})}),f.jsx(S3,{}),f.jsx(j3,{})]})}class mF extends S.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("BearDrive: unhandled render error",t,r.componentStack)}render(){return this.state.error?f.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[f.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),f.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),f.jsx("p",{className:"mb-4",children:f.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),f.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const pF=new ij({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}});N2.createRoot(document.getElementById("root")).render(f.jsx(S.StrictMode,{children:f.jsx(mF,{children:f.jsx(sj,{client:pF,children:f.jsx(hF,{})})})})); +`)continue;l+=y}}return u||((l!==""||o.length)&&m(),!i.length)||i[0].length<2?null:{rows:i,truncated:d}}function nP(e){const{apiBase:t,path:r,version:i,onMeta:o}=e,l=i?t+"blob?sha="+i+"&name="+encodeURIComponent(r):t+"file?path="+encodeURIComponent(r);return S.useEffect(()=>()=>o(""),[r,o]),C$.test(r)?f.jsx(iP,{...e}):AC.test(r)?f.jsx("iframe",{className:"htmlview",sandbox:"allow-scripts",src:l,title:r,onLoad:e.onRendered}):MC.test(r)?f.jsx("iframe",{className:"pdfview",src:l,title:r,onLoad:e.onRendered}):E$.test(r)?f.jsx(lP,{src:l,alt:r,version:i,onRendered:e.onRendered}):R$.test(r)?f.jsx(fw,{...e,fileURL:l,delim:/\.tsv$/i.test(r)?" ":","}):j$.test(r)?f.jsx(fw,{...e,fileURL:l}):f.jsx(rP,{...e,fileURL:l})}function rP(e){const{apiBase:t,path:r,version:i,fileURL:o,onRendered:l}=e,{data:u,error:d}=QC(o,["text",o],!0,!!i);return S.useEffect(()=>{u&&l?.()},[u,l]),d?f.jsx(hd,{version:i,err:d}):u?u.kind==="text"?f.jsx("pre",{className:"plain",children:u.text},r):f.jsx(aP,{apiBase:t,path:r,version:i,fileURL:o,children:u.kind==="too-large"?`Too large to preview (${gg(u.size)}).`:"No preview for this file type."}):null}function aP(e){const{apiBase:t,path:r,version:i,fileURL:o}=e;return f.jsxs("div",{className:"filecard",children:[f.jsx("div",{className:"name",children:r.split("/").pop()}),f.jsx("p",{children:e.children}),f.jsx("a",{className:"btn",download:!0,href:i?o+"&download=1":t+"download?path="+encodeURIComponent(r),children:"Download"})]})}function iP(e){const{apiBase:t,path:r,version:i,heatMap:o,flatFiles:l,projectId:u,onOpenFile:d,onMeta:m,onRendered:p}=e,{data:y,error:v}=Ft({queryKey:["render",t,r,i||""],queryFn:()=>qt(t+"render?path="+encodeURIComponent(r)+(i?"&sha="+i:"")),retry:i?!1:void 0}),b=S.useMemo(()=>y?oP(y.html,r,t,l,u):"",[y,r,t,l,u]),[x,w]=S.useState(null);return S.useEffect(()=>{if(w(null),!w2(b))return;let _=!1;return S2(b).then(E=>{_||w(E)}),()=>{_=!0}},[b]),S.useEffect(()=>{if(!y)return;const _=[],E=i?null:o&&o[y.path],R=ZC(E||null,y.time);(y.user_name||y.user||y.author)&&_.push(fd(y)+(y.device?" on "+y.device:"")),y.time&&_.push(new Date(y.time).toLocaleString());const T=E&&na(E)?el(E)+" / 30d":"",O=R?f.jsxs("span",{className:"meta-stale",title:R,children:[f.jsx("span",{"aria-hidden":"true",children:"⚠ "}),R]}):null;m(T?f.jsxs(f.Fragment,{children:[O,O?" · ":"",_.length?_.join(" · ")+" · ":"",f.jsxs("span",{title:Ci,children:[T,f.jsxs("span",{className:"sr-only",children:[" — ",Ci]})]})]}):O?f.jsxs(f.Fragment,{children:[O,_.length?" · "+_.join(" · "):""]}):_.join(" · ")),p?.()},[y,i,o,m,p]),v?f.jsx(hd,{version:i,err:v}):y?f.jsx("div",{dangerouslySetInnerHTML:{__html:x??b},onClick:_=>sP(_,r,d)}):null}function sP(e,t,r){const i=e.target.closest("a");if(!i||!e.currentTarget.contains(i)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;const o=i.getAttribute("href")||"",l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=i.getAttribute("data-wiki");u!==null?(e.preventDefault(),r(u)):/^([a-z]+:|\/|#)/i.test(o)||(e.preventDefault(),r(NC(l,decodeURIComponent(o))))}function oP(e,t,r,i,o){const l=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",u=m=>r+"file?path="+encodeURIComponent(m),d=new DOMParser().parseFromString(e,"text/html");for(const m of d.querySelectorAll("img")){const p=m.getAttribute("src")||"";/^\s*data:image\/svg/i.test(p)?m.removeAttribute("src"):/^([a-z]+:|\/)/i.test(p)||m.setAttribute("src",u(NC(l,p)))}for(const m of d.querySelectorAll("a")){const p=m.getAttribute("href")||"";if(p.startsWith("wiki:")){const y=T$(decodeURIComponent(p.slice(5)),i);y?(m.setAttribute("href",qs(y.path,o)),m.setAttribute("data-wiki",y.path)):(m.removeAttribute("href"),m.classList.add("wiki-missing"),m.setAttribute("title","No file matches this wikilink"));continue}/^\s*data:/i.test(p)?m.removeAttribute("href"):/^https?:/i.test(p)&&(m.setAttribute("target","_blank"),m.setAttribute("rel","noopener"))}return d.body.innerHTML}function lP(e){const[t,r]=S.useState(!1);return t?f.jsx(hd,{version:e.version,err:new Error("could not be loaded")}):f.jsx("img",{src:e.src,alt:e.alt,onLoad:e.onRendered,onError:()=>r(!0)})}function hd({version:e,err:t}){return f.jsx("div",{className:"empty",children:e?"That version isn't available.":"Could not load file: "+t.message})}function fw(e){const{path:t,version:r,fileURL:i,delim:o,onRendered:l}=e,{data:u,error:d}=Ft({queryKey:["text",i],queryFn:async()=>{const p=await fetch(i);if(!p.ok)throw new Error(await p.text());return p.text()},retry:r?!1:void 0});S.useEffect(()=>{u!=null&&l?.()},[u,l]);const m=S.useMemo(()=>o&&u!=null?tP(u,o,JC):null,[u,o]);return d?f.jsx(hd,{version:r,err:d}):u==null?null:m?f.jsx(cP,{csv:m},t):f.jsx("pre",{className:"plain",children:u},t)}function cP({csv:e}){const[t,...r]=e.rows,i=e.rows.reduce((l,u)=>Math.max(l,u.length),0),o=Array.from({length:i},(l,u)=>u);return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"csvbox",children:f.jsxs("table",{className:"csvview",children:[f.jsx("thead",{children:f.jsx("tr",{children:o.map(l=>f.jsx("th",{children:t[l]??""},l))})}),f.jsx("tbody",{children:r.map((l,u)=>f.jsx("tr",{children:o.map(d=>f.jsx("td",{children:l[d]??""},d))},u))})]})}),e.truncated>0&&f.jsxs("p",{className:"csvnote",children:["showing ",e.rows.length.toLocaleString()," of"," ",(e.rows.length+e.truncated).toLocaleString()," rows — Download for the rest"]})]})}const uP=[{value:"",label:"Never"},{value:"24h",label:"In 24 hours"},{value:"168h",label:"In 7 days"},{value:"720h",label:"In 30 days"}];function dP({url:e,copied:t,onClose:r}){const i=e.split("/s/")[1],[o,l]=S.useState(""),[u,d]=S.useState(),[m,p]=S.useState(!1),y=S.useRef(null);async function v(b){const x=o;l(b),p(!0);try{const w=await Wn("PATCH","/api/shares/"+i,{expires_in:b});d(w.expires)}catch(w){Ge(w.message,!0),l(x)}finally{p(!1)}}return f.jsx(Wu,{open:!0,onOpenChange:b=>!b&&r(),children:f.jsxs(ed,{className:"modal",showCloseButton:!1,onOpenAutoFocus:b=>{b.preventDefault(),y.current?.focus()},children:[f.jsx(Cl,{asChild:!0,children:f.jsx("h3",{children:"Public link"})}),f.jsxs("p",{children:[f.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until it expires or you revoke it."]}),f.jsx("div",{className:"modal-url",children:e}),f.jsxs("div",{className:"modal-expiry",children:[f.jsx("label",{htmlFor:"share-expiry",children:"Expires"}),f.jsx("select",{id:"share-expiry",value:o,disabled:m,onChange:b=>v(b.target.value),children:uP.map(b=>f.jsx("option",{value:b.value,children:b.label},b.value))}),f.jsx("span",{className:"modal-expiry-note",children:zC(u)})]}),f.jsxs("div",{className:"modal-actions",children:[f.jsx(xt,{ref:y,variant:"primary",onClick:()=>Zs(e).then(b=>Ge(b?"Copied.":"Select and copy the link above.")),children:t?"Copied ✓":"Copy link"}),f.jsx(xt,{variant:"subtle",onClick:()=>window.open(e,"_blank"),children:"Open"}),f.jsx(xt,{variant:"subtle",onClick:r,children:"Done"})]})]})})}function fP({shares:e,canRevoke:t,onChanged:r}){return e.length===0?null:f.jsxs("div",{className:"share-banner",role:"status",children:[f.jsxs("div",{className:"sb-head",children:[f.jsx(lt,{name:"share"}),f.jsx("b",{children:"Publicly shared"}),f.jsxs("span",{className:"sb-count",children:[e.length," active link",e.length>1?"s":""]})]}),f.jsxs("p",{className:"sb-note",children:[f.jsx("b",{children:"Anyone with this link can view this file"})," — no account needed. It always shows the latest version until you revoke it.",e.some(i=>i.opens!==void 0)&&f.jsxs(f.Fragment,{children:[" ",$C]})]}),e.map(i=>f.jsxs("div",{className:"sb-link",children:[f.jsx("span",{className:"sb-url mono",title:i.url,children:i.url}),f.jsx("span",{className:"sb-meta",children:LC(i,!1)}),f.jsxs("span",{className:"sb-actions",children:[f.jsx(xt,{variant:"subtle",onClick:()=>Zs(i.url).then(o=>Ge(o?"Copied.":"Select and copy the link.")),children:"Copy link"}),f.jsx(xt,{variant:"subtle",onClick:()=>window.open(i.url,"_blank"),children:"Open"}),t&&f.jsx("button",{className:"ai-del","aria-label":`Revoke the share of ${i.path}`,onClick:()=>PC(i,r),children:"Revoke"})]})]},i.token))]})}var hw=1,hP=.9,mP=.8,pP=.17,lm=.1,cm=.999,gP=.9999,vP=.99,yP=/[\\\/_+.#"@\[\(\{&]/,bP=/[\\\/_+.#"@\[\(\{&]/g,xP=/[\s-]/,WC=/[\s-]/g;function tp(e,t,r,i,o,l,u){if(l===t.length)return o===e.length?hw:vP;var d=`${o},${l}`;if(u[d]!==void 0)return u[d];for(var m=i.charAt(l),p=r.indexOf(m,o),y=0,v,b,x,w;p>=0;)v=tp(e,t,r,i,p+1,l+1,u),v>y&&(p===o?v*=hw:yP.test(e.charAt(p-1))?(v*=mP,x=e.slice(o,p-1).match(bP),x&&o>0&&(v*=Math.pow(cm,x.length))):xP.test(e.charAt(p-1))?(v*=hP,w=e.slice(o,p-1).match(WC),w&&o>0&&(v*=Math.pow(cm,w.length))):(v*=pP,o>0&&(v*=Math.pow(cm,p-o))),e.charAt(p)!==t.charAt(l)&&(v*=gP)),(vv&&(v=b*lm)),v>y&&(y=v),p=r.indexOf(m,p+1);return u[d]=y,y}function mw(e){return e.toLowerCase().replace(WC," ")}function wP(e,t,r){return e=r&&r.length>0?`${e+" "+r.join(" ")}`:e,tp(e,t,mw(e),mw(t),0,0,{})}var Yo='[cmdk-group=""]',um='[cmdk-group-items=""]',SP='[cmdk-group-heading=""]',eE='[cmdk-item=""]',pw=`${eE}:not([aria-disabled="true"])`,np="cmdk-item-select",Ns="data-value",_P=(e,t,r)=>wP(e,t,r),tE=S.createContext(void 0),Tl=()=>S.useContext(tE),nE=S.createContext(void 0),yg=()=>S.useContext(nE),rE=S.createContext(void 0),aE=S.forwardRef((e,t)=>{let r=Ds(()=>{var M,U;return{search:"",value:(U=(M=e.value)!=null?M:e.defaultValue)!=null?U:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),i=Ds(()=>new Set),o=Ds(()=>new Map),l=Ds(()=>new Map),u=Ds(()=>new Set),d=iE(e),{label:m,children:p,value:y,onValueChange:v,filter:b,shouldFilter:x,loop:w,disablePointerSelection:_=!1,vimBindings:E=!0,...R}=e,T=fn(),O=fn(),N=fn(),k=S.useRef(null),B=kP();Mi(()=>{if(y!==void 0){let M=y.trim();r.current.value=M,H.emit()}},[y]),Mi(()=>{B(6,ue)},[]);let H=S.useMemo(()=>({subscribe:M=>(u.current.add(M),()=>u.current.delete(M)),snapshot:()=>r.current,setState:(M,U,Q)=>{var K,de,re,xe;if(!Object.is(r.current[M],U)){if(r.current[M]=U,M==="search")fe(),be(),B(1,pe);else if(M==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let we=document.getElementById(N);we?we.focus():(K=document.getElementById(T))==null||K.focus()}if(B(7,()=>{var we;r.current.selectedItemId=(we=W())==null?void 0:we.id,H.emit()}),Q||B(5,ue),((de=d.current)==null?void 0:de.value)!==void 0){let we=U??"";(xe=(re=d.current).onValueChange)==null||xe.call(re,we);return}}H.emit()}},emit:()=>{u.current.forEach(M=>M())}}),[]),$=S.useMemo(()=>({value:(M,U,Q)=>{var K;U!==((K=l.current.get(M))==null?void 0:K.value)&&(l.current.set(M,{value:U,keywords:Q}),r.current.filtered.items.set(M,he(U,Q)),B(2,()=>{be(),H.emit()}))},item:(M,U)=>(i.current.add(M),U&&(o.current.has(U)?o.current.get(U).add(M):o.current.set(U,new Set([M]))),B(3,()=>{fe(),be(),r.current.value||pe(),H.emit()}),()=>{l.current.delete(M),i.current.delete(M),r.current.filtered.items.delete(M);let Q=W();B(4,()=>{fe(),Q?.getAttribute("id")===M&&pe(),H.emit()})}),group:M=>(o.current.has(M)||o.current.set(M,new Set),()=>{l.current.delete(M),o.current.delete(M)}),filter:()=>d.current.shouldFilter,label:m||e["aria-label"],getDisablePointerSelection:()=>d.current.disablePointerSelection,listId:T,inputId:N,labelId:O,listInnerRef:k}),[]);function he(M,U){var Q,K;let de=(K=(Q=d.current)==null?void 0:Q.filter)!=null?K:_P;return M?de(M,r.current.search,U):0}function be(){if(!r.current.search||d.current.shouldFilter===!1)return;let M=r.current.filtered.items,U=[];r.current.filtered.groups.forEach(K=>{let de=o.current.get(K),re=0;de.forEach(xe=>{let we=M.get(xe);re=Math.max(we,re)}),U.push([K,re])});let Q=k.current;ve().sort((K,de)=>{var re,xe;let we=K.getAttribute("id"),Me=de.getAttribute("id");return((re=M.get(Me))!=null?re:0)-((xe=M.get(we))!=null?xe:0)}).forEach(K=>{let de=K.closest(um);de?de.appendChild(K.parentElement===de?K:K.closest(`${um} > *`)):Q.appendChild(K.parentElement===Q?K:K.closest(`${um} > *`))}),U.sort((K,de)=>de[1]-K[1]).forEach(K=>{var de;let re=(de=k.current)==null?void 0:de.querySelector(`${Yo}[${Ns}="${encodeURIComponent(K[0])}"]`);re?.parentElement.appendChild(re)})}function pe(){let M=ve().find(Q=>Q.getAttribute("aria-disabled")!=="true"),U=M?.getAttribute(Ns);H.setState("value",U||void 0)}function fe(){var M,U,Q,K;if(!r.current.search||d.current.shouldFilter===!1){r.current.filtered.count=i.current.size;return}r.current.filtered.groups=new Set;let de=0;for(let re of i.current){let xe=(U=(M=l.current.get(re))==null?void 0:M.value)!=null?U:"",we=(K=(Q=l.current.get(re))==null?void 0:Q.keywords)!=null?K:[],Me=he(xe,we);r.current.filtered.items.set(re,Me),Me>0&&de++}for(let[re,xe]of o.current)for(let we of xe)if(r.current.filtered.items.get(we)>0){r.current.filtered.groups.add(re);break}r.current.filtered.count=de}function ue(){var M,U,Q;let K=W();K&&(((M=K.parentElement)==null?void 0:M.firstChild)===K&&((Q=(U=K.closest(Yo))==null?void 0:U.querySelector(SP))==null||Q.scrollIntoView({block:"nearest"})),K.scrollIntoView({block:"nearest"}))}function W(){var M;return(M=k.current)==null?void 0:M.querySelector(`${eE}[aria-selected="true"]`)}function ve(){var M;return Array.from(((M=k.current)==null?void 0:M.querySelectorAll(pw))||[])}function L(M){let U=ve()[M];U&&H.setState("value",U.getAttribute(Ns))}function Z(M){var U;let Q=W(),K=ve(),de=K.findIndex(xe=>xe===Q),re=K[de+M];(U=d.current)!=null&&U.loop&&(re=de+M<0?K[K.length-1]:de+M===K.length?K[0]:K[de+M]),re&&H.setState("value",re.getAttribute(Ns))}function ne(M){let U=W(),Q=U?.closest(Yo),K;for(;Q&&!K;)Q=M>0?NP(Q,Yo):DP(Q,Yo),K=Q?.querySelector(pw);K?H.setState("value",K.getAttribute(Ns)):Z(M)}let X=()=>L(ve().length-1),ee=M=>{M.preventDefault(),M.metaKey?X():M.altKey?ne(1):Z(1)},D=M=>{M.preventDefault(),M.metaKey?L(0):M.altKey?ne(-1):Z(-1)};return S.createElement(Pe.div,{ref:t,tabIndex:-1,...R,"cmdk-root":"",onKeyDown:M=>{var U;(U=R.onKeyDown)==null||U.call(R,M);let Q=M.nativeEvent.isComposing||M.keyCode===229;if(!(M.defaultPrevented||Q))switch(M.key){case"n":case"j":{E&&M.ctrlKey&&ee(M);break}case"ArrowDown":{ee(M);break}case"p":case"k":{E&&M.ctrlKey&&D(M);break}case"ArrowUp":{D(M);break}case"Home":{M.preventDefault(),L(0);break}case"End":{M.preventDefault(),X();break}case"Enter":{M.preventDefault();let K=W();if(K){let de=new Event(np);K.dispatchEvent(de)}}}}},S.createElement("label",{"cmdk-label":"",htmlFor:$.inputId,id:$.labelId,style:LP},m),pd(e,M=>S.createElement(nE.Provider,{value:H},S.createElement(tE.Provider,{value:$},M))))}),CP=S.forwardRef((e,t)=>{var r,i;let o=fn(),l=S.useRef(null),u=S.useContext(rE),d=Tl(),m=iE(e),p=(i=(r=m.current)==null?void 0:r.forceMount)!=null?i:u?.forceMount;Mi(()=>{if(!p)return d.item(o,u?.id)},[p]);let y=sE(o,l,[e.value,e.children,l],e.keywords),v=yg(),b=Za(B=>B.value&&B.value===y.current),x=Za(B=>p||d.filter()===!1?!0:B.search?B.filtered.items.get(o)>0:!0);S.useEffect(()=>{let B=l.current;if(!(!B||e.disabled))return B.addEventListener(np,w),()=>B.removeEventListener(np,w)},[x,e.onSelect,e.disabled]);function w(){var B,H;_(),(H=(B=m.current).onSelect)==null||H.call(B,y.current)}function _(){v.setState("value",y.current,!0)}if(!x)return null;let{disabled:E,value:R,onSelect:T,forceMount:O,keywords:N,...k}=e;return S.createElement(Pe.div,{ref:Vs(l,t),...k,id:o,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!b,"data-disabled":!!E,"data-selected":!!b,onPointerMove:E||d.getDisablePointerSelection()?void 0:_,onClick:E?void 0:w},e.children)}),EP=S.forwardRef((e,t)=>{let{heading:r,children:i,forceMount:o,...l}=e,u=fn(),d=S.useRef(null),m=S.useRef(null),p=fn(),y=Tl(),v=Za(x=>o||y.filter()===!1?!0:x.search?x.filtered.groups.has(u):!0);Mi(()=>y.group(u),[]),sE(u,d,[e.value,e.heading,m]);let b=S.useMemo(()=>({id:u,forceMount:o}),[o]);return S.createElement(Pe.div,{ref:Vs(d,t),...l,"cmdk-group":"",role:"presentation",hidden:v?void 0:!0},r&&S.createElement("div",{ref:m,"cmdk-group-heading":"","aria-hidden":!0,id:p},r),pd(e,x=>S.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?p:void 0},S.createElement(rE.Provider,{value:b},x))))}),RP=S.forwardRef((e,t)=>{let{alwaysRender:r,...i}=e,o=S.useRef(null),l=Za(u=>!u.search);return!r&&!l?null:S.createElement(Pe.div,{ref:Vs(o,t),...i,"cmdk-separator":"",role:"separator"})}),jP=S.forwardRef((e,t)=>{let{onValueChange:r,...i}=e,o=e.value!=null,l=yg(),u=Za(p=>p.search),d=Za(p=>p.selectedItemId),m=Tl();return S.useEffect(()=>{e.value!=null&&l.setState("search",e.value)},[e.value]),S.createElement(Pe.input,{ref:t,...i,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":m.listId,"aria-labelledby":m.labelId,"aria-activedescendant":d,id:m.inputId,type:"text",value:o?e.value:u,onChange:p=>{o||l.setState("search",p.target.value),r?.(p.target.value)}})}),TP=S.forwardRef((e,t)=>{let{children:r,label:i="Suggestions",...o}=e,l=S.useRef(null),u=S.useRef(null),d=Za(p=>p.selectedItemId),m=Tl();return S.useEffect(()=>{if(u.current&&l.current){let p=u.current,y=l.current,v,b=new ResizeObserver(()=>{v=requestAnimationFrame(()=>{let x=p.offsetHeight;y.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return b.observe(p),()=>{cancelAnimationFrame(v),b.unobserve(p)}}},[]),S.createElement(Pe.div,{ref:Vs(l,t),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":d,"aria-label":i,id:m.listId},pd(e,p=>S.createElement("div",{ref:Vs(u,m.listInnerRef),"cmdk-list-sizer":""},p)))}),OP=S.forwardRef((e,t)=>{let{open:r,onOpenChange:i,overlayClassName:o,contentClassName:l,container:u,...d}=e;return S.createElement(pp,{open:r,onOpenChange:i},S.createElement(vp,{container:u},S.createElement(yp,{"cmdk-overlay":"",className:o}),S.createElement(bp,{"aria-label":e.label,"cmdk-dialog":"",className:l},S.createElement(aE,{ref:t,...d}))))}),AP=S.forwardRef((e,t)=>Za(r=>r.filtered.count===0)?S.createElement(Pe.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),MP=S.forwardRef((e,t)=>{let{progress:r,children:i,label:o="Loading...",...l}=e;return S.createElement(Pe.div,{ref:t,...l,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},pd(e,u=>S.createElement("div",{"aria-hidden":!0},u)))}),md=Object.assign(aE,{List:TP,Item:CP,Input:jP,Group:EP,Separator:RP,Dialog:OP,Empty:AP,Loading:MP});function NP(e,t){let r=e.nextElementSibling;for(;r;){if(r.matches(t))return r;r=r.nextElementSibling}}function DP(e,t){let r=e.previousElementSibling;for(;r;){if(r.matches(t))return r;r=r.previousElementSibling}}function iE(e){let t=S.useRef(e);return Mi(()=>{t.current=e}),t}var Mi=typeof window>"u"?S.useEffect:S.useLayoutEffect;function Ds(e){let t=S.useRef();return t.current===void 0&&(t.current=e()),t}function Za(e){let t=yg(),r=()=>e(t.snapshot());return S.useSyncExternalStore(t.subscribe,r,r)}function sE(e,t,r,i=[]){let o=S.useRef(),l=Tl();return Mi(()=>{var u;let d=(()=>{var p;for(let y of r){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(p=y.current.textContent)==null?void 0:p.trim():o.current}})(),m=i.map(p=>p.trim());l.value(e,d,m),(u=t.current)==null||u.setAttribute(Ns,d),o.current=d}),o}var kP=()=>{let[e,t]=S.useState(),r=Ds(()=>new Map);return Mi(()=>{r.current.forEach(i=>i()),r.current=new Map},[e]),(i,o)=>{r.current.set(i,o),t({})}};function zP(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function pd({asChild:e,children:t},r){return e&&S.isValidElement(t)?S.cloneElement(zP(t),{ref:t.ref},r(t.props.children)):r(t)}var LP={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function $P({className:e,...t}){return f.jsx(md,{"data-slot":"command",className:We("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})}function IP({className:e,...t}){return f.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[f.jsx(x_,{className:"size-4 shrink-0 opacity-50"}),f.jsx(md.Input,{"data-slot":"command-input",className:We("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function PP({className:e,...t}){return f.jsx(md.List,{"data-slot":"command-list",className:We("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function FP({className:e,...t}){return f.jsx(md.Item,{"data-slot":"command-item",className:We("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...t})}function gw(e,t){if(!e)return{score:0,hits:[]};const r=e.toLowerCase(),i=t.toLowerCase();let o=0,l=0,u=0;const d=[];for(let m=0;m3&&i.endsWith("ies")?o=i.slice(0,-3)+"y":i.length>3&&i.endsWith("es")?o=i.slice(0,-2):i.length>2&&i.endsWith("s")&&(o=i.slice(0,-1)),o?gw(o,t):null}function UP({text:e,hits:t}){const r=[];let i=0;return t.forEach((o,l)=>{o>i&&r.push(e.slice(i,o)),r.push(f.jsx("b",{children:e[o]},l)),i=o+1}),r.push(e.slice(i)),f.jsx("span",{className:"plabel",children:r})}function HP({open:e,onClose:t,candidates:r}){const[i,o]=S.useState(""),l=S.useMemo(()=>{if(!e)return[];const d=[];for(const m of r()){const p=VP(i,m.label);p&&d.push({...m,score:p.score,hits:p.hits})}return d.sort((m,p)=>p.score-m.score),d.slice(0,40)},[e,i,r]);S.useEffect(()=>{e&&o("")},[e]);const u=d=>{t(),d.run()};return f.jsx(Wu,{open:e,onOpenChange:d=>!d&&t(),children:f.jsxs(ed,{id:"palette",className:"palette",showCloseButton:!1,"aria-describedby":void 0,children:[f.jsx(Cl,{className:"sr-only",children:"Search and quick actions"}),f.jsxs($P,{shouldFilter:!1,loop:!0,children:[f.jsxs("div",{id:"palette-inputwrap",children:[f.jsx(lt,{name:"search"}),f.jsx(IP,{placeholder:"Search file names, projects, actions…",autoComplete:"off",spellCheck:!1,value:i,onValueChange:o})]}),f.jsx(PP,{children:l.length===0?f.jsx("div",{className:"pempty",children:"No matches — search covers file names, projects, and actions"}):l.map(d=>f.jsxs(FP,{value:d.kind+":"+d.label,onSelect:()=>u(d),children:[f.jsx("span",{className:"picon",children:f.jsx(lt,{name:d.icon})}),f.jsx(UP,{text:d.label,hits:d.hits}),f.jsx("span",{className:"pkind",children:d.kind})]},d.kind+":"+d.label))}),f.jsx("footer",{id:"palette-hint",children:"↑↓ navigate · ⏎ select · esc close"})]})]})})}function BP(e,t){return Ft({queryKey:["heatDevices",e],queryFn:()=>qt(e+"heat?by=device&days=30"),enabled:t,retry:!1,staleTime:6e4}).data?.devices??null}const qP=["all","human","agent","share"],GP={all:"All reads",human:"Human reads",agent:"Agent reads",share:"Shared reads"},ZP={agent:{agent:1,human:0,share:0},human:{agent:0,human:1,share:0},share:{agent:0,human:0,share:1}};function vw(e){const[t,r]=S.useState("all"),{flatFiles:i,heatMap:o,devices:l,scope:u}=e,d=w=>!u||w===u||w.startsWith(u+"/"),m=u?i.filter(w=>d(w.path)):i;if(!e.loading&&!m.length)return f.jsxs("div",{className:"insights",children:[f.jsxs("h1",{className:"in-title",children:["Knowledge insights",u?f.jsxs("span",{className:"in-scope",children:[" · ",u]}):null]}),f.jsxs("div",{className:"dl-empty in-blank",children:[f.jsx("p",{children:u?`Nothing in ${u} to chart yet.`:"Nothing to chart yet."}),f.jsx("p",{children:u?`No files under ${u} are syncing here yet.`:"This project has no files. Once a device syncs files here, the map, the reads × freshness plot and the hot path fill in on their own."}),e.installHref&&f.jsx("a",{className:"pbtn",...Gs(e.installHref),children:"Set up a device →"})]})]});const p=l&&u?l.map(w=>{const _=Object.create(null);for(const[E,R]of Object.entries(w.folders||{}))d(E)&&(_[E]=R);return{...w,folders:_}}).filter(w=>Object.keys(w.folders).length>0):l,y=Date.now(),v=m.map(w=>{const _=o&&o[w.path]||{},E=w.time?Math.max(0,(y-new Date(w.time).getTime())/864e5):0,R=t==="all"?na(_):_[t]||0;return{path:w.path,reads:R,agent:_.agent||0,human:_.human||0,share:_.share||0,total:na(_),days:E,danger:GC(R,E)}}),b=cI(o,new Set(i.map(w=>w.path))).filter(d).map(w=>{const _=o[w];return{path:w,reads:t==="all"?na(_):_[t]||0,agent:_.agent||0,human:_.human||0,share:_.share||0,total:na(_),days:0,danger:!1,orphan:!0}}).filter(w=>w.reads>0),x=b.length>0?f.jsxs("p",{className:"in-legend in-orphan-note",children:[rp(b.length,"file")," with reads ",b.length===1?"is":"are"," no longer in the project — see Hot path."]}):null;return f.jsxs("div",{className:"insights",children:[f.jsxs("h1",{className:"in-title",children:["Knowledge insights",u?f.jsxs("span",{className:"in-scope",children:[" · ",u]}):null]}),f.jsx("p",{className:"dl-sub",children:u?`Reads over the last 30 days × freshness, for ${u} and everything in it. ${Ci}`:"Reads over the last 30 days × how long since each file changed. Hot but stale knowledge — read a lot, maintained by nobody — is the danger zone. "+Ci}),f.jsx("div",{className:"in-lens",children:qP.map(w=>f.jsx("button",{className:"in-lens-btn"+(w===t?" active":""),onClick:()=>r(w),children:GP[w]},w))}),f.jsx("h3",{className:"dl-h3",children:"Map — cell size = reads, color = freshness (scale below)"}),f.jsx(YP,{pts:v,onOpenFile:e.onOpenFile,onOpenFolder:e.onOpenFolder,isFolder:e.isFolder}),x,f.jsxs("h3",{className:"dl-h3 in-h3-row",children:["Reads × freshness",f.jsx("span",{className:"in-cap",children:"dot size = agent share of reads"})]}),f.jsx(XP,{pts:v,onOpenFile:e.onOpenFile}),x,f.jsx("h3",{className:"dl-h3",children:"Hot path — top files by reads"}),f.jsx(JP,{pts:[...v,...b],lens:t,onOpenFile:e.onOpenFile,onOpenHistory:e.onOpenHistory}),p&&p.length>0&&f.jsxs(f.Fragment,{children:[f.jsx("h3",{className:"dl-h3",children:"Agent coverage — which agents read which areas"}),f.jsx(WP,{devices:p})]})]})}const KP="rgb(150,156,164)";function oE(e){const t=[[76,195,138],[232,196,84],[224,93,93]],r=Math.min(1,Math.max(0,e/300))*(t.length-1),i=Math.min(t.length-2,Math.floor(r)),o=r-i,l=t[i].map((u,d)=>Math.round(u+(t[i+1][d]-u)*o));return`rgb(${l[0]},${l[1]},${l[2]})`}function yw(e,t,r,i,o){const l=e.reduce((p,y)=>p+y.value,0);if(!l||i<=0||o<=0)return[];const u=e.slice().sort((p,y)=>y.value-p.value).map(p=>({it:p,a:p.value/l*i*o})),d=(p,y)=>{const b=p.reduce((w,_)=>w+_.a,0)/y;let x=0;for(const w of p){const _=w.a/b;x=Math.max(x,_/b,b/_)}return x},m=[];for(;u.length;){const p=i>=o,y=p?o:i,v=[u.shift()];for(;u.length&&d(v.concat(u[0]),y)<=d(v,y);)v.push(u.shift());const b=v.reduce((w,_)=>w+_.a,0)/y;let x=0;for(const w of v){const _=w.a/b;p?m.push({item:w.it,x:t,y:r+x,w:b,h:_}):m.push({item:w.it,x:t+x,y:r,w:_,h:b}),x+=_}p?(t+=b,i-=b):(r+=b,o-=b)}return m}const dm=15;function bw(e,t,r){const i=Math.floor((r-8)/6),o=`${e} · ${t}`;return o.length<=i?{label:o,fit:i}:{label:e.length>i?e.slice(0,Math.max(1,i-1))+"…":e,fit:i}}const rp=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function YP({pts:e,onOpenFile:t,onOpenFolder:r,isFolder:i}){const u=dI(e.map(y=>y.days)),d=!!u&&fI(u.min,u.max),m=new Map;for(const y of e){const v=y.path.includes("/")?y.path.split("/")[0]:"/";let b=m.get(v);b||m.set(v,b={name:v,files:[],value:0,reads:0}),b.files.push(y),b.value+=y.reads+1,b.reads+=y.reads}const p=[];for(const y of yw([...m.values()],0,0,720,480)){const v=y.item,b=v.name==="/"?"":v.name,x=v.name==="/"?"(root)":v.name;if(p.push(f.jsx("rect",{x:y.x+1,y:y.y+1,width:Math.max(0,y.w-2),height:Math.max(0,y.h-2),rx:3,className:"in-tm-group","data-dir":b,children:f.jsx("title",{children:`${v.name==="/"?"(root)":v.name+"/"} — ${rp(v.reads,"read")}/30d · ${rp(v.files.length,"file")}`})},"g"+v.name)),y.w>46&&y.h>dm+10){const{label:_}=bw(x,v.reads,y.w);p.push(f.jsx("text",{x:y.x+5,y:y.y+12,className:"in-tm-glabel","data-dir":b,children:_},"gl"+v.name))}const w=yw(v.files.map(_=>({..._,name:_.path.split("/").pop(),value:_.reads+1})),y.x+2,y.y+dm,Math.max(0,y.w-4),Math.max(0,y.h-dm-2));for(const _ of w)if(p.push(f.jsx("rect",{x:_.x+.6,y:_.y+.6,width:Math.max(.4,_.w-1.2),height:Math.max(.4,_.h-1.2),rx:1.5,fill:d?KP:oE(_.item.days),className:"in-tm-cell","data-path":_.item.path,children:f.jsx("title",{children:`${_.item.path} — ${_.item.reads} read${_.item.reads===1?"":"s"}/30d · changed ${Math.round(_.item.days)}d ago`})},_.item.path)),_.w>54&&_.h>16){const{label:E,fit:R}=bw((_.item.danger?"⚠ ":"")+_.item.name,_.item.reads,_.w);R>=5&&p.push(f.jsx("text",{x:_.x+4.5,y:_.y+12.5,className:"in-tm-label","data-path":_.item.path,children:E},"l"+_.item.path))}}return f.jsxs(f.Fragment,{children:[f.jsx("svg",{viewBox:"0 0 720 480",className:"in-chart in-treemap",onClick:y=>{const v=y.target.closest("[data-path], [data-dir]");if(!v)return;const b=v.getAttribute("data-path");if(b)return t(b);const x=v.getAttribute("data-dir");x&&i(x)&&r(x)},children:p}),f.jsx(QP,{range:u,flat:d})]})}function QP({range:e,flat:t}){if(!e)return null;const r=hI(e.min,e.max);return f.jsxs("p",{className:"in-legend in-tm-legend",children:["freshness 0d",f.jsx("span",{className:"in-sw in-sw-age"+(t?" in-sw-flat":""),style:{background:`linear-gradient(to right, ${[0,60,150,300].map(oE).join(", ")})`}}),"300d+",f.jsx("span",{className:"in-tm-range",children:t?`all files here: ${r} old — colour off, not enough range to rank`:`observed: ${r} old`})]})}function XP({pts:e,onOpenFile:t}){const o={l:44,r:16,t:20,b:34},l=Math.max(Ms*2,...e.map(w=>w.days)),u=Math.max(tl*2,...e.map(w=>w.reads)),d=w=>Math.log10(w+1)/Math.log10(l+1),m=w=>Math.log10(w+1)/Math.log10(u+1),p=w=>3+4*w,y=p(1),v=w=>o.l+y+d(w)*(720-o.l-o.r-2*y),b=w=>360-o.b-y-m(w)*(360-o.t-o.b-2*y),x=gI(e.filter(w=>w.danger).map(w=>({path:w.path,reads:w.reads,cx:v(w.days),cy:b(w.reads),r:p(w.total?(w.agent||0)/w.total:0)})),{right:720-o.r,top:o.t+8,bottom:360-o.b-4});return f.jsxs("svg",{viewBox:"0 0 720 360",className:"in-chart",children:[f.jsx("rect",{x:v(Ms),y:o.t,width:720-o.r-v(Ms),height:b(tl)-o.t,className:"in-danger-zone"}),f.jsx("line",{x1:v(Ms),y1:o.t,x2:v(Ms),y2:360-o.b,className:"in-threshold"}),f.jsx("line",{x1:o.l,y1:b(tl),x2:720-o.r,y2:b(tl),className:"in-threshold"}),f.jsx("line",{x1:o.l,y1:360-o.b,x2:720-o.r,y2:360-o.b,className:"in-axis"}),f.jsx("line",{x1:o.l,y1:o.t,x2:o.l,y2:360-o.b,className:"in-axis"}),f.jsx("text",{x:(o.l+720-o.r)/2,y:352,className:"in-label",children:"days since last change →"}),f.jsx("text",{x:12,y:(o.t+360-o.b)/2,className:"in-label",transform:`rotate(-90 12 ${(o.t+360-o.b)/2})`,children:"reads / 30d →"}),f.jsx("text",{x:720-o.r-6,y:o.t+14,className:"in-quad in-quad-danger",textAnchor:"end",children:"hot + stale"}),f.jsx("text",{x:o.l+6,y:o.t+14,className:"in-quad",children:"hot + fresh"}),f.jsx("text",{x:720-o.r-6,y:360-o.b-8,className:"in-quad",textAnchor:"end",children:"cold + stale"}),f.jsx("text",{x:o.l+6,y:360-o.b-8,className:"in-quad",children:"cold + fresh"}),e.map(w=>{const _=w.total?(w.agent||0)/w.total:0;return f.jsx("circle",{cx:Number(v(w.days).toFixed(1)),cy:Number(b(w.reads).toFixed(1)),r:Number(p(_).toFixed(1)),className:"in-pt"+(w.danger?" danger":w.reads?"":" cold"),onClick:()=>t(w.path),children:f.jsx("title",{children:`${w.path} — ${w.reads} read${w.reads===1?"":"s"} / 30d · changed ${Math.round(w.days)}d ago`})},w.path)}),x.map(w=>f.jsx("text",{x:Number(w.x.toFixed(1)),y:Number(w.y.toFixed(1)),textAnchor:w.anchor,className:"in-pt-label",children:w.name},w.path))]})}function JP({pts:e,lens:t,onOpenFile:r,onOpenHistory:i}){const o=e.filter(d=>d.reads>0).sort((d,m)=>m.reads-d.reads||m.days-d.days).slice(0,20);if(!o.length)return f.jsx("div",{className:"dl-empty",children:"No reads in the window yet."});const l=o[0].reads,u=o.some(d=>d.share>0);return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"in-hotpath",children:o.map(d=>{const m=ZP[t]??lI(d),p=d.reads/l*100,y=()=>d.orphan?i(d.path):r(d.path);return f.jsxs("div",{className:"in-hp-row",tabIndex:0,role:"button",title:d.orphan?`${d.reads} read${d.reads===1?"":"s"}/30d · no longer in the project — open its history`:d.danger?`${d.reads} read${d.reads===1?"":"s"}/30d · unchanged ${Math.round(d.days)}d — review this file`:d.path,onClick:y,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),y())},children:[f.jsx("span",{className:"in-hp-name"+(d.danger?" danger":""),children:d.path+(d.danger?" ⚠":"")}),d.orphan&&f.jsx("span",{className:"in-hp-gone",children:"· no longer in the project"}),f.jsxs("span",{className:"in-hp-bar",children:[f.jsx("span",{className:"in-hp-agent",style:{width:(p*m.agent).toFixed(1)+"%"}}),f.jsx("span",{className:"in-hp-human",style:{width:(p*m.human).toFixed(1)+"%"}}),f.jsx("span",{className:"in-hp-share",style:{width:(p*m.share).toFixed(1)+"%"}})]}),f.jsx("span",{className:"in-hp-count",children:d.reads})]},d.path)})}),f.jsxs("p",{className:"in-legend",children:[f.jsx("span",{className:"in-sw agent"})," agent reads ",f.jsx("span",{className:"in-sw human"})," human reads",u&&f.jsxs(f.Fragment,{children:[" ",f.jsx("span",{className:"in-sw share"})," shared reads"]})]})]})}function WP({devices:e}){const t=new Map;for(const b of e)for(const[x,w]of Object.entries(b.folders||{}))t.set(x,(t.get(x)||0)+w);const r=[...t.entries()].sort((b,x)=>x[1]-b[1]).slice(0,12).map(b=>b[0]),i=e.slice(0,12),o=140,l=6,u=Math.min(76,Math.max(34,(720-o-8)/r.length)),d=26,m=720,p=l+i.length*d+58,y=Math.max(1,...i.flatMap(b=>r.map(x=>(b.folders||{})[x]||0))),v=b=>{const x=[23,25,31],w=[245,166,35],_=x.map((E,R)=>Math.round(E+(w[R]-E)*b));return`rgb(${_[0]},${_[1]},${_[2]})`};return f.jsxs("svg",{viewBox:`0 0 ${m} ${p}`,className:"in-chart in-matrix",children:[i.map((b,x)=>{let w=b.name||b.id||"";return w.length>20&&(w=w.slice(0,19)+"…"),f.jsxs("g",{children:[f.jsx("text",{x:o-8,y:l+x*d+17,textAnchor:"end",className:"in-label",children:w}),r.map((_,E)=>{const R=(b.folders||{})[_]||0;return f.jsx("rect",{x:o+E*u,y:l+x*d,width:u-4,height:d-4,rx:3,fill:v(Math.sqrt(R/y)),children:f.jsx("title",{children:`${b.name||b.id} × ${_||"(root)"}: ${R} read${R===1?"":"s"}/30d`})},_)})]},b.id||x)}),r.map((b,x)=>{const w=o+x*u+(u-4)/2,_=l+i.length*d+14;return f.jsx("text",{x:w,y:_,className:"in-label",textAnchor:"end",transform:`rotate(-28 ${w} ${_})`,children:b||"(root)"},b)})]})}function lE(e){return new Set(e.entries.map(t=>t.path)).size}function eF(e){const t=l=>(l.session?"s\0"+l.session:"n\0"+l.note)+"\0"+(l.device?.id??""),r=new Map;e.forEach((l,u)=>{if(!l.note&&!l.session)return;const d=r.get(t(l));if(d){d.entries.push(l),d.idx.push(u);return}r.set(t(l),{note:l.note??"",session:l.session,entries:[l],idx:[u]})});const i=[],o=new Set;return e.forEach((l,u)=>{const d=l.note||l.session?r.get(t(l)):void 0;if(!d||lE(d)<2){i.push({i:u});return}o.has(d)||(o.add(d),i.push({run:d,i:u}))}),i}function tF(e){const{filters:t,authors:r,onChange:i}=e,o=(y,v)=>i({...t,[y]:v||void 0}),[l,u]=S.useState(t?.q??""),d=S.useRef(!1);S.useEffect(()=>{d.current||u(t?.q??"")},[t?.q]),S.useEffect(()=>{if(!d.current)return;const y=setTimeout(()=>{d.current=!1,l!==(t?.q??"")&&o("q",l)},250);return()=>clearTimeout(y)},[l]);const m=t?.user&&!r.includes(t.user)?[t.user,...r]:r,p=Yp(t);return f.jsxs("div",{className:"hfilters",children:[f.jsxs("label",{className:"hf-search",children:[f.jsx(lt,{name:"search"}),f.jsx(fu,{type:"search",value:l,placeholder:"path contains…","aria-label":"Filter by path",onChange:y=>{d.current=!0,u(y.target.value)}})]}),f.jsxs("select",{className:"hf-user",value:t?.user??"","aria-label":"Filter by author",onChange:y=>o("user",y.target.value),children:[f.jsx("option",{value:"",children:"Anyone"}),m.map(y=>f.jsx("option",{value:y,children:y},y))]}),f.jsxs("span",{className:"hf-dates",children:[f.jsx("span",{className:"hf-lbl",children:"UTC"}),f.jsx(fu,{type:"date",className:"hf-date",value:t?.since??"","aria-label":"From date (UTC)",onChange:y=>o("since",y.target.value)}),f.jsx("span",{className:"hf-dash",children:"–"}),f.jsx(fu,{type:"date",className:"hf-date",value:t?.until??"","aria-label":"To date (UTC)",onChange:y=>o("until",y.target.value)})]}),p&&f.jsx("button",{type:"button",className:"hf-clear",onClick:()=>i({}),children:"Clear"})]})}function nF(e){const t=new Set;for(const r of e)r.user&&t.add(r.user);return[...t].sort()}function rF(e){const{apiBase:t,target:r,isFolder:i,onMeta:o,onRendered:l,restore:u,remove:d,undoRun:m,filters:p}=e,y=r?i(r)?{prefix:r+"/"}:{path:r}:{prefix:""},v=("path"in y&&y.path!==void 0?"path="+encodeURIComponent(y.path):"prefix="+encodeURIComponent(y.prefix??""))+D_(p).replace("?","&"),{data:b,error:x,fetchNextPage:w,hasNextPage:_,isFetchingNextPage:E}=vj({queryKey:["history",t,v],queryFn:({pageParam:$})=>qt(t+"history?"+v+"&n=100"+($?"&cursor="+encodeURIComponent($):"")),initialPageParam:"",getNextPageParam:$=>$.next_cursor,staleTime:15e3}),R=S.useRef(new Set);S.useEffect(()=>{x&&o("History unavailable: "+x.message)},[x,o]),S.useEffect(()=>{b&&l?.()},[b,l]);const T=b?b.pages.flatMap($=>$.entries||[]):[];for(const $ of nF(T))R.current.add($);const O=e.onFilters&&f.jsx(tF,{filters:p,authors:[...R.current].sort(),onChange:e.onFilters});if(!b)return O?f.jsx("div",{className:"history",children:O}):null;const N=$=>{for(let he=$+1;he{const he=T[$].kind==="delete"?N($):T[$].blob;return he&&he===k.get(T[$].path)?void 0:he},H=$=>k.get(T[$].path)==="";return f.jsxs("div",{className:"history",children:[O,T.length===0&&(Yp(p)?f.jsxs("div",{className:"empty",children:["No changes match these filters.",f.jsx("br",{}),f.jsx("button",{type:"button",className:"btn hf-clear-empty",onClick:()=>e.onFilters?.({}),children:"Clear filters"})]}):f.jsx("div",{className:"empty",children:"No history yet."})),eF(T).map(($,he)=>$.run?f.jsx(aF,{run:$.run,onOpen:e.onOpen,apiBase:t,prevBlob:N,restoreSha:B,recreates:H,restore:u,remove:d,undoRun:m},"g"+he):f.jsx(vg,{entry:T[$.i],apiBase:t,onOpen:e.onOpen,diff:{apiBase:t,prev:N($.i)},restore:u,restoreSha:B($.i),recreates:H($.i)},"r"+$.i)),_&&f.jsx("button",{type:"button",className:"btn hmore",onClick:()=>w(),disabled:E,children:E?"Loading…":"Load more"})]})}function aF({run:e,onOpen:t,apiBase:r,prevBlob:i,restoreSha:o,recreates:l,restore:u,remove:d,undoRun:m}){const[p,y]=S.useState(!0),v=e.entries[0],b=fd(v),x=[v.device.name||v.device.id,v.device.os].filter(Boolean).join(" · "),w=v.session,_=v.device?.id,{data:E}=Ft({queryKey:["session-reads",r,w,_],queryFn:()=>qt(r+"heat?session="+encodeURIComponent(w)+"&device="+encodeURIComponent(_)),enabled:!!w&&!!_,staleTime:3e4}),R=new Set(E?.paths??[]),T=new Set(e.entries.map($=>$.path)),O=[...R].filter($=>!T.has($)).sort(),N=e.entries.map($=>new Date($.time).getTime()),k=iF(Math.min(...N),Math.max(...N)),B=lE(e),H=!!m?.busy&&m.busy===(e.session||e.note);return f.jsxs("div",{className:"hrun"+(p?" open":""),children:[f.jsxs("div",{className:"hrun-head",children:[f.jsx("button",{type:"button",className:"hrun-toggle","aria-expanded":p,title:p?"Collapse this run":"Expand this run",onClick:()=>y(!p),children:f.jsx(lt,{name:p?"chevd":"chev"})}),f.jsx("span",{className:"hrun-note",children:f.jsx(XC,{text:e.note})}),f.jsxs("span",{className:"hrun-meta",children:[R.size>0?`read ${R.size} · changed ${B}`:`${B} file${B===1?"":"s"}`," ·"," ",b,x?" · "+x:""]}),f.jsx("span",{className:"hrun-time",children:k}),m&&f.jsxs("button",{type:"button",className:"hrun-undo",disabled:H,title:"Put every file this run touched back the way it was",onClick:()=>m.onUndoRun(e),children:[f.jsx(lt,{name:"hist"}),H?"undoing…":"undo this run"]})]}),p&&f.jsxs("div",{className:"hrun-body",children:[e.entries.map(($,he)=>f.jsx(vg,{entry:$,apiBase:r,onOpen:t,diff:{apiBase:r,prev:i(e.idx[he])},restore:u,remove:d,restoreSha:o(e.idx[he]),recreates:l(e.idx[he]),inRun:!0,read:R.has($.path)},he)),O.length>0&&f.jsxs("div",{className:"hrun-reads",children:[f.jsx("div",{className:"hrun-reads-head",children:"Read, not changed"}),O.map($=>f.jsxs("button",{type:"button",className:"hrun-read",onClick:()=>t($),children:[f.jsx("span",{className:"hkind",children:"read"}),f.jsx("span",{className:"hpath",children:$})]},$))]}),w&&f.jsx("div",{className:"hrun-foot",children:"Reads shown only for files the project still has."})]})]})}function iF(e,t){const r=new Date(e),i=new Date(t),o=u=>u.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r.toDateString()!==i.toDateString())return r.toLocaleString()+" – "+i.toLocaleString();const l=i.toLocaleDateString();return e===t?l+" "+o(i):l+" "+o(r)+" – "+o(i)}function sF(e,t){return e?t(e)?e+"/ (folder)":e:"all changes"}function oF(e){const{apiBase:t,path:r,version:i}=e,o="path="+encodeURIComponent(r),{data:l}=Ft({queryKey:["history",t,o,200],queryFn:()=>qt(t+"history?"+o+"&n=200"),staleTime:15e3}),u=l?.entries?.find(y=>y.blob===i),d=u?fd(u):"",m=u?.time?new Date(u.time).toLocaleString():"",p=t+"blob?sha="+i+"&name="+encodeURIComponent(r.split("/").pop()||r)+"&download=1";return f.jsxs("div",{className:"vbanner",role:"status",children:[f.jsx("span",{className:"vb-icon",children:f.jsx(lt,{name:"clock"})}),f.jsxs("div",{className:"vb-text",children:[f.jsx("b",{children:[m&&"Version from "+m,d&&"by "+d].filter(Boolean).join(" ")||"Earlier version"}),f.jsx("span",{children:"This is not the current file."})]}),f.jsxs("div",{className:"vb-actions",children:[f.jsx("button",{className:"ai-btn",onClick:e.onViewCurrent,children:"View current"}),f.jsx("a",{className:"ai-btn",download:!0,href:p,children:"Download this version"})]})]})}const lF={aws_access_key_id:"an AWS access key",openai_api_key:"an OpenAI API key",github_pat:"a GitHub token",slack_token:"a Slack token",private_key:"a private key",gitlab_pat:"a GitLab token"};function cF(e=[]){const t=e.map(i=>`${lF[i.rule]??i.rule} (line ${i.line})`);return`BearDrive found ${t.length>1?t.slice(0,-1).join(", ")+" and "+t[t.length-1]:t[0]||"something credential-shaped"} in this file. The check covers the file at the moment you share it — a link always serves the file's latest content, so later changes are never checked. Share anyway?`}function cE(e){const{config:t,apiBase:r,route:i,hub:o,project:l}=e,u=Xp(),d=Ni(),{tree:m,flatFiles:p,dirIndex:y,loaded:v}=bI(r,!o||!!l),b=xI(r,o&&!!l&&!!t.reads?.enabled),x=o&&!!l&&!i.path&&!i.view,w=i.view==="dashboard"||x,_=BP(r,w);S.useEffect(()=>{w&&d.invalidateQueries({queryKey:["heat",r]})},[w,r,d]);const E=i.path,R=i.view?void 0:i.version,T=E||(i.view==="dashboard"||i.view==="history")&&i.viewTarget||"",O=!!E&&y.has(E),N=!!E&&v&&!O&&p.some(te=>te.path===E),k=!!E&&v&&!O&&!N,B=O&&!i.view,{data:H}=Ft({queryKey:["resolve",r,E],queryFn:()=>qt(r+"resolve?path="+encodeURIComponent(E)),enabled:k,retry:!1,staleTime:6e4}),[$,he]=S.useState(null);S.useEffect(()=>{!k||!H?.to||(he({from:E,to:H.to}),Yt(qs(H.to,l?.id),{replace:!0}))},[k,H,E,l?.id]);const[be,pe]=S.useState(()=>new Set),fe=S.useRef(!0);S.useEffect(()=>{if(!m||!fe.current)return;fe.current=!1;const te=(m.children||[]).filter(oe=>oe.dir);te.length===1&&pe(oe=>new Set(oe).add(te[0].path))},[m]),S.useEffect(()=>{!T||!v||pe(te=>{const oe=new Set(te);for(const Re of VI(T))oe.add(Re);return y.has(T)&&oe.add(T),oe})},[T,v,y]);const ue=S.useCallback(te=>{pe(oe=>{const Re=new Set(oe);return Re.has(te)?Re.delete(te):Re.add(te),Re})},[]),W=S.useRef(null),ve=S.useRef(new Map),L=S.useRef({key:"",want:0,attempts:0});S.useEffect(()=>{L.current={key:u,want:$3()==="POP"?ve.current.get(u)??0:0,attempts:0}},[u]);const Z=S.useCallback(()=>{const te=W.current,oe=L.current;!te||oe.key!==u||oe.attempts>=3||(oe.attempts++,te.scrollTo({top:oe.want,behavior:"instant"}))},[u]),ne=S.useCallback(()=>{W.current&&ve.current.set(u,W.current.scrollTop)},[u]),X=S.useCallback((te,oe)=>{Yt(qs(te,l?.id,oe)),hr()},[l?.id]),ee=S.useCallback(te=>Yt(Pn("history",l?.id,te)),[l?.id]),[D,M]=S.useState(""),[U,Q]=S.useState(null),[K,de]=S.useState(!1),[re,xe]=S.useState(!1);S.useEffect(()=>GD(()=>xe(!0)),[]);const we=S.useRef(null),Me=e.panel??null,Fe=!Me&&o&&!!l&&N&&_i(l.perm,"write"),{data:He}=T_(l?.id,o&&!!l),ct=S.useCallback(()=>{d.invalidateQueries({queryKey:["shares",l?.id]})},[d,l?.id]),Je=N?(He||[]).filter(te=>te.path===E):[],hn=!Me&&o&&!!l,mn=!Me&&N,Xt=!Me&&(N||o&&!!l&&O),yr=R?r+"blob?sha="+R+"&name="+encodeURIComponent(E)+"&download=1":r+"download?path="+encodeURIComponent(E),At=S.useCallback(async()=>{const te=oe=>fetch(r+"shares",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(oe?{path:E,confirm:!0}:{path:E})});try{let oe=await te(!1);if(oe.status===409){const{findings:at}=await oe.json();if(!await za("This file may contain credentials",cF(at),"Share anyway",!0))return;oe=await te(!0)}if(!oe.ok)throw new Error(await oe.text());const Re=await oe.json();zw("share_created");const ze=await Zs(Re.url);Q({url:Re.url,copied:ze}),ct()}catch(oe){Ge("Share failed: "+oe.message,!0)}},[r,E,ct]),[rr,br]=S.useState(""),Rt=o&&!!l&&_i(l?.perm,"write"),Vn=S.useCallback(async(te,oe,Re)=>{if(await za("Restore this version of "+te+"?","It syncs to every device as a new change. "+(Re?"The file comes back on every device. Removing it again isn't available from History yet.":"You can restore any other version afterwards."),"Restore")){br(te+oe);try{await ea(r+"restore",{path:te,sha:oe}),d.invalidateQueries({queryKey:["history",r]}),d.invalidateQueries({queryKey:["tree",r]}),d.invalidateQueries({queryKey:["render",r,te]}),d.invalidateQueries({queryKey:["text"]}),Ge("Restored "+te+" — it syncs to every device like any other change.")}catch(ze){Ge("Restore failed: "+ze.message,!0)}finally{br("")}}},[r,d]),[zt,Dr]=S.useState(""),ar=S.useCallback(async te=>{if(await za("Remove "+te+"?","It disappears from every synced device. History keeps it — you can restore it from the DELETED row afterwards.","Remove file",!0)){Dr(te);try{await ea(r+"remove",{path:te}),d.invalidateQueries({queryKey:["history",r]}),d.invalidateQueries({queryKey:["tree",r]}),d.invalidateQueries({queryKey:["render",r,te]}),d.invalidateQueries({queryKey:["text"]}),Ge("Removed "+te+" — it syncs to every device like any other change.")}catch(oe){Ge("Remove failed: "+oe.message,!0)}finally{Dr("")}}},[r,d]),[oa,ir]=S.useState(""),la=S.useCallback(async te=>{const oe=te.session||te.note,Re=te.session?{session:te.session,device:te.entries[0]?.device?.id}:{note:te.note,device:te.entries[0]?.device?.id};ir(oe);try{const ze=await ea(r+"undo-run",{...Re,preview:!0}),at=new Set(ze.changed_after);if(!ze.undone.length){Ge("Nothing to undo — every file this run touched already holds its pre-run content.");return}if(!await za("Undo this run?",f.jsxs(f.Fragment,{children:[f.jsxs("div",{children:[te.note||oe," — ",ze.undone.length," file",ze.undone.length===1?"":"s"]}),f.jsx("div",{className:"undo-list",children:ze.undone.map(it=>f.jsxs("div",{className:"undo-row",children:[f.jsx("span",{className:"undo-path",children:it.path}),at.has(it.path)&&f.jsx("span",{className:"undo-after",children:"changed after this run"}),f.jsx("span",{className:"undo-what",children:it.action==="remove"?"remove (the run created it)":"restore to pre-run version"})]},it.path))}),at.size>0&&f.jsxs("div",{className:"undo-warn",children:[at.size," file",at.size===1?" was":"s were"," changed by someone else after this run. Undoing overwrites ",at.size===1?"that change":"those changes"," too."]}),ze.skipped.length>0&&f.jsxs("div",{children:[ze.skipped.length," already hold",ze.skipped.length===1?"s":""," its pre-run content and will be left alone."]}),ze.refused.length>0&&f.jsxs("div",{children:[ze.refused.length," path",ze.refused.length===1?"":"s"," can't be written by the hub and will be left alone: ",ze.refused.join(", "),"."]})]}),"Undo run",!0))return;const Ae=await ea(r+"undo-run",Re);d.invalidateQueries({queryKey:["history",r]}),d.invalidateQueries({queryKey:["tree",r]}),d.invalidateQueries({queryKey:["render",r]}),d.invalidateQueries({queryKey:["text"]});const ut=Ae.skipped.length?`, skipped ${Ae.skipped.length} (already current)`:"";Ge(`Undid ${Ae.undone.length} file${Ae.undone.length===1?"":"s"}${ut}.`)}catch(ze){Ge("Undo failed: "+ze.message,!0)}finally{ir("")}},[r,d]),Jt=S.useCallback(()=>{if(!E)return ee("");ee(O?E+"/":E)},[E,O,ee]);S.useEffect(()=>{const te=oe=>{(oe.metaKey||oe.ctrlKey)&&oe.key.toLowerCase()==="k"&&(oe.preventDefault(),xe(Re=>!Re))};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[]);const A=S.useCallback(()=>{const te=[],oe=(Re,ze,at,_t)=>te.push({icon:Re,label:ze,kind:at,run:_t});if(o&&l){const Re=l.id,ze=at=>()=>{e.onClosePanel?.(),Yt(at)};oe("folder",l.name+" — project root","project",ze("/"+Re)),oe("dashboard","Dashboard","action",ze(Pn("dashboard",Re))),oe("terminal","Installation","action",ze(Pn("install",Re))),oe("gear","Settings","action",ze(Pn("settings",Re)))}if(o&&l&&E&&(N&&oe("share","Share: "+E,"action",At),oe("hist","History: "+E,"action",Jt),N&&oe("download","Download: "+E,"action",()=>we.current?.click())),o&&l&&oe("hist","History: whole project","action",()=>ee("")),o)for(const Re of e.projects||[])(!l||Re.id!==l.id)&&oe("folder","Switch to project: "+Re.name,"project",()=>Yt("/"+Re.id));t.auth?.enabled&&oe("power","Sign out","action",()=>window.location.href="/auth/logout");for(const Re of y.keys())oe("folder",Re,"folder",()=>X(Re));for(const Re of p)oe("doc",Re.path,"file",()=>X(Re.path));return te},[o,l,E,N,t.auth?.enabled,y,p,e.projects,e.onClosePanel,At,Jt,ee,X]);S.useEffect(()=>{if(!K)return;const te=()=>de(!1);return document.addEventListener("click",te),()=>document.removeEventListener("click",te)},[K]);const P=S.useCallback(te=>y.has(te),[y]);let F="app",ce,se;Me?se=Me.body:i.view==="dashboard"?se=f.jsx(vw,{flatFiles:p,heatMap:b,devices:_,scope:i.viewTarget||"",loading:!v,installHref:l?Pn("install",l.id):void 0,onOpenFile:X,onOpenFolder:X,onOpenHistory:ee,isFolder:P}):i.view==="history"?se=f.jsx(rF,{apiBase:r,target:i.viewTarget||"",isFolder:P,onOpen:X,onMeta:M,onRendered:Z,restore:Rt?{onRestore:Vn,busy:rr}:void 0,remove:Rt?{onRemove:ar,busy:zt}:void 0,undoRun:Rt?{onUndoRun:la,busy:oa}:void 0,filters:i.filters,onFilters:te=>Yt(Pn("history",l?.id,i.viewTarget||"",te))}):E?v?k?se=f.jsxs("div",{className:"notfound",children:[f.jsx("h1",{children:"Couldn't find that"}),f.jsxs("p",{children:[f.jsx("code",{children:E})," isn't in this project right now."]}),f.jsx("p",{className:"nf-sub",children:"If it was just created, it may still be uploading or syncing from a teammate's device — this page checks again automatically every few seconds, so refresh or come back in a moment."}),f.jsx("button",{className:"pbtn",onClick:()=>d.invalidateQueries({queryKey:["tree",r]}),children:"Check again"})]}):O?se=f.jsx(WI,{node:y.get(E),heatMap:b,hub:o&&!!l,apiBase:r,onOpen:X,onFullHistory:ee,onRendered:Z}):(F=AC.test(E)||MC.test(E)?"wide":"read",ce="markdown",se=f.jsxs(f.Fragment,{children:[R&&f.jsx(oF,{apiBase:r,path:E,version:R,onViewCurrent:()=>X(E)}),f.jsx(nP,{apiBase:r,path:E,version:R,heatMap:b,flatFiles:p,projectId:l?.id,onOpenFile:X,onMeta:M,onRendered:Z})]})):se=f.jsx("div",{className:"empty",children:"Loading…"}):x?se=f.jsxs(f.Fragment,{children:[f.jsx(BC,{project:l,existing:i.connect==="existing"}),f.jsx("div",{className:"home-insights",children:f.jsx(vw,{flatFiles:p,heatMap:b,devices:_,loading:!v,onOpenFile:X,onOpenFolder:X,onOpenHistory:ee,isFolder:P})})]}):se=f.jsx("div",{className:"empty",children:"Select a file to read it."}),$&&$.to===E&&(se=f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"vbanner",role:"status",children:[f.jsx("span",{className:"vb-icon",children:f.jsx(lt,{name:"link"})}),f.jsxs("div",{className:"vb-text",children:[f.jsxs("b",{children:["Moved from ",$.from]}),f.jsx("span",{children:"The URL has been updated."})]})]}),se]}));const ye=Me?Me.crumb:E?f.jsx(UI,{path:E,onOpenFolder:X}):i.view==="dashboard"?"Dashboard — "+(i.viewTarget||l?.name||""):i.view==="history"?"History — "+sF(i.viewTarget||"",P):x?l.name:null,Se=f.jsx(hl,{crumb:ye,meta:D,actions:f.jsxs(f.Fragment,{children:[Fe&&f.jsx(xt,{id:"share-btn",variant:"toolbar",className:"icon-only",title:"Share","aria-label":"Share",onClick:At,children:f.jsx(lt,{name:"share"})}),hn&&!E&&!i.view&&f.jsxs(xt,{id:"history-btn",variant:"toolbar",onClick:Jt,children:[f.jsx(lt,{name:"hist"})," ",f.jsx("span",{className:"lbl",children:"History"})]}),mn&&f.jsx("a",{id:"download",hidden:!0,download:!0,href:yr,ref:we,children:"Download"}),Xt&&f.jsx(xt,{id:"more-btn",variant:"toolbar",className:"icon-only",title:"More actions","aria-label":"More actions",onClick:te=>{te.stopPropagation(),de(!K)},children:f.jsx(lt,{name:"dots"})}),K&&f.jsxs("div",{id:"more-menu",role:"menu",children:[hn&&f.jsx("button",{className:"more-item",onClick:Jt,children:"History"}),mn&&f.jsx("button",{className:"more-item",onClick:()=>we.current?.click(),children:"Download"}),o&&!!l&&f.jsx("button",{className:"more-item",onClick:()=>{e.onClosePanel?.(),Yt(Pn("dashboard",l?.id,E))},children:"Dashboard"})]})]})});return f.jsxs(f.Fragment,{children:[f.jsx(fl,{vault:e.sidebar.vault,projectsNav:e.sidebar.projectsNav,orgBar:e.sidebar.orgBar,tree:f.jsx(FI,{root:m,expanded:be,onToggle:ue,currentPath:T,listingShowing:B,onOpen:X}),topbar:Se,contentRef:W,onContentScroll:ne,children:f.jsxs(_u,{width:F,className:ce,children:[!Me&&N&&f.jsx(fP,{shares:Je,canRevoke:!!l&&_i(l.perm,"write"),onChanged:ct}),se]})}),U&&f.jsx(dP,{url:U.url,copied:U.copied,onClose:()=>{Q(null),ct()}}),f.jsx(HP,{open:re,onClose:()=>xe(!1),candidates:A})]})}function uF({config:e}){const t=Xp(),r=A_(),[i,o]=S.useState(null),[l,u]=S.useState(null);S.useEffect(()=>u(null),[t]);const d=S.useMemo(()=>{const ve=t.split("?")[0].match(/^\/join\/([0-9a-f]+)\/?$/);return ve?ve[1]:null},[t]),{data:m}=A3(!d),{data:p}=M3(!d),y=!!e.auth.admin,{data:v}=O_(y),b=S.useMemo(()=>k_(t,"hub"),[t]),[x,w]=S.useState(!1),_=e.upload.enabled,E=async(ve,L)=>{const Z=L===qC;try{const ne=await ea("/api/projects",{name:ve,template:Z?"":L});w(!1),await r(),Yt("/"+ne.project.id+(Z?"?connect=existing":"")),Ge(`Created “${ne.project.name}”.`)}catch(ne){Ge("Could not create the project: "+ne.message,!0)}},R=x?f.jsx(sI,{templates:e.templates??[],onCreate:E,onClose:()=>w(!1)}):null,T=S.useMemo(()=>m&&(m.find(ve=>ve.id===b.project)||i&&m.find(ve=>ve.org===i)||m.find(ve=>ve.id===O$())||m[0])||null,[m,b.project,i]);if(S.useEffect(()=>{document.title=T?T.name+" — BearDrive":e.brand||"BearDrive",T&&A$(T.id)},[T,e]),d)return f.jsx(dF,{token:d,onDone:async ve=>{o(ve),await r(),Yt("/",{replace:!0})}});const O=e.brand||"BearDrive",N=T&&p?.find(ve=>ve.id===T.org)||null,k=f.jsx(Ju,{name:O,onHome:()=>Yt("/"),search:!!T,beta:O==="BearDrive"}),B=e.me?f.jsx(X$,{me:e.me,org:N,orgActive:!!b.org,billing:e.billing,admin:y?{pending:v?.length||0,onClick:()=>{u({kind:"hub"}),hr()}}:void 0}):void 0;if(!m||!p)return f.jsx(fl,{vault:k,topbar:f.jsx(hl,{}),children:f.jsx(_u,{children:f.jsx("div",{className:"empty",children:"Loading…"})})});if(!T)return f.jsxs(fl,{vault:k,projectsNav:f.jsx(sw,{projects:m,onNew:()=>w(!0)}),orgBar:B,topbar:f.jsx(hl,{}),children:[f.jsx(_u,{children:f.jsx(iI,{onNew:()=>w(!0),canCreate:_})}),R]});const H=l?.kind==="hub"?{crumb:"Signup & access",body:f.jsx(V$,{})}:null,$=b.org?p.find(ve=>ve.id===b.org):null,be=b.org&&!$?{crumb:"Organization",body:f.jsxs("div",{className:"empty",children:[f.jsx("h3",{children:"Organization not found"}),f.jsx("p",{children:"This organization doesn't exist, or you're no longer a member."}),f.jsx("p",{children:f.jsxs("a",{...Gs("/"+T.id),children:["Back to ",T.name]})})]})}:$?{crumb:"Organization",body:f.jsx(I$,{org:$,projects:m,myEmail:e.me?.email||""})}:null,pe=!!b.project&&!m.some(ve=>ve.id===b.project),fe=pe?{crumb:"Project",body:f.jsxs("div",{className:"empty",children:[f.jsx("h3",{children:"Project not found"}),f.jsx("p",{children:"This project doesn't exist, or you're no longer a member."}),f.jsx("p",{children:f.jsxs("a",{...Gs("/"+T.id),children:["Back to ",T.name]})})]})}:null,ue=b.billing?{crumb:"Billing",body:e.billing?f.jsx(J$,{url:e.billing.url}):f.jsxs("div",{className:"empty",children:[f.jsx("h3",{children:"No billing on this hub"}),f.jsx("p",{children:"This BearDrive hub doesn't have a billing surface."})]})}:null,W=b.view==="settings"?{crumb:"Project settings",body:f.jsx(tI,{project:T,org:N,onDeleted:async()=>{await r(),Yt("/")}})}:b.view==="install"?{crumb:"Installation",body:f.jsx(BC,{project:T,existing:b.connect==="existing"})}:null;if(!pe){if(!b.org&&!b.billing&&b.project!==T.id)return f.jsx(Jo,{to:"/"+T.id});if(b.legacyView&&b.view)return f.jsx(Jo,{to:Pn(b.view,T.id,b.viewTarget,b.filters)});if(b.queryTarget&&b.view)return f.jsx(Jo,{to:Pn(b.view,T.id,b.viewTarget,b.filters)});if(b.trailingSlash&&b.path)return f.jsx(Jo,{to:qs(b.path,T.id,b.version)})}return f.jsxs(f.Fragment,{children:[f.jsx(cE,{config:e,apiBase:"/api/p/"+T.id+"/",route:b,hub:!0,project:T,projects:m,sidebar:{vault:k,projectsNav:f.jsx(sw,{projects:m,currentId:T.id,onNew:()=>w(!0),menu:{active:l?null:b.view==="dashboard"&&!b.viewTarget?"dashboard":b.view==="install"?"install":b.view==="history"&&!b.viewTarget?"history":b.view==="settings"?"settings":null,onDashboard:()=>{u(null),Yt(Pn("dashboard",T.id)),hr()},onInstall:()=>{u(null),Yt(Pn("install",T.id)),hr()},onHistory:()=>{u(null),Yt(Pn("history",T.id)),hr()},onSettings:()=>{u(null),Yt(Pn("settings",T.id)),hr()}}}),orgBar:B},panel:H||be||fe||ue||W,onClosePanel:()=>u(null)},T.id),R]})}function dF({token:e,onDone:t}){return S.useEffect(()=>{let r=!1;return ea("/api/invites/"+e).then(i=>{r||(Ge(`Welcome — you joined the “${i.org.name}” team. Opening its projects…`),t(i.org.id))}).catch(i=>{r||String(i.message).includes("signing in")||(Ge("Could not accept the invite: "+i.message,!0),t(null))}),()=>{r=!0}},[e]),f.jsx(fl,{vault:f.jsx(Ju,{name:"BearDrive",beta:!0}),topbar:f.jsx(hl,{}),children:f.jsx(_u,{children:f.jsx("div",{className:"empty",children:"Joining…"})})})}function fF({config:e}){const t=Xp(),r=e.volume||"BearDrive";S.useEffect(()=>{document.title=e.brand||r},[e,r]);const i=S.useMemo(()=>k_(t,"volume"),[t]);return i.trailingSlash&&i.path?f.jsx(Jo,{to:qs(i.path)}):f.jsx(cE,{config:e,apiBase:"/api/",route:i,hub:!1,sidebar:{vault:f.jsx(Ju,{name:r,showSignout:e.auth.enabled,search:!0})}})}function hF(){const{data:e}=Sj();return f.jsxs(UD,{delayDuration:150,children:[e?e.mode==="hub"?f.jsx(uF,{config:e}):f.jsx(fF,{config:e}):f.jsx(fl,{vault:f.jsx(Ju,{name:"…",showSignout:!1}),topbar:f.jsx(hl,{}),children:f.jsx("div",{className:"empty",children:"Loading…"})}),f.jsx(S3,{}),f.jsx(j3,{})]})}class mF extends S.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("BearDrive: unhandled render error",t,r.componentStack)}render(){return this.state.error?f.jsxs("div",{className:"mx-auto max-w-lg p-8 text-sm",children:[f.jsx("h1",{className:"mb-2 text-lg font-semibold",children:"This page didn’t load"}),f.jsx("p",{className:"mb-4 opacity-80",children:"Something went wrong rendering this view. The rest of BearDrive is fine."}),f.jsx("p",{className:"mb-4",children:f.jsx("a",{className:"underline",href:"/",children:"Go to the project list"})}),f.jsx("pre",{className:"overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/10",children:String(this.state.error)})]}):this.props.children}}const pF=new ij({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}});N2.createRoot(document.getElementById("root")).render(f.jsx(S.StrictMode,{children:f.jsx(mF,{children:f.jsx(sj,{client:pF,children:f.jsx(hF,{})})})})); diff --git a/internal/webapp/static/index.html b/internal/webapp/static/index.html index 36f504b..1ca835d 100644 --- a/internal/webapp/static/index.html +++ b/internal/webapp/static/index.html @@ -5,7 +5,7 @@ BearDrive - +