@openparachute/app 0.22.9 → 0.22.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/.parachute/info +1 -1
  2. package/dist/assets/{Account-BS79MR2p.js → Account-DYfzZj5S.js} +1 -1
  3. package/dist/assets/{Activity-BCI-VU_G.js → Activity-CKF0o1vW.js} +1 -1
  4. package/dist/assets/{AddVault-BGmLnyvr.js → AddVault-DKBqKeyq.js} +1 -1
  5. package/dist/assets/{AddVaultChooser-BOYsRq-6.js → AddVaultChooser-BW2Q-Yue.js} +1 -1
  6. package/dist/assets/{AddVaultCreate-VvY9DfX7.js → AddVaultCreate-CtO9yrS5.js} +1 -1
  7. package/dist/assets/{Calendar-CStTh0s6.js → Calendar-DFuh1M3x.js} +1 -1
  8. package/dist/assets/{CheckEmail-D1qSfrIa.js → CheckEmail-CIv1Gt1o.js} +1 -1
  9. package/dist/assets/{ConnectAI-_yRQ6PVE.js → ConnectAI-BL20KQ5Y.js} +1 -1
  10. package/dist/assets/{DayView-CP-3vwhX.js → DayView-Dr2pAVmN.js} +1 -1
  11. package/dist/assets/{Export-BN79ECKv.js → Export-BynzqvGJ.js} +1 -1
  12. package/dist/assets/{Import-CGC0ejYh.js → Import-6SmwJlgO.js} +1 -1
  13. package/dist/assets/{NoteEditor-7Ul1HK8m.js → NoteEditor-OPipzN_Z.js} +1 -1
  14. package/dist/assets/NoteNew-Dy1AbHxm.js +8 -0
  15. package/dist/assets/{NoteRenderer-CyTOvjQK.js → NoteRenderer-BXeTxHnB.js} +1 -1
  16. package/dist/assets/NoteView-B0eNsUUX.js +3 -0
  17. package/dist/assets/{OAuthCallback-DXQknDTs.js → OAuthCallback-D35vvyoO.js} +1 -1
  18. package/dist/assets/{PinArchiveButtons-CJcBoOpQ.js → PinArchiveButtons-DyFdYBrq.js} +1 -1
  19. package/dist/assets/Settings-UmrOUQH_.js +1 -0
  20. package/dist/assets/{TagPage-CHDSvaJ4.js → TagPage-B7bGWyY4.js} +1 -1
  21. package/dist/assets/{TagSchemaEditor-Qk8dM9DF.js → TagSchemaEditor-Bas3UMIJ.js} +1 -1
  22. package/dist/assets/{Tags-BKTmTns9.js → Tags-CTF2n8-H.js} +1 -1
  23. package/dist/assets/{VaultGraph-CX2MzD9D.js → VaultGraph-BLefh0Zh.js} +2 -2
  24. package/dist/assets/{Vaults-B9uh43KI.js → Vaults-tXitT9QI.js} +1 -1
  25. package/dist/assets/{ViewNew-C6gk4Ujs.js → ViewNew-DRZyYhEC.js} +1 -1
  26. package/dist/assets/{ViewSurface-B-DhVasF.js → ViewSurface-DzU1BogH.js} +1 -1
  27. package/dist/assets/{Welcome-pHYMoace.js → Welcome-yAs98HfO.js} +1 -1
  28. package/dist/assets/{WizardShell-Dbn_qWnU.js → WizardShell-B0Fjh0Vt.js} +1 -1
  29. package/dist/assets/{attachment-upload-BfsE-IDX.js → attachment-upload-B8YiOVGU.js} +1 -1
  30. package/dist/assets/{history-BU5ztowk.js → history-Ce29a331.js} +1 -1
  31. package/dist/assets/{index-BhV_u6Bm.js → index-H6VNro-x.js} +2 -2
  32. package/dist/assets/{provenance-BoiAp4jO.js → provenance-DDSHYRnT.js} +1 -1
  33. package/dist/assets/{react-force-graph-2d-CAZ4sIdb.js → react-force-graph-2d-G4yaBBi0.js} +1 -1
  34. package/dist/assets/{transcribe-default-3hayXb7m.js → transcribe-default-B7i-j3pr.js} +1 -1
  35. package/dist/assets/{useAttachmentUploader-BPyx3tZN.js → useAttachmentUploader-C78HTrMx.js} +1 -1
  36. package/dist/index.html +1 -1
  37. package/dist/sw.js +1 -1
  38. package/package.json +1 -1
  39. package/dist/assets/NoteNew-B-Lomu-W.js +0 -8
  40. package/dist/assets/NoteView-CCQoXBAK.js +0 -3
  41. package/dist/assets/Settings-BvqkQbc1.js +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Account-BS79MR2p.js","assets/provenance-BoiAp4jO.js","assets/AddVault-BGmLnyvr.js","assets/WizardShell-Dbn_qWnU.js","assets/history-BU5ztowk.js","assets/url-QSQwrjSV.js","assets/AddVaultChooser-BOYsRq-6.js","assets/AddVaultCreate-VvY9DfX7.js","assets/DayView-CP-3vwhX.js","assets/Import-CGC0ejYh.js","assets/attachment-upload-BfsE-IDX.js","assets/NoteEditor-7Ul1HK8m.js","assets/useAttachmentUploader-BPyx3tZN.js","assets/NoteRenderer-CyTOvjQK.js","assets/PinArchiveButtons-CJcBoOpQ.js","assets/editor-mode-D9fveTEx.js","assets/NoteNew-B-Lomu-W.js","assets/transcribe-default-3hayXb7m.js","assets/types-BaJkUfo6.js","assets/NoteView-CCQoXBAK.js","assets/OAuthCallback-DXQknDTs.js","assets/Settings-BvqkQbc1.js","assets/Tags-BKTmTns9.js","assets/TagSchemaEditor-Qk8dM9DF.js","assets/TagPage-CHDSvaJ4.js","assets/ViewSurface-B-DhVasF.js","assets/Vaults-B9uh43KI.js","assets/Welcome-pHYMoace.js","assets/CheckEmail-D1qSfrIa.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Account-DYfzZj5S.js","assets/provenance-DDSHYRnT.js","assets/AddVault-DKBqKeyq.js","assets/WizardShell-B0Fjh0Vt.js","assets/history-Ce29a331.js","assets/url-QSQwrjSV.js","assets/AddVaultChooser-BW2Q-Yue.js","assets/AddVaultCreate-CtO9yrS5.js","assets/DayView-Dr2pAVmN.js","assets/Import-6SmwJlgO.js","assets/attachment-upload-B8YiOVGU.js","assets/NoteEditor-OPipzN_Z.js","assets/useAttachmentUploader-C78HTrMx.js","assets/NoteRenderer-BXeTxHnB.js","assets/PinArchiveButtons-DyFdYBrq.js","assets/editor-mode-D9fveTEx.js","assets/NoteNew-Dy1AbHxm.js","assets/transcribe-default-B7i-j3pr.js","assets/types-BaJkUfo6.js","assets/NoteView-B0eNsUUX.js","assets/OAuthCallback-D35vvyoO.js","assets/Settings-UmrOUQH_.js","assets/Tags-CTF2n8-H.js","assets/TagSchemaEditor-Bas3UMIJ.js","assets/TagPage-B7bGWyY4.js","assets/ViewSurface-DzU1BogH.js","assets/Vaults-tXitT9QI.js","assets/Welcome-yAs98HfO.js","assets/CheckEmail-CIv1Gt1o.js"])))=>i.map(i=>d[i]);
2
2
  var X1=Object.defineProperty;var Ev=t=>{throw TypeError(t)};var Z1=(t,a,r)=>a in t?X1(t,a,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[a]=r;var fe=(t,a,r)=>Z1(t,typeof a!="symbol"?a+"":a,r),rd=(t,a,r)=>a.has(t)||Ev("Cannot "+r);var A=(t,a,r)=>(rd(t,a,"read from private field"),r?r.call(t):a.get(t)),ue=(t,a,r)=>a.has(t)?Ev("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,r),J=(t,a,r,i)=>(rd(t,a,"write to private field"),i?i.call(t,r):a.set(t,r),r),xe=(t,a,r)=>(rd(t,a,"access private method"),r);var Iu=(t,a,r,i)=>({set _(u){J(t,a,u,r)},get _(){return A(t,a,i)}});(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))i(u);new MutationObserver(u=>{for(const f of u)if(f.type==="childList")for(const h of f.addedNodes)h.tagName==="LINK"&&h.rel==="modulepreload"&&i(h)}).observe(document,{childList:!0,subtree:!0});function r(u){const f={};return u.integrity&&(f.integrity=u.integrity),u.referrerPolicy&&(f.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?f.credentials="include":u.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function i(u){if(u.ep)return;u.ep=!0;const f=r(u);fetch(u.href,f)}})();var sD=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function J1(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var sd={exports:{}},Gi={};/**
3
3
  * @license React
4
4
  * react-jsx-runtime.production.js
@@ -31,7 +31,7 @@ Please change the parent <Route path="${O}"> to <Route path="${O==="/"?"*":`${O}
31
31
  `)}return t}function dm(t){const a=t.split("/");return(a[a.length-1]??t).replace(/\.md$/i,"")}const XA=/^\/?Notes\/(\d{4})\/(\d{2})-(\d{2})\/(\d{2})-(\d{2})-(\d{2})(?:\.md)?$/i;function ZA(t){const a=t.match(XA);if(a){const[,r,i,u,f,h]=a,m=new Date(Number(r),Number(i)-1,Number(u),Number(f),Number(h));if(!Number.isNaN(m.getTime())){const p=m.toLocaleDateString(void 0,{month:"long",day:"numeric"}),y=m.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return{kind:"timestamp",text:`${p} · ${y}`}}}return{kind:"title",text:dm(t)}}function dh(t){const a=t.displayTitle;if(typeof a=="string"&&a.length>0)return{kind:"title",text:a};if(a===void 0){const r=t.content;if(typeof r=="string"){const i=hm(r);if(i)return{kind:"title",text:i}}}return t.path?ZA(t.path):{kind:"title",text:t.id}}const sb=120,JA=100;function A0(t){var r,i;if(((r=t[0])==null?void 0:r.trim())!=="---")return 0;const a=Math.min(t.length,JA);for(let u=1;u<a;u++)if(((i=t[u])==null?void 0:i.trim())==="---")return u+1;return 0}function _0(t){return t.replace(/^#{1,6}\s*/,"").trim()}function hm(t){if(!t)return null;const a=t.split(`
32
32
  `);for(let r=A0(a);r<a.length;r++){const i=_0(a[r]);if(i==="")continue;const u=Array.from(i);return u.length>sb?u.slice(0,sb).join(""):i}return null}function ED(t){const a=t.split(`
33
33
  `),r=A0(a);let i=r;for(;i<a.length&&_0(a[i])==="";)i++;if(i>=a.length)return t;let u=i+1;for(;u<a.length&&a[u].trim()==="";)u++;return a.splice(r,u-r),a.join(`
34
- `)}const R0=512*1024*1024,ib=200;function hh(t){return t.contentEvicted?0:typeof t.byteSize=="number"&&Number.isFinite(t.byteSize)&&t.byteSize>=0?t.byteSize:WA(t)}function WA(t){var r,i,u,f;let a=(((r=t.content)==null?void 0:r.length)??0)+(((i=t.preview)==null?void 0:i.length)??0);return(u=t.links)!=null&&u.length&&(a+=JSON.stringify(t.links).length),(f=t.attachments)!=null&&f.length&&(a+=JSON.stringify(t.attachments).length),a}function e2(t){var a,r;return!!(t.content||(a=t.links)!=null&&a.length||(r=t.attachments)!=null&&r.length)}function t2(t){const a=t.preview??n2(t.content),i=t.displayTitle??hm(t.content);return{...t,content:void 0,links:void 0,attachments:void 0,contentEvicted:!0,preview:a,displayTitle:i,byteSize:(a==null?void 0:a.length)??0}}function n2(t){if(!t)return;const a=FA(t).replace(/\s+/g," ").trim();if(a)return a.length>ib?`${a.slice(0,ib).trimEnd()}…`:a}function a2(t,a,r){let i=0;for(const h of t)i+=hh(h);const u=i,f=[];if(i>a)for(const h of t){if(i<=a)break;h.contentEvicted||r(h.id)||e2(h)&&(f.push(h),i-=hh(h))}return{toEvict:f,totalBefore:u,totalAfter:i,freedBytes:u-i}}async function r2(t,a,r=R0){const i=await Lo(t,a),u=await fh(t,a),f=N0(u),h=a2(i,r,f);if(h.toEvict.length===0)return{evicted:0,freedBytes:0,totalBytes:h.totalAfter};const m=t.transaction("mirror_notes","readwrite");for(const p of h.toEvict)await m.store.put(t2(p));return await m.done,{evicted:h.toEvict.length,freedBytes:h.freedBytes,totalBytes:h.totalAfter}}async function TD(t,a){const r=await Lo(t,a);let i=0;for(const u of r)i+=hh(u);return i}const s2={includeContent:!0,includeLinks:!0,includeAttachments:!0},lb={includeContent:!1,includeLinks:!1,includeAttachments:!1},i2=6e4,l2=200,u2=1e3,o2=360*60*1e3,c2=1e3;function f2(t){return t instanceof Error?/cursor_invalid|cursor_query_mismatch/i.test(t.message):!1}class d2{constructor(a){fe(this,"timer",null);fe(this,"syncing",!1);fe(this,"sweeping",!1);fe(this,"evicting",!1);fe(this,"subscription",null);fe(this,"db");fe(this,"tickMs");fe(this,"pageLimit");fe(this,"maxDrainPages");fe(this,"sweepEnumLimit");fe(this,"sweepIntervalMs");fe(this,"ceilingBytes");fe(this,"onlineListener");fe(this,"visibilityListener");fe(this,"lastRun",null);this.opts=a,this.db=a.db,this.tickMs=a.tickIntervalMs??i2,this.pageLimit=a.pageLimit??l2,this.maxDrainPages=a.maxDrainPages??c2,this.sweepEnumLimit=a.sweepEnumLimit??u2,this.sweepIntervalMs=a.sweepIntervalMs??o2,this.ceilingBytes=a.ceilingBytes??R0,this.onlineListener=()=>{this.lastRun=this.syncOnce()},this.visibilityListener=()=>{typeof document<"u"&&document.visibilityState==="visible"&&(this.lastRun=this.syncOnce())}}start(){this.timer||(typeof window<"u"&&window.addEventListener("online",this.onlineListener),typeof document<"u"&&document.addEventListener("visibilitychange",this.visibilityListener),this.timer=setInterval(()=>{this.lastRun=this.syncOnce()},this.tickMs),this.lastRun=this.syncOnce())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&window.removeEventListener("online",this.onlineListener),typeof document<"u"&&document.removeEventListener("visibilitychange",this.visibilityListener),this.teardownSubscription()}get isSyncing(){return this.syncing}async syncOnce(){const a={pagesApplied:0,notesApplied:0,reWalked:!1};if(this.syncing)return{...a,skipped:"in-flight"};if(typeof navigator<"u"&&navigator.onLine===!1)return{...a,skipped:"offline"};const r=this.opts.resolveContext();if(!r)return this.teardownSubscription(),{...a,skipped:"no-context"};this.ensureSubscription(r),this.syncing=!0;try{const i=await this.withVaultLock(r.vaultId,()=>({...a,skipped:"locked"}),()=>this.drainCursor(r.client,r.vaultId));return await this.maybeSweep(r,i),await this.maybeEvict(i),i}catch(i){return{...a,error:i instanceof Error?i.message:String(i)}}finally{this.syncing=!1}}async withVaultLock(a,r,i){const u=typeof navigator<"u"?navigator.locks:void 0;return u!=null&&u.request?u.request(`mirror:${a}`,{ifAvailable:!0},async f=>f?i():r()):i()}async drainCursor(a,r){var p,y,S,v,x,T,j,_,C,O;let i=await _A(this.db,r)??"";const u=await go(this.db,r)===void 0;if(u){const B={phase:"hydrating"};await yd(this.db,r,B),(y=(p=this.opts).onStateChange)==null||y.call(p,r,B),(v=(S=this.opts).onProgress)==null||v.call(S,r,0)}let f=0,h=0,m=!1;try{let B=!1;for(;;){const k=i;let Y;try{Y=await a.queryNotesCursor(s2,k,this.pageLimit)}catch(G){if(!m&&f2(G)){await x0(this.db,r),i="",m=!0;continue}throw G}const Q=Y.items??[];if(Q.length>0&&(await UA(this.db,r,Q),h+=Q.length,u&&((T=(x=this.opts).onProgress)==null||T.call(x,r,h))),Q.length>0&&Y.nextCursor===void 0)throw new Error(`mirror drain: ${Q.length}-row page returned no next_cursor — cursor pagination contract violated (stale surface-client?)`);if(Y.nextCursor!==void 0&&(i=Y.nextCursor,await RA(this.db,r,i)),f+=1,Q.length===0){B=!0;break}if(Y.nextCursor===k)break;if(f>=this.maxDrainPages)throw new Error(`mirror drain: exceeded ${this.maxDrainPages} pages without exhausting the cursor`)}B&&await OA(this.db,r,Date.now());const H={phase:"live"};return await yd(this.db,r,H),(_=(j=this.opts).onStateChange)==null||_.call(j,r,H),{pagesApplied:f,notesApplied:h,reWalked:m}}catch(B){const H=B instanceof Error?B.message:String(B),k={phase:"error",lastError:H};return await yd(this.db,r,k),(O=(C=this.opts).onStateChange)==null||O.call(C,r,k),{pagesApplied:f,notesApplied:h,reWalked:m,error:H}}}async maybeSweep(a,r){if(r.error||r.skipped)return;const i=await MA(this.db,a.vaultId);(r.reWalked||i===void 0||Date.now()-i>=this.sweepIntervalMs)&&await this.reconcileSweep()}async maybeEvict(a){a.error||a.skipped||await this.evictIfOverCeiling()}async evictIfOverCeiling(){const a=i=>({evicted:0,freedBytes:0,totalBytes:0,skipped:i});if(this.evicting)return a("in-flight");const r=this.opts.resolveContext();if(!r)return a("no-context");this.evicting=!0;try{return await this.withVaultLock(r.vaultId,()=>a("locked"),()=>r2(this.db,r.vaultId,this.ceilingBytes))}finally{this.evicting=!1}}async reconcileSweep(){const a=i=>({deleted:0,backfilled:0,refetched:0,enumerated:0,aborted:i});if(this.sweeping)return a("in-flight");if(typeof navigator<"u"&&navigator.onLine===!1)return a("offline");const r=this.opts.resolveContext();if(!r)return a("no-context");this.sweeping=!0;try{return await this.withVaultLock(r.vaultId,()=>a("locked"),()=>this.runSweep(r.client,r.vaultId))}finally{this.sweeping=!1}}async runSweep(a,r){const i=await this.enumerateServerIds(a);if(!i.complete)return{deleted:0,backfilled:0,refetched:0,enumerated:i.index.size,aborted:"incomplete-enumeration"};if(i.index.size===0)return{deleted:0,backfilled:0,refetched:0,enumerated:0,aborted:"empty-enumeration"};const u=await fh(this.db,r),f=N0(u),h=await Lo(this.db,r),m=YA(h,i.index,f);await zA(this.db,r,m.toDelete);let p=0,y=0;if(a.getNote){for(const S of m.toBackfill){const v=await a.getNote(S,{includeLinks:!0,includeAttachments:!0});v&&(await ch(this.db,r,v),p+=1)}for(const S of m.toRefetch){const v=await a.getNote(S,{includeLinks:!0,includeAttachments:!0});v&&(await ch(this.db,r,v),y+=1)}}return await this.refreshTags(a,r),await DA(this.db,r,Date.now()),{deleted:m.toDelete.length,backfilled:p,refetched:y,enumerated:i.index.size}}async enumerateServerIds(a){const r=new Map;let i="",u=0;try{for(;;){const f=i,h=await a.queryNotesCursor(lb,f,this.sweepEnumLimit),m=h.items??[];for(const p of m)r.set(p.id,p.updatedAt??p.createdAt??"");if(m.length>0&&h.nextCursor===void 0)return{index:r,complete:!1};if(h.nextCursor!==void 0&&(i=h.nextCursor),m.length===0)break;if(h.nextCursor===f)return{index:r,complete:!1};if(u+=1,u>=this.maxDrainPages)return{index:r,complete:!1}}return{index:r,complete:!0}}catch{return{index:r,complete:!1}}}async refreshTags(a,r){if(a.listTags)try{const i=await a.listTags();await kA(this.db,r,i)}catch{}}ensureSubscription(a){var f;const r=a.client;if(!r.subscribe||((f=this.subscription)==null?void 0:f.vaultId)===a.vaultId)return;this.teardownSubscription();const i=a.vaultId,u=r.subscribe(lb,{onSnapshot:()=>{},onUpsert:()=>{},onRemove:h=>this.applyWsRemove(i,h)});this.subscription={vaultId:i,unsubscribe:u}}teardownSubscription(){var a;(a=this.subscription)==null||a.unsubscribe(),this.subscription=null}async applyWsRemove(a,r){try{if(zs(r)||(await fh(this.db,a)).has(r))return;await w0(this.db,a,r)}catch{}}}const h2="lens-blobs";function m2(){return typeof navigator<"u"&&typeof navigator.storage<"u"&&typeof navigator.storage.getDirectory=="function"}async function vd(){return(await navigator.storage.getDirectory()).getDirectoryHandle(h2,{create:!0})}function jD(){return crypto.randomUUID()}class p2{constructor(){fe(this,"backend","opfs")}async put(a,r,i){const u=await vd(),h=await(await u.getFileHandle(a,{create:!0})).createWritable();await h.write(r),await h.close();const p=await(await u.getFileHandle(`${a}.meta`,{create:!0})).createWritable();await p.write(i),await p.close()}async get(a){try{const r=await vd(),f=await(await(await r.getFileHandle(a)).getFile()).arrayBuffer();let h="application/octet-stream";try{h=await(await(await r.getFileHandle(`${a}.meta`)).getFile()).text()||h}catch{}return{data:f,mimeType:h}}catch(r){if(r instanceof DOMException&&r.name==="NotFoundError")return null;throw r}}async delete(a){const r=await vd();for(const i of[a,`${a}.meta`])try{await r.removeEntry(i)}catch(u){if(u instanceof DOMException&&u.name==="NotFoundError")continue;throw u}}}class g2{constructor(a){fe(this,"backend","idb");this.db=a}async put(a,r,i,u){await this.db.put("blobs",{blobId:a,data:r,mimeType:i,vaultId:u,createdAt:Date.now()})}async get(a){const r=await this.db.get("blobs",a);return r?{data:r.data,mimeType:r.mimeType}:null}async delete(a){await this.db.delete("blobs",a)}}function y2(t){return m2()?new p2:new g2(t)}const v2=3e4;class b2{constructor(a){fe(this,"timer",null);fe(this,"draining",!1);fe(this,"tickMs");fe(this,"onlineListener");fe(this,"lastRun",null);this.opts=a,this.tickMs=a.tickIntervalMs??v2,this.onlineListener=()=>{this.lastRun=this.runOnce()}}start(){this.timer||(typeof window<"u"&&window.addEventListener("online",this.onlineListener),this.timer=setInterval(()=>{this.lastRun=this.runOnce()},this.tickMs),this.lastRun=this.runOnce())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&window.removeEventListener("online",this.onlineListener)}get isDraining(){return this.draining}async runOnce(){var r,i,u,f;if(this.draining||typeof navigator<"u"&&navigator.onLine===!1)return null;const a=this.opts.resolveContext();if(!a)return null;this.draining=!0,(i=(r=this.opts).onDrainStart)==null||i.call(r);try{const h=await B2({db:this.opts.db,client:a.client,vaultId:a.vaultId,blobStore:this.opts.blobStore,...this.opts.mirror&&{mirror:this.opts.mirror}});return(f=(u=this.opts).onDrain)==null||f.call(u,h),h}finally{this.draining=!1}}}async function x2(){var t;if(typeof navigator>"u"||!((t=navigator.storage)!=null&&t.persist))return!1;try{return await navigator.storage.persist()}catch{return!1}}async function S2(){var t;if(typeof navigator>"u"||!((t=navigator.storage)!=null&&t.persisted))return!1;try{return await navigator.storage.persisted()}catch{return!1}}async function w2(){var t;if(typeof navigator>"u"||!((t=navigator.storage)!=null&&t.estimate))return{persisted:!1,usage:null,quota:null,supported:!1};try{const[a,r]=await Promise.all([S2(),navigator.storage.estimate()]);return{persisted:a,usage:r.usage??null,quota:r.quota??null,supported:!0}}catch{return{persisted:!1,usage:null,quota:null,supported:!1}}}const C0="lens:sync:lastSyncedAt";function E2(){try{const t=localStorage.getItem(C0);if(!t)return null;const a=Number(t);return Number.isFinite(a)?a:null}catch{return null}}const T2={enabled:!1,state:"off",lastSyncedAt:null,syncNow:async()=>{},clearOffline:async()=>{}},O0=b.createContext({db:null,blobStore:null,engine:null,isOnline:!0,isDraining:!1,lastSyncedAt:null,mirror:T2});function j2(t,a,r,i){return t?a?r==="error"?"error":r==="hydrating"||r===void 0&&i===null?"hydrating":"synced":"offline":"off"}function Zt(){return b.useContext(O0)}function N2({children:t}){const[a,r]=b.useState(null),[i,u]=b.useState(null),[f,h]=b.useState(typeof navigator<"u"?navigator.onLine:!0),[m,p]=b.useState(!1),[y,S]=b.useState(()=>E2()),v=ke(),x=ae(re=>re.activeVaultId),T=pt(),j=b.useMemo(()=>ra(),[]),[_,C]=b.useState(void 0),[O,B]=b.useState(void 0),[H,k]=b.useState(null);b.useEffect(()=>{let re=!1,ee=null;return NA().then(M=>{if(re){M.close();return}ee=M,r(M),u(y2(M)),x2()}).catch(()=>{}),()=>{re=!0,ee==null||ee.close()}},[]),b.useEffect(()=>{if(typeof window>"u")return;const re=()=>h(!0),ee=()=>h(!1);return window.addEventListener("online",re),window.addEventListener("offline",ee),()=>{window.removeEventListener("online",re),window.removeEventListener("offline",ee)}},[]);const Y=b.useRef(v),Q=b.useRef(x),G=b.useRef(T);Y.current=v,Q.current=x,G.current=T;const F=b.useMemo(()=>!a||!i?null:new b2({db:a,blobStore:i,mirror:$A(a),resolveContext:()=>{const re=Y.current,ee=Q.current;return!re||!ee?null:{client:re,vaultId:ee}},onDrainStart:()=>{p(!0)},onDrain:re=>{if(p(!1),re.drained>0){const ee=Date.now();S(ee);try{localStorage.setItem(C0,String(ee))}catch{}const M=Q.current;G.current.invalidateQueries({queryKey:["notes",M]}),G.current.invalidateQueries({queryKey:["tags",M]}),G.current.invalidateQueries({queryKey:["vaultInfo",M]})}}}),[a,i]);b.useEffect(()=>{if(F)return F.start(),()=>F.stop()},[F]);const Z=b.useMemo(()=>{if(!a||!j)return null;const re=ee=>ee===Q.current;return new d2({db:a,resolveContext:()=>{const ee=Y.current,M=Q.current;return!ee||!M?null:{client:ee,vaultId:M}},onStateChange:(ee,M)=>{re(ee)&&(C(M.phase),M.phase==="live"&&(B(void 0),go(a,ee).then(P=>{re(ee)&&k(P??null)})))},onProgress:(ee,M)=>{re(ee)&&B({done:M})}})},[a,j]);b.useEffect(()=>{if(Z)return Z.start(),()=>Z.stop()},[Z]),b.useEffect(()=>{if(!a||!j||!x){C(void 0),B(void 0),k(null);return}let re=!0;return B(void 0),Promise.all([CA(a,x),go(a,x)]).then(([ee,M])=>{re&&(C(ee==null?void 0:ee.phase),k(M??null))}),()=>{re=!1}},[a,j,x]);const le=b.useCallback(async()=>{await(Z==null?void 0:Z.syncOnce())},[Z]),de=b.useCallback(async()=>{!a||!x||(await HA(a,x),await x0(a,x),await LA(a,x),C(void 0),B(void 0),k(null),T.invalidateQueries({queryKey:["notes",x]}),T.invalidateQueries({queryKey:["notesForDateViews",x]}),T.invalidateQueries({queryKey:["notesForPathTree",x]}),T.invalidateQueries({queryKey:["tags",x]}))},[a,x,T]),ye=b.useMemo(()=>({enabled:j,state:j2(j,f,_,H),progress:O,lastSyncedAt:H,syncNow:le,clearOffline:de}),[j,f,_,O,H,le,de]),we=b.useMemo(()=>({db:a,blobStore:i,engine:F,isOnline:f,isDraining:m,lastSyncedAt:y,mirror:ye}),[a,i,F,f,m,y,ye]);return c.jsx(O0.Provider,{value:we,children:t})}const zt={pinned:"pinned",archived:"archived",captureVoice:"capture",captureText:"capture",view:"view"},ND=["pinned","archived","captureVoice","captureText","view"],A2="lens:tag-roles:";function _2(t){return A2+t}function Fi(t,a){if(typeof t!="string")return a;const r=t.trim().replace(/^#/,"");return r.length>0?r:a}function zo(t){if(!t||typeof t!="object")return{...zt};const a=t;return{pinned:Fi(a.pinned,zt.pinned),archived:Fi(a.archived,zt.archived),captureVoice:Fi(a.captureVoice,zt.captureVoice),captureText:Fi(a.captureText,zt.captureText),view:Fi(a.view,zt.view)}}function R2(t){try{const a=localStorage.getItem(_2(t));return a?zo(JSON.parse(a)):{...zt}}catch{return{...zt}}}const _r=".parachute/notes/settings",M0=1,sa={schemaVersion:M0,tagRoles:{...zt}};function mh(t){if(!t||typeof t!="object")return{...sa,tagRoles:{...zt}};const a=t,r=typeof a.schemaVersion=="number"?a.schemaVersion:M0,i=zo(a.tagRoles);return{schemaVersion:r,tagRoles:i}}function mm(t){if(!t||!t.metadata||typeof t.metadata!="object")return{...sa,tagRoles:{...zt}};const a=t.metadata;return mh(a.notes??a.lens)}function na(t,a){return{schemaVersion:a.schemaVersion??t.schemaVersion,tagRoles:a.tagRoles?zo({...t.tagRoles,...a.tagRoles}):t.tagRoles}}function C2(t,a){if(!t)return{...a,tagRoles:a.tagRoles?{...a.tagRoles}:void 0};const r={};return(a.schemaVersion!==void 0||t.schemaVersion!==void 0)&&(r.schemaVersion=a.schemaVersion??t.schemaVersion),(a.tagRoles||t.tagRoles)&&(r.tagRoles={...t.tagRoles??{},...a.tagRoles??{}}),r}const O2="notes:settings:";function D0(t){return O2+t}function k0(t){return{settings:t??{...sa,tagRoles:{...zt}},serverSettings:t,serverUpdatedAt:null,noteExists:!1,dirtyPatch:null}}function M2(t){try{const a=localStorage.getItem(D0(t));if(!a)return null;const r=JSON.parse(a);if(!r||typeof r!="object")return null;const i=r.serverSettings===null?null:r.serverSettings?mh(r.serverSettings):null,u=r.dirtyPatch??null,f=i??{...sa,tagRoles:{...zt}};return{settings:u?na(f,u):mh(r.settings??f),serverSettings:i,serverUpdatedAt:typeof r.serverUpdatedAt=="string"?r.serverUpdatedAt:null,noteExists:r.noteExists===!0,dirtyPatch:u}}catch{return null}}function Ju(t,a){try{localStorage.setItem(D0(t),JSON.stringify(a))}catch{}}function D2(t){if(typeof localStorage>"u"||!localStorage.getItem(`lens:tag-roles:${t}`))return null;const r={tagRoles:R2(t)};return{settings:na(sa,r),serverSettings:null,serverUpdatedAt:null,noteExists:!1,dirtyPatch:r}}function k2(t){const a=M2(t);if(a)return a;const r=D2(t);return r||k0(null)}async function ub(t,a,r,i){if(!a.noteExists){const u=na(a.serverSettings??sa,r);try{const f=await t.createNote({path:_r,content:"",metadata:{notes:u}},{signal:i});return{server:u,serverUpdatedAt:f.updatedAt??f.createdAt??null,noteExists:!0}}catch(f){if(f instanceof Wn||L2(f))return bd(t,r,i);throw f}}if(a.serverUpdatedAt&&a.serverSettings)try{const u=na(a.serverSettings,r),f=await t.updateNote(_r,{metadata:{notes:u},if_updated_at:a.serverUpdatedAt},{signal:i});return{server:u,serverUpdatedAt:f.updatedAt??a.serverUpdatedAt,noteExists:!0}}catch(u){if(u instanceof Wn)return bd(t,r,i);throw u}return bd(t,r,i)}async function bd(t,a,r){let i=null;try{i=await t.getNote(_r)}catch(p){if(!(p instanceof Sl))throw p;i=null}if(!i){const p=na(sa,a),y=await t.createNote({path:_r,content:"",metadata:{notes:p}},{signal:r});return{server:p,serverUpdatedAt:y.updatedAt??y.createdAt??null,noteExists:!0}}const u=mm(i),f=na(u,a),h=i.updatedAt??i.createdAt,m=await t.updateNote(_r,{metadata:{notes:f},if_updated_at:h},{signal:r});return{server:f,serverUpdatedAt:m.updatedAt??h??null,noteExists:!0}}function L2(t){if(!(t instanceof Error))return!1;const a=t.message.toLowerCase();return a.includes("already exists")||a.includes("duplicate")||a.includes("conflict")}function U2(t){const a=ke(),r=pt(),{db:i}=Zt(),u=b.useMemo(()=>t?k2(t):k0(null),[t]),[f,h]=b.useState(u),[m,p]=b.useState(a?"loading":"offline");b.useEffect(()=>{h(u),p(a?"loading":"offline")},[u,a]);const y=lt({queryKey:["vault-settings",t],enabled:!!t&&!!a,queryFn:async()=>{try{const v=await a.getNote(_r);return v?{server:mm(v),serverUpdatedAt:v.updatedAt??v.createdAt??null,noteExists:!0}:{server:null,serverUpdatedAt:null,noteExists:!1}}catch(v){if(!(v instanceof Sl))throw v;return{server:null,serverUpdatedAt:null,noteExists:!1}}},retry:!1,staleTime:6e4});b.useEffect(()=>{if(!t||!a||!y.data)return;const v=y.data;if(f.dirtyPatch){const T=f.dirtyPatch;(async()=>{try{const j=await ub(a,{serverSettings:v.server,serverUpdatedAt:v.serverUpdatedAt,noteExists:v.noteExists},T),_={settings:j.server,serverSettings:j.server,serverUpdatedAt:j.serverUpdatedAt,noteExists:!0,dirtyPatch:null};h(_),Ju(t,_),p("synced"),r.invalidateQueries({queryKey:["vault-settings",t]})}catch{p("offline")}})();return}const x=v.server?{settings:v.server,serverSettings:v.server,serverUpdatedAt:v.serverUpdatedAt,noteExists:v.noteExists,dirtyPatch:null}:{settings:f.settings,serverSettings:null,serverUpdatedAt:null,noteExists:!1,dirtyPatch:null};h(x),Ju(t,x),p("synced")},[t,a,y.data]),b.useEffect(()=>{y.isError&&p("offline")},[y.isError]);const S=b.useCallback(async v=>{if(!t)return;const x=C2(f.dirtyPatch,v),j={settings:na(f.serverSettings??sa,x),serverSettings:f.serverSettings,serverUpdatedAt:f.serverUpdatedAt,noteExists:f.noteExists,dirtyPatch:x};if(h(j),Ju(t,j),!a){p("offline");return}const _=i?async()=>(await El(i,{kind:"update-settings",notePath:_r,patch:x,baselineUpdatedAt:f.serverUpdatedAt},{vaultId:t}),null):null;try{const C=await Ho(O=>ub(a,{serverSettings:f.serverSettings,serverUpdatedAt:f.serverUpdatedAt,noteExists:f.noteExists},v,O),_);if(C){const O={settings:C.server,serverSettings:C.server,serverUpdatedAt:C.serverUpdatedAt,noteExists:!0,dirtyPatch:null};h(O),Ju(t,O),p("synced"),r.invalidateQueries({queryKey:["vault-settings",t]})}else p(Ys()?"offline":"queued")}catch(C){C instanceof Wn?p("conflict"):p("offline")}},[t,a,i,f,r]);return{settings:f.settings,update:S,status:m}}function wl(t){const{settings:a,update:r}=U2(t),i=b.useCallback(u=>{if(!t)return;const f=u??{...zt};r({tagRoles:zo(f)})},[t,r]);return{roles:a.tagRoles,setRoles:i}}const L0="auth-halted",z2=600*1e3;function V2(t){const a=2**t*1e3;return Math.min(a,z2)}async function El(t,a,r){const i={id:crypto.randomUUID(),vaultId:r.vaultId,mutation:a,createdAt:Date.now(),attemptCount:0,nextAttemptAt:0,status:"pending"},u=await t.add("pending",i);return{...i,seq:u}}async function U0(t,a){return a?t.getAllFromIndex("pending","by-vault",a):t.getAll("pending")}async function B2(t){const a=t.now??(()=>Date.now()),r={drained:0,stashed:0,deferred:0,authHalted:!1};for(;;){const i=await H2(t.db,t.vaultId,a());if(!i)break;try{await q2(t,i),await t.db.delete("pending",i.seq),r.drained+=1}catch(u){if(u instanceof Uo){await Gs(t.db,L0,{vaultId:t.vaultId,at:a(),message:u.message}),r.authHalted=!0,await ob(t.db,i,u,a),r.deferred+=1;break}if(u instanceof Wn){await t.db.put("pending",{...i,status:"needs-human",lastError:`Conflict: current=${u.currentUpdatedAt??"?"} expected=${u.expectedUpdatedAt??"?"}`,attemptCount:i.attemptCount+1}),r.stashed+=1;continue}if(u instanceof pr){await t.db.put("pending",{...i,attemptCount:i.attemptCount+1,lastError:u.message,nextAttemptAt:a()+5e3}),r.deferred+=1;break}if(u instanceof Sl){await t.db.delete("pending",i.seq),r.drained+=1;continue}await ob(t.db,i,u,a),r.deferred+=1;break}}return r}async function H2(t,a,r){let u=await t.transaction("pending","readonly").store.openCursor();for(;u;){const f=u.value;if(f.vaultId===a&&f.status==="pending"&&f.nextAttemptAt<=r)return f;u=await u.continue()}return null}async function ob(t,a,r,i){const u=a.attemptCount+1;await t.put("pending",{...a,attemptCount:u,nextAttemptAt:i()+V2(u),lastError:r instanceof Error?r.message:String(r)})}class pr extends Error{}async function q2(t,a){var i,u,f;const r=a.mutation;switch(r.kind){case"create-note":{const h=await t.client.createNote(r.payload);await oA(t.db,r.localId,h.id,t.vaultId),await((i=t.mirror)==null?void 0:i.localIdLanded(t.vaultId,r.localId,h));return}case"update-note":{const h=await bs(t.db,r.targetId,t.vaultId);if(!h)throw new pr(`Awaiting local id ${r.targetId}`);const m=await I2(t.client,h,r.payload,r.baselineUpdatedAt);m&&await((u=t.mirror)==null?void 0:u.upsert(t.vaultId,m));return}case"update-settings":{await K2(t.client,r.notePath,r.patch);return}case"delete-note":{const h=await bs(t.db,r.targetId,t.vaultId);if(!h)throw new pr(`Awaiting local id ${r.targetId}`);await t.client.deleteNote(h),await((f=t.mirror)==null?void 0:f.remove(t.vaultId,h));return}case"upload-attachment":{const h=await t.blobStore.get(r.blobId);if(!h)throw new pr(`Missing blob ${r.blobId}`);const m=h.mimeType||r.mimeType,p=new File([h.data],r.filename,{type:m}),y=await t.client.uploadStorageFile(p);await fA(t.db,r.blobId,y.path,t.vaultId),await t.blobStore.delete(r.blobId);return}case"link-attachment":{const h=await bs(t.db,r.noteId,t.vaultId);if(!h)throw new pr(`Awaiting local id ${r.noteId}`);let m=r.pathRef;if(g0(r.pathRef)&&(m=await cA(t.db,r.pathRef,t.vaultId),!m))throw new pr(`Awaiting blob ${y0(r.pathRef)}`);await t.client.linkAttachment(h,{path:m,mimeType:r.mimeType,...r.transcribe?{transcribe:!0}:{},...r.segment_index!==void 0?{segment_index:r.segment_index}:{}});return}case"delete-attachment":{const h=await bs(t.db,r.noteId,t.vaultId);if(!h)throw new pr(`Awaiting local id ${r.noteId}`);await t.client.deleteAttachment(h,r.attachmentId);return}}}async function $2(t,a){const r=await t.get("pending",a);r&&await t.put("pending",{...r,status:"pending",attemptCount:0,nextAttemptAt:0,lastError:void 0})}async function Q2(t,a){await t.delete("pending",a)}const xd=3,cb=3;async function I2(t,a,r,i){let u=i;for(let f=0;f<=cb;f++){const h=u?{...r,if_updated_at:u}:{...r};try{return await t.updateNote(a,h)}catch(m){if(m instanceof Wn&&f<cb){if(m.currentUpdatedAt)u=m.currentUpdatedAt;else{const p=await t.getNote(a);if(!p)throw new Sl(`Note ${a} disappeared during retry`);u=p.updatedAt??p.createdAt}continue}if(m instanceof Wn)return await t.updateNote(a,{...r,force:!0});throw m}}}async function K2(t,a,r){for(let i=0;i<=xd;i++){let u=null;try{u=await t.getNote(a)}catch(p){if(!(p instanceof Sl))throw p}if(!u)try{await t.createNote({path:a,content:"",metadata:{notes:na(sa,r)}});return}catch(p){if(p instanceof Wn&&i<xd)continue;throw p}const f=mm(u),h=na(f,r),m=u.updatedAt??u.createdAt;try{await t.updateNote(a,{metadata:{notes:h},if_updated_at:m});return}catch(p){if(p instanceof Wn&&i<xd)continue;if(p instanceof Wn){await t.updateNote(a,{metadata:{notes:h},force:!0});return}throw p}}}async function G2(t,a){const r=await U0(t,a),i=t.transaction("pending","readwrite");for(const u of r)await i.store.delete(u.seq);return await i.done,r.length}let Y2=1;const aa=Ia(t=>({toasts:[],push(a,r,i){const u=Y2++;return t(f=>({toasts:[...f.toasts,{id:u,message:a,tone:r??"info",durationMs:i==null?void 0:i.durationMs}]})),u},dismiss(a){t(r=>({toasts:r.toasts.filter(i=>i.id!==a)}))},clear(){t({toasts:[]})}})),P2=/_Transcript pending(?: \(part \d+\))?\._/,F2=/_Transcription unavailable(?: \(part \d+\))?\._/,X2=/_Monthly voice limit reached[^\n]*\._/;function z0(t){var r;const a={pending:0,failed:0,done:0,total:0};for(const i of t??[]){const u=(r=i.metadata)==null?void 0:r.transcribe_status;(u==="pending"||u==="done"||u==="failed")&&(a[u]+=1,a.total+=1)}return a}function Z2(t){const a=t.content??"",r=X2.test(a),{pending:i,failed:u,total:f}=z0(t.attachments);return f>0?i>0?"pending":u>0?r?"voice-limit":"failed":"none":P2.test(a)?"pending":r?"voice-limit":F2.test(a)?"failed":"none"}function AD(t){const{pending:a,failed:r,done:i,total:u}=z0(t.attachments);return u<=1||a===0?null:{done:i+r,total:u}}function J2(t){return Z2(t)==="pending"}function W2(t){var i,u;const a=(i=t.attachments)==null?void 0:i.map(f=>{var h;return((h=f.metadata)==null?void 0:h.transcribe_status)==="failed"?{...f,metadata:{...f.metadata,transcribe_status:"pending"}}:f}),r=(u=t.content)==null?void 0:u.replace(/_Transcription unavailable( \(part \d+\))?\._/g,(f,h)=>`_Transcript pending${h??""}._`);return{...t,...a?{attachments:a}:{},...r?{content:r}:{}}}const yo="lens:auth-halt:";function fb(){const t={};if(typeof localStorage>"u")return t;try{for(let a=0;a<localStorage.length;a++){const r=localStorage.key(a);if(!(r!=null&&r.startsWith(yo)))continue;const i=localStorage.getItem(r);if(i)try{const u=JSON.parse(i);u!=null&&u.vaultId&&(t[u.vaultId]=u)}catch{}}}catch{}return t}const Rr=Ia(t=>({byVault:fb(),markHalted(a,r){const i={vaultId:a,reason:r,at:Date.now()};try{localStorage.setItem(yo+a,JSON.stringify(i))}catch{}t(u=>({byVault:{...u.byVault,[a]:i}}))},clearHalt(a){try{localStorage.removeItem(yo+a)}catch{}t(r=>{if(!(a in r.byVault))return r;const{[a]:i,...u}=r.byVault;return{byVault:u}})},reloadFromStorage(){t({byVault:fb()})}})),e_=yo,t_=mx;function Vo({queryKey:t,params:a,client:r,enabled:i=!0}){const u=pt(),[f,h]=b.useState(!1),m=a.toString(),p=JSON.stringify(t);return b.useEffect(()=>{if(h(!1),!i||!r)return;const y=new URLSearchParams(m);if(!t_(y))return;let S=!0;const v=zE(r,y),x=v.getList();let T=null;const j=()=>{if(!S)return;const C=v.getState();h(C.status==="live"),C.list!==x&&C.list!==T&&(T=C.list,u.setQueryData(t,C.list))},_=v.subscribe(j);return j(),()=>{S=!1,h(!1),_(),v.close()}},[r,m,p,i,u]),{isLive:f}}const gr=50,n_={search:"",tags:[],tagMatch:"any",pathPrefix:"",sort:"desc",limit:gr,offset:0};function a_(t){const a=new URLSearchParams,r=t.search.trim();r&&a.set("search",r),t.tags.length>0&&(a.set("tag",t.tags.join(",")),t.tags.length>1&&a.set("tag_match",t.tagMatch));const i=t.pathPrefix.trim();return i&&a.set("path_prefix",i),t.hasTags===!1?a.set("has_tags","false"):t.hasTags===!0&&a.set("has_tags","true"),t.hasLinks===!1?a.set("has_links","false"):t.hasLinks===!0&&a.set("has_links","true"),a.set("sort",t.sort),a.set("limit",String(t.limit)),t.offset>0&&a.set("offset",String(t.offset)),a}function r_(t){return t.search.trim().length>0||t.tags.length>0||t.pathPrefix.trim().length>0}const s_=3,Wu=[1e3,2e3,4e3,8e3,16e3,3e4];function i_(t){return{vaultId:t,state:"healthy",consecutiveFailures:0,lastErrorAt:null,lastErrorReason:null,nextProbeAt:null,backoffIndex:0}}function l_(t){const a=Math.min(t,Wu.length-1);return Wu[a]??Wu[Wu.length-1]??3e4}const Dr=Ia(t=>({byVault:{},reportSignal(a,r,i){t(u=>{const f=u.byVault[a]??i_(a);if(r==="healthy"){if(!(a in u.byVault))return u;const{[a]:v,...x}=u.byVault;return{byVault:x}}const h=f.consecutiveFailures+1,m=f.backoffIndex+1,p=h>=s_?"down":"retrying",y=Date.now(),S={vaultId:a,state:p,consecutiveFailures:h,lastErrorAt:y,lastErrorReason:i??null,nextProbeAt:y+l_(m),backoffIndex:m};return{byVault:{...u.byVault,[a]:S}}})},resetToHealthy(a){t(r=>{if(!(a in r.byVault))return r;const{[a]:i,...u}=r.byVault;return{byVault:u}})}})),u_="Parachute Notes";async function V0(t,a=fetch.bind(globalThis)){return fE(t,a)}async function o_(t,a,r=fetch.bind(globalThis)){return dE(t,{clientName:u_,redirectUri:a},r)}const c_="/oauth/callback",f_="vault:read vault:write";function d_(){return pl()}function h_(t=window.location.origin){return`${t.replace(/\/$/,"")}${d_()}${c_}`}function m_(t){let a;try{a=new URL(kh(t))}catch{return}const r=a.pathname.match(/^\/vault\/([^/]+)$/);if(r!=null&&r[1])try{return decodeURIComponent(r[1])}catch{return}}async function pm(t,a=f_,r=fetch.bind(globalThis),i={}){const u=kh(t),f=h_(),h=await V0(u,r);let m=Wj(h.issuer,f);m||(m=(await o_(h.registration_endpoint,f,r)).client_id,eN(h.issuer,f,m));const p=gE(),y=await yE(p),S=vE(),v={issuerUrl:u,issuer:h.issuer,tokenEndpoint:h.token_endpoint,clientId:m,codeVerifier:p,state:S,redirectUri:f,scope:a,startedAt:new Date().toISOString(),...i.priorHaltedVaultId?{priorHaltedVaultId:i.priorHaltedVaultId}:{},...i.redirect?{redirect:i.redirect}:{}};Jj(v);const x=new URL(h.authorization_endpoint);if(x.searchParams.set("response_type","code"),x.searchParams.set("client_id",m),x.searchParams.set("redirect_uri",f),x.searchParams.set("code_challenge",y),x.searchParams.set("code_challenge_method","S256"),x.searchParams.set("state",S),x.searchParams.set("scope",a),i.params)for(const[T,j]of Object.entries(i.params))x.searchParams.has(T)||x.searchParams.set(T,j);if(!x.searchParams.has("vault")){const T=m_(u);T&&x.searchParams.set("vault",T)}return{authorizeUrl:x.toString(),pending:v}}function p_(t){if(typeof t!="string"||t.length===0)return;let a;try{a=new URL(t)}catch{return}if(!(a.protocol!=="http:"&&a.protocol!=="https:"))return t}function g_(t){let a;try{a=JSON.parse(t)}catch{return null}if(typeof a!="object"||a===null)return null;const r=a;if(r.error!=="invalid_client")return null;const i=p_(r.approve_url);return i?{approveUrl:i}:null}async function _D(t,a,r=fetch.bind(globalThis)){const i=Zj();if(!i)throw new Error("No pending OAuth flow. Start the connect flow from the vault page.");if(i.state!==a)throw Fu(),new Error("OAuth state mismatch. The flow was likely interrupted; please try again.");const u=new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:i.codeVerifier,client_id:i.clientId,redirect_uri:i.redirectUri}),f=await r(i.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:u.toString()});if(!f.ok){const m=await f.text();Fu();const p=g_(m);throw p?new xE(p.approveUrl):new Error(`Token exchange failed (${f.status}): ${m}`)}const h=await f.json();if(!h.access_token)throw Fu(),new Error("Token response missing access_token");return Fu(),{pending:i,token:h}}async function y_(t,a=fetch.bind(globalThis)){const r=new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken,client_id:t.clientId}),i=await a(t.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:r.toString()});if(!i.ok){const f=await i.text();throw new cx(i.status,f)}const u=await i.json();if(!u.access_token)throw new Error("Refresh response missing access_token");return u}const Sd=new Map;async function v_(t){const a=Sd.get(t);if(a)return a;const r=b_(t).finally(()=>{Sd.delete(t)});return Sd.set(t,r),r}async function b_(t){const a=ae.getState().vaults[t];if(a){const{isHostedVaultRecord:i,remintHostedVault:u}=await Qe(async()=>{const{isHostedVaultRecord:f,remintHostedVault:h}=await Promise.resolve().then(()=>vN);return{isHostedVaultRecord:f,remintHostedVault:h}},[]);if(i(a.clientId)){try{await u(a.name);const f=Ls(t);if(f!=null&&f.accessToken)return Rr.getState().clearHalt(t),f.accessToken}catch{}return null}}const r=Ls(t);if(!(r!=null&&r.refreshToken)||!(a!=null&&a.tokenEndpoint)||!a.clientId)return null;try{const i=await y_({tokenEndpoint:a.tokenEndpoint,clientId:a.clientId,refreshToken:r.refreshToken}),u=bE(i);return!u.refreshToken&&r.refreshToken&&(u.refreshToken=r.refreshToken),Qx(t,u),Rr.getState().clearHalt(t),u.accessToken}catch(i){if(i instanceof cx&&i.status>=400&&i.status<500){const u=i.oauthError==="invalid_grant"||i.status===400||i.status===401?"Your vault session expired. Reconnect to resume syncing.":`Token refresh failed (${i.status}). Reconnect to resume syncing.`;Rr.getState().markHalted(t,u)}return null}}function ke(){const t=ae(r=>r.getActiveVault()),a=ae(r=>r.activeVaultId);return b.useMemo(()=>{if(!t||!a)return null;const r=Ls(a);return r?new KA({vaultUrl:t.url,accessToken:r.accessToken,onAuthError:()=>v_(a),onAuthRevoked:i=>Rr.getState().markHalted(a,`Vault rejected the current session (${i}).`),onReachability:(i,u)=>Dr.getState().reportSignal(a,i,u)}):null},[t,a])}async function gm(t,a,r,i){const u=()=>t&&a?j0(t,a,r):Promise.resolve(null);if(t&&a&&Ys()){const f=await u();if(f)return f}try{return await i()}catch(f){if(f instanceof il){const h=await u();if(h)return h}throw f}}async function x_(t,a,r,i){const u=()=>t&&a&&r?T0(t,a,r):Promise.resolve(void 0);if(t&&a&&r&&Ys()){const f=await u();if(f)return f}try{return await i()}catch(f){if(f instanceof il){const h=await u();if(h)return h}throw f}}async function S_(t,a,r){const i=()=>t&&a?S0(t,a):Promise.resolve(void 0);if(t&&a&&Ys()){const u=await i();if(u)return u}try{return await r()}catch(u){if(u instanceof il){const f=await i();if(f)return f}throw u}}function ym(t,a,r,i){const[u,f]=b.useState(void 0),h=r.toString();return b.useEffect(()=>{if(!i||!t||!a){f(void 0);return}let m=!0;return j0(t,a,new URLSearchParams(h)).then(p=>{m&&p&&f(p)}).catch(()=>{}),()=>{m=!1}},[i,t,a,h]),u}function w_(t,a,r,i){const[u,f]=b.useState(void 0);return b.useEffect(()=>{if(f(void 0),!i||!t||!a||!r)return;let h=!0;return T0(t,a,r).then(m=>{h&&m&&f(m)}).catch(()=>{}),()=>{h=!1}},[i,t,a,r]),u}function E_(t,a,r){const[i,u]=b.useState(void 0);return b.useEffect(()=>{if(!r||!t||!a){u(void 0);return}let f=!0;return S0(t,a).then(h=>{f&&h&&u(h)}).catch(()=>{}),()=>{f=!1}},[r,t,a]),i}function B0(){const t=ke(),a=ae(r=>r.activeVaultId);return lt({queryKey:["vaultInfo",a],enabled:!!t,queryFn:()=>t.vaultInfo(!0),staleTime:3e4})}function RD(){return H0().capability}function H0(){var m,p,y;const t=ke(),a=ae(S=>S.activeVaultId),r=B0(),i=!!t&&r.isSuccess&&((m=r.data)==null?void 0:m.transcription)===void 0,u=lt({queryKey:["vaultLanding",a],enabled:i,queryFn:()=>t.vaultLanding(),staleTime:5*6e4,retry:!1}),f=r.isSuccess||r.isError,h=!i||u.isSuccess||u.isError;return{capability:((p=r.data)==null?void 0:p.transcription)??((y=u.data)==null?void 0:y.transcription),settled:f&&h}}function T_(t,a){const r=ke(),i=ae(v=>v.activeVaultId),{db:u}=Zt(),f=ra(),h=a==null?void 0:a.live,m=b.useMemo(()=>["notes",i,t],[i,t]),p=b.useMemo(()=>{const v=a_(t);return v.set("include_content","false"),v},[t]),{isLive:y}=Vo({queryKey:m,params:p,client:r,enabled:h}),S=ym(u,i,p,f);return lt({queryKey:m,enabled:!!r,queryFn:()=>f?gm(u,i,p,()=>r.queryNotes(p)):r.queryNotes(p),staleTime:y?Number.POSITIVE_INFINITY:1e4,refetchInterval:y?!1:3e4,refetchOnWindowFocus:!y,placeholderData:f?v=>v??S:t0,networkMode:f?"always":"online"})}const Bo=5e3;function j_(t){const a=ke(),r=ae(i=>i.activeVaultId);return lt({queryKey:["allNotesForSwitcher",r],enabled:!!a&&t,queryFn:()=>{const i=new URLSearchParams;return i.set("include_content","true"),i.set("sort","desc"),i.set("limit",String(Bo)),a.queryNotes(i)},staleTime:6e4})}function N_(){const t=ke(),a=ae(p=>p.activeVaultId),{db:r}=Zt(),i=ra(),u=b.useMemo(()=>["notesForDateViews",a],[a]),f=b.useMemo(()=>{const p=new URLSearchParams;return p.set("sort","desc"),p.set("limit",String(Bo)),p.set("include_content","false"),p},[]),{isLive:h}=Vo({queryKey:u,params:f,client:t}),m=ym(r,a,f,i);return lt({queryKey:u,enabled:!!t,queryFn:()=>i?gm(r,a,f,()=>t.queryNotes(f)):t.queryNotes(f),staleTime:h?Number.POSITIVE_INFINITY:6e4,refetchInterval:h?!1:6e4,refetchOnWindowFocus:!h,placeholderData:i?p=>p??m:void 0,networkMode:i?"always":"online"})}function A_(t){const a=ke(),r=ae(m=>m.activeVaultId),{db:i}=Zt(),u=ra(),f=b.useMemo(()=>{const m=new URLSearchParams;return m.set("sort","desc"),m.set("limit",String(Bo)),m},[]),h=ym(i,r,f,u&&t);return lt({queryKey:["notesForPathTree",r],enabled:!!a&&t,queryFn:()=>u?gm(i,r,f,()=>a.queryNotes(f)):a.queryNotes(f),staleTime:6e4,placeholderData:u?m=>m??h:void 0,networkMode:u?"always":"online"})}function CD(){const t=ke(),a=ae(r=>r.activeVaultId);return lt({queryKey:["allNotesWithLinks",a],enabled:!!t,queryFn:()=>{const r=new URLSearchParams;return r.set("include_links","true"),r.set("sort","desc"),r.set("limit",String(Bo)),t.queryNotes(r)},staleTime:6e4})}function __(){const t=ke(),a=ae(f=>f.activeVaultId),{db:r}=Zt(),i=ra(),u=E_(r,a,i);return lt({queryKey:["tags",a],enabled:!!t,queryFn:()=>i?S_(r,a,()=>t.listTags()):t.listTags(),staleTime:6e4,placeholderData:i?f=>f??u:void 0,networkMode:i?"always":"online"})}function R_(){const t=ke(),a=ae(r=>r.activeVaultId);return lt({queryKey:["tags",a,"with-schema"],enabled:!!t,queryFn:()=>t.listTags({includeSchema:!0}),staleTime:6e4})}function OD(t){const a=ke(),r=ae(i=>i.activeVaultId);return lt({queryKey:["tag",r,t],enabled:!!a&&!!t,queryFn:()=>a.getTag(t),staleTime:3e4})}function MD(){const t=ke(),a=ae(i=>i.activeVaultId),r=pt();return xn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.updateTag(i.name,i.payload)},onSuccess:(i,u)=>{r.setQueryData(["tag",a,u.name],i),r.invalidateQueries({queryKey:["tags",a]})}})}function C_(t,a){return t&&zs(t)&&!(a&&!zs(a.id))?2e3:a&&J2(a)?4e3:!1}function O_(t){const a=ke(),r=ae(m=>m.activeVaultId),{db:i}=Zt(),u=pt(),f=ra(),h=w_(i,r,t,f);return lt({queryKey:["note",r,t],enabled:!!a&&!!t,queryFn:()=>{const m=async()=>{if(t&&zs(t)){const p=i&&r?await bs(i,t,r):null;if(!p){const y=u.getQueryData(["note",r,t]);if(y)return y;throw new Error("This note is still syncing — try again in a moment.")}return a.getNote(p,{includeLinks:!0,includeAttachments:!0})}return a.getNote(t,{includeLinks:!0,includeAttachments:!0})};return f?x_(i,r,t,m):m()},refetchInterval:m=>C_(t,m.state.data),staleTime:1e4,placeholderData:f?h:void 0,networkMode:f?"always":"online"})}const M_=8e3;function Ys(){return typeof navigator<"u"&&navigator.onLine===!1}async function Ho(t,a){if(a&&Ys())return a();const r=new AbortController,i=setTimeout(()=>r.abort(new Error("offline-timeout")),M_);try{return await t(r.signal)}catch(u){if(a)return a();throw u}finally{clearTimeout(i)}}function D_(t,a){const r=new Date().toISOString();return{id:a,path:t.path,createdAt:r,updatedAt:r,tags:t.tags,metadata:t.metadata,content:t.content}}async function k_(t,a,r){const i=uA();return await El(t,{kind:"create-note",localId:i,payload:r},{vaultId:a}),D_(r,i)}async function L_(t,a,r,i,u){const f=u==null?void 0:u.updatedAt;return await El(t,{kind:"update-note",targetId:r,payload:i,...f&&{baselineUpdatedAt:f}},{vaultId:a}),{...u??{id:r,createdAt:new Date().toISOString()},...i.content!==void 0&&{content:i.content},...i.path!==void 0&&{path:i.path},...i.metadata!==void 0&&{metadata:i.metadata},updatedAt:new Date().toISOString()}}function U_(t){const a=ke(),r=ae(f=>f.activeVaultId),{db:i}=Zt(),u=pt();return xn({mutationFn:async f=>{if(!t)throw new Error("No note id");return Ho(m=>{if(!a)throw new Error("No active vault");return a.updateNote(t,f,{signal:m})},i&&r?()=>{const m=u.getQueryData(["note",r,t]);return L_(i,r,t,f,m)}:null)},onSuccess:f=>{u.setQueryData(["note",r,t],f),u.invalidateQueries({queryKey:["notes",r]}),u.invalidateQueries({queryKey:["tags",r]}),f!=null&&f.id&&f.id!==t&&u.setQueryData(["note",r,f.id],f),i&&r&&f&&fm(i,r,f)}})}function z_(){const t=ke(),a=ae(u=>u.activeVaultId),{db:r}=Zt(),i=pt();return xn({mutationFn:async u=>Ho(h=>{if(!t)throw new Error("No active vault");return t.createNote(u,{signal:h})},r&&a?()=>k_(r,a,u):null),onSuccess:u=>{i.setQueryData(["note",a,u.id],u),i.invalidateQueries({queryKey:["notes",a]}),i.invalidateQueries({queryKey:["notesForDateViews",a]}),i.invalidateQueries({queryKey:["hasUserAuthoredNote",a]}),i.invalidateQueries({queryKey:["tags",a]}),i.invalidateQueries({queryKey:["vaultInfo",a]}),r&&a&&fm(r,a,u)}})}function DD(){const t=ke();return xn({mutationFn:async a=>{if(!t)throw new Error("No active vault");return t.uploadStorageFile(a.file,{onProgress:a.onProgress,signal:a.signal})}})}function kD(){const t=ke(),a=ae(i=>i.activeVaultId),r=pt();return xn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.linkAttachment(i.noteId,{path:i.path,mimeType:i.mimeType})},onSuccess:(i,u)=>{r.invalidateQueries({queryKey:["note",a,u.noteId]})}})}function LD(){const t=ke(),a=ae(u=>u.activeVaultId),r=pt(),i=aa(u=>u.push);return xn({mutationFn:async u=>{if(!t)throw new Error("No active vault");await t.retryTranscription(u.serverId)},onMutate:async({cacheId:u})=>{const f=["note",a,u];await r.cancelQueries({queryKey:f});const h=r.getQueryData(f);return h&&r.setQueryData(f,W2(h)),{prev:h,key:f}},onError:(u,f,h)=>{h!=null&&h.prev&&h.key&&r.setQueryData(h.key,h.prev),i("Couldn't retry transcription right now.","error")},onSettled:(u,f,{cacheId:h})=>{r.invalidateQueries({queryKey:["note",a,h]})}})}function UD(){const t=ke(),a=ae(u=>u.activeVaultId),{db:r}=Zt(),i=pt();return xn({mutationFn:async u=>{if(Ys()&&r&&a)return await El(r,{kind:"delete-attachment",noteId:u.noteId,attachmentId:u.attachmentId},{vaultId:a}),u;if(!t)throw new Error("No active vault");return await t.deleteAttachment(u.noteId,u.attachmentId),u},onSuccess:u=>{i.invalidateQueries({queryKey:["note",a,u.noteId]})}})}function zD(){const t=ke(),a=ae(i=>i.activeVaultId),r=pt();return xn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.renameTag(i.oldName,i.newName)},onSuccess:()=>{r.invalidateQueries({queryKey:["tags",a]}),r.invalidateQueries({queryKey:["notes",a]}),r.invalidateQueries({queryKey:["vaultInfo",a]})}})}function VD(){const t=ke(),a=ae(i=>i.activeVaultId),r=pt();return xn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.mergeTags(i.sources,i.target)},onSuccess:()=>{r.invalidateQueries({queryKey:["tags",a]}),r.invalidateQueries({queryKey:["notes",a]}),r.invalidateQueries({queryKey:["vaultInfo",a]})}})}function BD(){const t=ke(),a=ae(u=>u.activeVaultId),{db:r}=Zt(),i=pt();return xn({mutationFn:async u=>Ho(async h=>{if(!t)throw new Error("No active vault");return await t.deleteNote(u,{signal:h}),u},r&&a?async()=>(await El(r,{kind:"delete-note",targetId:u},{vaultId:a}),u):null),onSuccess:u=>{i.removeQueries({queryKey:["note",a,u]}),i.invalidateQueries({queryKey:["notes",a]}),i.invalidateQueries({queryKey:["tags",a]}),i.invalidateQueries({queryKey:["vaultInfo",a]}),i.invalidateQueries({queryKey:["hasUserAuthoredNote",a]}),r&&a&&E0(r,a,u)}})}function V_(){b.useEffect(()=>{if(typeof window>"u")return;function t(a){if(a.key===null){ae.setState({vaults:$d(),activeVaultId:Qd()}),Rr.getState().reloadFromStorage();return}if(a.key===ho){ae.setState({activeVaultId:Qd()});return}if(a.key===Gh){ae.setState({vaults:$d()});return}if(a.key.startsWith(e_)){Rr.getState().reloadFromStorage();return}}return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[])}const HD={search:"",tags:[]};function B_(t){const a=new Map;for(const f of t)a.set(f.id,f);const r=new Map,i=new Map;for(const f of t)for(const h of f.links??[]){if(h.sourceId===h.targetId||!a.has(h.sourceId)||!a.has(h.targetId))continue;const m=`${h.sourceId}|${h.targetId}|${h.relationship}`;r.has(m)||(r.set(m,{source:h.sourceId,target:h.targetId,relationship:h.relationship}),i.set(h.sourceId,(i.get(h.sourceId)??0)+1),i.set(h.targetId,(i.get(h.targetId)??0)+1))}return{nodes:t.map(f=>{var m;const h=f.tags??[];return{id:f.id,path:f.path,title:H_(f),tags:h,topTag:h[0],degree:i.get(f.id)??0,summary:typeof((m=f.metadata)==null?void 0:m.summary)=="string"?f.metadata.summary:void 0}}),edges:[...r.values()]}}function H_(t){return t.path?(t.path.split("/").pop()??t.path).replace(/\.md$/i,""):t.id}function qD(t,a){const r=a.search.trim().toLowerCase();return!(r&&![t.path??"",t.title,t.id].join(" ").toLowerCase().includes(r)||a.tags.length>0&&!a.tags.some(u=>t.tags.includes(u)))}function $D(t){const a=new Map;for(const r of t)for(const i of r.tags)a.set(i,(a.get(i)??0)+1);return[...a.entries()].sort((r,i)=>i[1]-r[1]||r[0].localeCompare(i[0])).map(([r])=>r)}function QD(t){if(!t)return"#8a9a7a";let a=0;for(let i=0;i<t.length;i++)a=a*31+t.charCodeAt(i)&16777215;return`hsl(${a%360}, 40%, 55%)`}function q_(t){try{return new URL(t.issuer).origin}catch{return null}}function $_(t){if(typeof t!="object"||t===null)return!1;const a=t;return typeof a.name=="string"&&typeof a.url=="string"&&typeof a.version=="string"}async function Q_(t,a=fetch.bind(globalThis),r){const i=`${t.replace(/\/$/,"")}/.well-known/parachute.json`;let u;try{u=await a(i,{headers:{Accept:"application/json"},signal:r})}catch{return null}if(!u.ok)return null;let f;try{f=await u.json()}catch{return null}if(typeof f!="object"||f===null)return null;const h=f.vaults;return Array.isArray(h)?h.filter($_):null}const I_=15,K_=2;function G_(t){if(!t||t.length===0)return 0;const a=B_([...t]);let r=0;for(const i of a.nodes)i.degree>0&&r++;return r}function Y_(t,a){return t>=K_||a>=I_}function q0(){const t=ae(u=>Object.keys(u.vaults).length),a=ae(u=>u.activeVaultId),r=lt({queryKey:["allNotesWithLinks",a],queryFn:()=>{throw new Error("useMapEarned reads the query cache only")},enabled:!1}),i=b.useMemo(()=>G_(r.data),[r.data]);return Y_(t,i)}const P_="lens:pinned-tags:";function $0(t){return P_+t}function ph(t){return t.trim().replace(/^#/,"")}function vm(t){const a=new Set,r=[];for(const i of t){const u=ph(i);if(!u)continue;const f=u.toLowerCase();a.has(f)||(a.add(f),r.push(u))}return r}function db(t){try{const a=localStorage.getItem($0(t));if(!a)return[];const r=JSON.parse(a);return Array.isArray(r)?vm(r.filter(i=>typeof i=="string")):[]}catch{return[]}}function hb(t,a){try{localStorage.setItem($0(t),JSON.stringify(vm(a)))}catch{}}function F_(t){const[a,r]=b.useState(()=>t?db(t):[]);b.useEffect(()=>{r(t?db(t):[])},[t]);const i=b.useCallback(h=>{if(!t)return;const m=vm(h);hb(t,m),r(m)},[t]),u=b.useCallback(h=>{if(!t)return;const m=ph(h);m&&r(p=>{const S=p.some(v=>v.toLowerCase()===m.toLowerCase())?p.filter(v=>v.toLowerCase()!==m.toLowerCase()):[...p,m];return hb(t,S),S})},[t]),f=b.useCallback(h=>{const m=ph(h).toLowerCase();return a.some(p=>p.toLowerCase()===m)},[a]);return{pinnedTags:a,setPinnedTags:i,togglePin:u,isPinned:f}}const Q0=2500,X_="http://127.0.0.1:1939";async function wd(t,a=Q0,r=fetch.bind(globalThis)){return Z_(t,a,r)}async function Z_(t,a,r){const i=new AbortController,u=setTimeout(()=>i.abort(),a),f=(h,m)=>r(h,{...m??{},signal:i.signal});try{return await V0(t,f),t}catch{return null}finally{clearTimeout(u)}}async function I0(t,a=Q0,r=fetch.bind(globalThis),i=mE()){if(i){const f=await wd(i,a,r);if(f)return f}const u=await wd(t,a,r);if(u)return u;if(J_(t)){const f=await wd(X_,a,r);if(f)return f}return null}function J_(t){let a;try{a=new URL(t)}catch{return!1}return!(!(a.hostname==="localhost"||a.hostname==="127.0.0.1")||a.port==="1939"&&a.protocol==="http:")}function ID(){const t=ae(i=>Object.keys(i.vaults).length>0),[a,r]=b.useState(()=>({status:t?"skipped":"probing",origin:null}));return b.useEffect(()=>{if(t){r({status:"skipped",origin:null});return}let i=!1;return r({status:"probing",origin:null}),I0(window.location.origin).then(u=>{i||r(u?{status:"found",origin:u}:{status:"not-found",origin:null})}),()=>{i=!0}},[t]),a}function W_(t,a){const r=Dr(u=>t?u.byVault[t]:void 0),i=pt();b.useEffect(()=>{if(!t||!a||!r||r.state==="healthy"||r.nextProbeAt===null)return;const u=Date.now(),f=Math.max(0,r.nextProbeAt-u);let h=!1;const m=setTimeout(()=>{h||a.vaultInfo(!1).then(()=>{i.invalidateQueries({queryKey:["notes",t]}),i.invalidateQueries({queryKey:["tags",t]}),i.invalidateQueries({queryKey:["vaultInfo",t]}),i.invalidateQueries({queryKey:["note",t]})}).catch(()=>{})},f);return()=>{h=!0,clearTimeout(m)}},[t,a,r,i])}function el(t){if(t.name)return t.name;try{return new URL(t.url).host}catch{return t.url}}function bm(t){aa.getState().push(`Now in ${t}`,"success")}function eR(t,a={}){const r=ae.getState(),i=r.vaults[t];if(!i)return!1;const u=r.activeVaultId===t;return r.setActiveVault(t),(a.toast??!0)&&!u&&bm(el(i)),!0}const Ed=25,mb=40;async function tR(t){for(let a=0;a<mb;a++){const r=a*Ed,i=new URLSearchParams;i.set("exclude_tag",d0),i.set("sort","desc"),i.set("limit",String(Ed)),i.set("include_content","false"),r>0&&i.set("offset",String(r));const u=await t.queryNotes(i);if(h0(u))return!0;if(u.length<Ed)return!1}throw new Error(`first-note probe: ${mb} full pages without ending the set — offset paging appears broken`)}function nR(){const t=ke(),a=ae(r=>r.activeVaultId);return lt({queryKey:["hasUserAuthoredNote",a],enabled:!!t,queryFn:()=>tR(t),staleTime:6e4})}const aR=["list","board","calendar","gallery","table"];function rR(t){return typeof t=="string"&&aR.includes(t)}const Td={code:"invalid_query_json",message:"This view's query didn't parse — nothing is being filtered out or shown. Open the note to fix it."};function sR(t){return t.path?dm(t.path):t.id}function K0(t){const a=t.metadata??{},r=rR(a.kind)?a.kind:"list",i=[];let u={};if(typeof a.query=="string"&&a.query.trim().length>0)try{const f=JSON.parse(a.query);f&&typeof f=="object"&&!Array.isArray(f)?u=f:(u=null,i.push(Td))}catch{u=null,i.push(Td)}else a.query!==void 0&&a.query!==null&&typeof a.query!="string"&&(u=null,i.push(Td));return{noteId:t.id,path:t.path,title:sR(t),kind:r,query:u,groupBy:typeof a.group_by=="string"?a.group_by:typeof a.lane_by=="string"?a.lane_by:void 0,dateField:typeof a.date_field=="string"?a.date_field:void 0,fields:iR(a.fields),problems:i}}function iR(t){let a=t;if(typeof t=="string"){if(t.trim().length===0)return;try{a=JSON.parse(t)}catch{return}}if(!Array.isArray(a))return;const r=a.filter(i=>typeof i=="string"&&i.trim().length>0);return r.length>0?r:void 0}function lR(t,a){return(t.tags??[]).includes(a)}function uR(t){const a=t.metadata;return(a==null?void 0:a.kind)==="saved-view"}const oR="Views/All notes",cR="Views/Recent",G0="Views/Pinned",Y0="Views/Archive",fR=[oR,cR,G0,Y0],dR="Views/";function KD(t){const a=t.trim().replace(/[/\\]/g,"-");return`${dR}${a||"Untitled view"}`}const hR={pinned:G0,archived:Y0},mR={pinned:"Pinned",archived:"Archive"};function pR(t){return hR[t]}function gR(t,a){const r=t==="pinned"?a.pinned:a.archived;return{noteId:`builtin:${t}`,title:mR[t],kind:"list",query:{tag:r},problems:[]}}function yR(t,a,r){if(a&&lR(a,r.view)){const i=K0(a);if(i.query!==null)return{def:i,isPackNote:!0}}return{def:gR(t,r),isPackNote:!1}}function vR(t){const a=t.split(".");if(a.length<2)return null;const r=a[1];if(!r)return null;try{const i=r.replace(/-/g,"+").replace(/_/g,"/"),u=i+"=".repeat((4-i.length%4)%4),f=atob(u),h=JSON.parse(f),m=h==null?void 0:h.sub;return typeof m=="string"?m:null}catch{return null}}function pb(t){if(typeof t=="string"||Array.isArray(t)&&t.every(a=>typeof a=="string"))return t}function bR(t){const a=[],r={};let i;for(const[f,h]of Object.entries(t))switch(f){case"tag":r.tag=pb(h);break;case"exclude_tags":r.excludeTag=pb(h);break;case"tag_match":(h==="all"||h==="any")&&(r.tagMatch=h);break;case"metadata":h&&typeof h=="object"&&!Array.isArray(h)&&(r.metadata=h);break;case"order_by":typeof h=="string"&&(r.orderBy=h);break;case"sort":(h==="asc"||h==="desc")&&(r.sort=h);break;case"path_prefix":typeof h=="string"&&(r.pathPrefix=h);break;case"limit":typeof h=="number"&&(r.limit=h);break;case"offset":typeof h=="number"&&(r.offset=h);break;case"search":typeof h=="string"&&(i=h);break;default:a.push({code:"unsupported_query_key",message:`This view uses "${f}", which this app can't run yet; results may be broader than intended.`})}let u;try{u=Vd(r)}catch(f){const h=f instanceof Error?f.message.replace(/^buildNotesQuery: /,""):"a malformed value";a.push({code:"unsupported_query_key",message:`This view's metadata filter couldn't run (${h}) — results run without it.`});const{metadata:m,...p}=r;u=Vd(p)}return i&&u.set("search",i),{params:u,problems:a}}function GD(t){return t.addTags.length>0||t.removeExcludes.length>0||!!t.search||!!t.sort}function YD(t){var r;const a=new URLSearchParams;for(const i of t.addTags)a.append("tag",i);for(const i of t.removeExcludes)a.append("noExclude",i);return(r=t.search)!=null&&r.trim()&&a.set("search",t.search.trim()),t.sort&&a.set("sort",t.sort),a}function PD(t){return{addTags:t.getAll("tag"),removeExcludes:t.getAll("noExclude"),search:t.get("search")??void 0,sort:t.get("sort")==="asc"?"asc":t.get("sort")==="desc"?"desc":void 0}}function ll(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(a=>typeof a=="string"):[]}function xR(t,a){if(t===null)return null;const r={...t};if(a.addTags.length>0&&(r.tag=[...ll(t.tag),...a.addTags],r.tag_match="all"),a.removeExcludes.length>0){const i=ll(t.exclude_tags).filter(u=>!a.removeExcludes.includes(u));r.exclude_tags=i}return a.search&&(r.search=a.search),a.sort&&(r.sort=a.sort),r}function P0(t){return t?ll(t.tag):[]}function SR(t){return P0(t)[0]}function FD(t){if(!t)return[];const a=[];for(const r of ll(t.tag))a.push({kind:"tag",value:r,label:`#${r}`});for(const r of ll(t.exclude_tags))a.push({kind:"exclude",value:r,label:`not #${r}`});return typeof t.search=="string"&&t.search&&a.push({kind:"search",label:`"${t.search}"`}),(t.sort==="asc"||t.sort==="desc")&&a.push({kind:"sort",value:t.sort,label:`sorted by ${t.sort==="desc"?"newest":"oldest"}`}),typeof t.path_prefix=="string"&&t.path_prefix&&a.push({kind:"pathPrefix",value:t.path_prefix,label:`in ${t.path_prefix}`}),a}const XD=O_;function wR(t){const a=ke(),r=ae(h=>h.activeVaultId),i=b.useMemo(()=>{const h=new URLSearchParams;return h.set("tag",t),h.set("sort","asc"),h},[t]),u=b.useMemo(()=>["viewList",r,t],[r,t]),{isLive:f}=Vo({queryKey:u,params:i,client:a,enabled:!!t});return lt({queryKey:u,enabled:!!a&&!!t,queryFn:()=>a.queryNotes(i),staleTime:f?Number.POSITIVE_INFINITY:3e4,refetchInterval:f?!1:3e4,refetchOnWindowFocus:!f})}function ER(t,a){const r=ke(),i=ae(h=>h.activeVaultId),u=t?pR(t):null,f=lt({queryKey:["defaultViewNote",i,u],queryFn:async()=>(await r.queryNotes({path:u}))[0]??null,enabled:!!r&&!!u,staleTime:3e4,refetchOnWindowFocus:!1});return b.useMemo(()=>t?yR(t,f.data??null,a):{def:null,isPackNote:!1},[t,f.data,a])}function ZD(t,a,r){const i=ke(),u=ae(v=>v.activeVaultId),f=(r==null?void 0:r.live)??!0,h=b.useMemo(()=>t?xR(t.query,a):null,[t,a]),m=b.useMemo(()=>h?bR(h):null,[h]),p=b.useMemo(()=>["viewResults",u,t==null?void 0:t.noteId,(m==null?void 0:m.params.toString())??null],[u,t==null?void 0:t.noteId,m]),{isLive:y}=Vo({queryKey:p,params:(m==null?void 0:m.params)??new URLSearchParams,client:m?i:null,enabled:!!m&&f}),S=lt({queryKey:p,enabled:!!i&&!!m,queryFn:()=>i.queryNotes(m.params),staleTime:y?Number.POSITIVE_INFINITY:1e4,refetchInterval:y?!1:3e4,refetchOnWindowFocus:!y,placeholderData:t0});return{data:S.data,isPending:S.isPending,isError:S.isError,error:S.error,refetch:()=>void S.refetch(),problems:(m==null?void 0:m.problems)??[],queryKey:p}}function JD(){const t=ae(a=>a.activeVaultId);return b.useMemo(()=>{if(!t)return null;const a=Ls(t);return a!=null&&a.accessToken?vR(a.accessToken):null},[t])}function WD(t,a){return a&&(t!=null&&t.createdBy)&&t.createdBy===a?"update":"fork"}function F0(t){return t.pathname==="/"||t.pathname==="/today"||t.pathname.startsWith("/n/")}function xm(t){return new URLSearchParams(t.search).get("view")}function TR(t){if(t.pathname!=="/notes")return!1;const a=xm(t);return a!=="pinned"&&a!=="archived"}function jR(t){return t.pathname==="/notes"&&xm(t)==="pinned"}function NR(t){return t.pathname==="/notes"&&xm(t)==="archived"}function AR(t){return F0(t)||t.pathname==="/notes"}const X0="/",_R="/notes",vo="/map";function hn(t){return a=>a.pathname===t}const RR=["/welcome","/check-email","/add","/add-vault","/oauth/callback"];function Z0(t){return RR.some(a=>t===a||t.startsWith(`${a}/`))}const CR={id:"recent",label:"Recent",to:X0,icon:c.jsx(Tj,{}),match:F0},OR={id:"notes",label:"All notes",to:_R,icon:c.jsx(Ih,{}),match:TR},MR={id:"pinned",label:"Pinned",to:"/notes?view=pinned",icon:c.jsx(Dj,{}),match:jR},DR={id:"archive",label:"Archive",to:"/notes?view=archived",icon:c.jsx(kj,{}),match:NR},gb="/views/new",kR={id:"new-view",label:"New view",to:gb,icon:c.jsx(Kh,{}),match:hn(gb)},LR={id:"calendar",label:"Calendar",to:"/calendar",icon:c.jsx(Ux,{}),match:hn("/calendar")},UR={id:"tags",label:"Tags",to:"/tags",icon:c.jsx(jj,{}),match:hn("/tags")},zR={id:"activity",label:"Activity",to:"/activity",icon:c.jsx(_j,{}),match:hn("/activity")},VR={id:"map",label:"Map",to:vo,icon:c.jsx(Bx,{}),match:hn(vo)},BR={id:"vaults",label:"Vaults",to:"/vaults",icon:c.jsx(Rj,{}),match:hn("/vaults")},HR={id:"connect",label:"Connect AI",to:"/connect",icon:c.jsx(zx,{}),match:hn("/connect")},qR={id:"import",label:"Import notes",to:"/import",icon:c.jsx(Vx,{}),match:hn("/import")},$R={id:"export",label:"Export notes",to:"/export",icon:c.jsx(Cj,{}),match:hn("/export")},QR={id:"settings",label:"Settings",to:"/settings",icon:c.jsx(Aj,{}),match:hn("/settings")},IR={write:{label:"Write a note",to:"/new",icon:c.jsx(KR,{}),match:()=>!1}};function KR(){return c.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 place-items-center rounded-full border border-border text-[10px]",children:"✦"})}function GR({daysLeft:t}){return c.jsxs("span",{className:"shrink-0 rounded-full bg-sun-soft px-1.5 py-0.5 font-round text-[10px] font-semibold text-sun-ink",title:`Free trial · ${t} day${t===1?"":"s"} left`,children:[t,"d"]})}function YR(t){const a=[CR,OR,MR,DR],r=[LR,UR,zR];t.mapEarned&&r.push(VR);const i={id:"account",label:"Account & plan",to:"/account",icon:c.jsx(Nj,{}),match:hn("/account"),badge:t.trialDaysLeft!==null?c.jsx(GR,{daysLeft:t.trialDaysLeft}):void 0},u=[{id:"notes",label:"Your notes",items:a},{id:"views",label:"Views",items:[...t.viewItems,kR]},{id:"explore",label:"Explore",items:r},{id:"parachute",label:"Your parachute",items:[i,BR,HR,qR,$R]}];return t.setup&&t.setup.steps.length>0&&u.push({id:"setup",label:"Set up",sublabel:`${t.setup.done} of ${t.setup.total}`,items:t.setup.steps.map(f=>({id:`setup-${f}`,...IR[f]}))}),u.push({id:"foot",items:[QR]}),u}function PR(){var T;const t=ae(j=>j.getActiveVault()),a=q0(),r=nR(),{roles:i}=wl((t==null?void 0:t.id)??null),u=wR(i.view),f=t!==null&&Qs(t.clientId),h=am({enabled:f}),m=((T=f?nm(h.data):null)==null?void 0:T.plan)??null,p=typeof(m==null?void 0:m.trial_days_left)=="number"?m.trial_days_left:null,y=b.useMemo(()=>Array.isArray(u.data)?u.data.filter(j=>!fR.includes(j.path??"")&&!uR(j)).map(j=>{const _=K0(j),C=`/views/${encodeURIComponent(j.id)}`;return{id:`view-${j.id}`,label:_.title,to:C,icon:c.jsx(Gj,{kind:_.kind,hueTag:SR(_.query)}),match:hn(C)}}).sort((j,_)=>j.label.localeCompare(_.label)):[],[u.data]);if(!t)return[];const S=m0({hasUserNote:r.data===!0}),v=S.filter(j=>!j.done),x=r.data===void 0||v.length===0?null:{steps:v.map(j=>j.id),done:S.length-v.length,total:S.length};return YR({mapEarned:a,trialDaysLeft:p,setup:x,viewItems:y})}const J0=b.createContext(null);function FR({children:t}){const a=PR();return c.jsx(J0.Provider,{value:a,children:t})}function Sm(){const t=b.useContext(J0);if(t===null)throw new Error("useNavBands must render under <NavBandsProvider> — the nav model derives once, in the app shell (app#110)");return t}const XR=Ia(t=>({shown:!1,setShown(a){t({shown:a})}}));function ZR(){const t=ae(u=>u.activeVaultId!==null),a=q0(),r=XR(u=>u.shown),{pathname:i}=Ge();return!t||a||i===vo||r?null:c.jsx(_e,{to:vo,"aria-label":"Open the relational map",title:"Your map",className:"focus-ring fixed right-5 bottom-20 z-20 grid h-12 w-12 place-items-center rounded-full border border-border bg-card text-accent shadow-lg hover:border-accent lg:right-6 lg:bottom-6",children:c.jsx(Bx,{width:22,height:22})})}const tl=Ia(t=>({open:!1,setOpen(a){t({open:a})},toggle(){t(a=>({open:!a.open}))}}));function JR(){const t=ae(u=>u.activeVaultId!==null),a=tl(u=>u.setOpen),r=Ge();if(!t)return null;const i=AR(r);return c.jsx("nav",{"aria-label":"Primary",className:"fixed inset-x-0 bottom-0 z-20 border-t border-border bg-bg/95 backdrop-blur lg:hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:c.jsxs("ul",{className:"mx-auto flex max-w-(--w-page) items-stretch justify-around px-2",children:[c.jsx(WR,{to:X0,label:"Notes",active:i,icon:c.jsx(Ih,{})}),c.jsx(tC,{}),c.jsx(eC,{label:"Search",icon:c.jsx(co,{}),onClick:()=>a(!0)})]})})}function WR({to:t,label:a,icon:r,active:i}){return c.jsx("li",{className:"flex-1",children:c.jsxs(_e,{to:t,"aria-label":a,"aria-current":i?"page":void 0,className:`focus-ring flex h-14 flex-col items-center justify-center gap-0.5 text-2xs ${i?"text-accent":"text-fg-muted hover:text-accent"}`,children:[c.jsx("span",{"aria-hidden":"true",children:r}),c.jsx("span",{children:a})]})})}function eC({label:t,icon:a,onClick:r}){return c.jsx("li",{className:"flex-1",children:c.jsxs("button",{type:"button",onClick:r,"aria-label":t,className:"focus-ring flex h-14 w-full flex-col items-center justify-center gap-0.5 text-2xs text-fg-muted hover:text-accent",children:[c.jsx("span",{"aria-hidden":"true",children:a}),c.jsx("span",{children:t})]})})}function tC(){return c.jsx("li",{className:"flex flex-1 items-center justify-center",children:c.jsx(_e,{to:"/new","aria-label":"New note",className:"focus-ring -mt-4 grid h-[3.25rem] w-[3.25rem] place-items-center rounded-full bg-accent text-(--color-on-accent) shadow-lg transition-colors hover:bg-accent-hover",children:c.jsx(Kh,{width:26,height:26,strokeWidth:2})})})}function W0({title:t,message:a,retry:r,retryLabel:i="Try again",action:u,className:f=""}){return c.jsxs("div",{className:`rounded-lg border border-(--color-danger-border) bg-(--color-danger-soft) p-6 ${f}`.trim(),children:[c.jsx("p",{className:"mb-2 font-medium text-(--color-danger)",children:t}),a?c.jsx("p",{className:"mb-4 text-sm text-fg-muted",children:a}):null,r||u?c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r?c.jsx("button",{type:"button",onClick:r,className:"btn btn-secondary btn-touch",children:i}):null,u]}):null]})}class eS extends b.Component{constructor(){super(...arguments);fe(this,"state",{error:null})}static getDerivedStateFromError(r){return{error:r}}componentDidCatch(r,i){console.error("ErrorBoundary caught a render error:",r,i.componentStack)}render(){return this.state.error?this.props.fallback(this.state.error):this.props.children}}function nC({error:t}){return c.jsx("div",{className:"page",children:c.jsx(W0,{title:"Something went wrong",message:c.jsxs(c.Fragment,{children:["This page hit an unexpected error. You can head back to your notes.",c.jsxs("details",{className:"mt-3",children:[c.jsx("summary",{className:"cursor-pointer text-xs text-fg-dim hover:text-fg-muted",children:"Technical detail"}),c.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-xs text-fg-dim",children:t.message})]})]}),action:c.jsx(_e,{to:"/notes",className:"btn btn-secondary btn-touch",children:"Back to notes"})})})}function Fe({children:t}){const a=Ge();return c.jsx(eS,{fallback:r=>c.jsx(nC,{error:r}),children:t},a.key)}function aC({error:t}){return c.jsxs("div",{className:"mx-auto flex min-h-dvh max-w-md flex-col items-center justify-center gap-3 px-6 text-center",children:[c.jsx("p",{className:"font-serif text-xl text-fg",children:"Something went wrong"}),c.jsx("p",{className:"text-sm text-fg-muted",children:"Parachute hit an unexpected error and couldn't recover on its own. Reloading usually fixes it."}),c.jsxs("details",{className:"w-full text-left",children:[c.jsx("summary",{className:"cursor-pointer text-xs text-fg-dim hover:text-fg-muted",children:"Technical detail"}),c.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-xs text-fg-dim",children:t.message})]}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"btn btn-primary btn-touch",children:"Reload"})]})}function rC({children:t}){return c.jsx(eS,{fallback:a=>c.jsx(aC,{error:a}),children:t})}const bo=Ia(t=>({on:!1,setOn(a){t({on:a})},toggle(){t(a=>({on:!a.on}))}})),sC=/^\/n\/[^/]+(\/edit)?$/;function tS(t){return sC.test(t)}function iC(){const t=Ge(),a=bo(i=>i.setOn),r=bo(i=>i.toggle);return b.useEffect(()=>{a(!1)},[t.pathname]),b.useEffect(()=>{const i=u=>{(u.metaKey||u.ctrlKey)&&(u.altKey||u.shiftKey||u.key==="."&&tS(t.pathname)&&(u.preventDefault(),r()))};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[t.pathname,r]),null}function lC(){const t=bo(a=>a.setOn);return c.jsx("button",{type:"button",onClick:()=>t(!1),"aria-label":"Exit focus mode",title:"Exit focus (⌘.)",className:"glass-panel enter-fade focus-ring fixed top-4 right-4 z-30 grid h-10 w-10 place-items-center rounded-full border border-border text-fg-muted shadow-lift hover:text-accent",style:{marginTop:"env(safe-area-inset-top)"},children:c.jsx(Bj,{width:18,height:18})})}function uC(){const t=aa(u=>u.push),[a,r]=b.useState(!1);return{copied:a,copy:async u=>{try{await navigator.clipboard.writeText(u),r(!0),t("Copied to clipboard.","success"),window.setTimeout(()=>r(!1),2e3)}catch{t("Couldn't copy — select and copy manually.","error")}}}}function oC({value:t,label:a,className:r}){const{copied:i,copy:u}=uC();return c.jsxs("div",{className:`flex items-stretch gap-2 ${r??""}`,children:[c.jsx("code",{className:"min-w-0 flex-1 overflow-x-auto rounded-md border border-border bg-bg-soft px-3 py-2 font-mono text-sm text-fg",children:t}),c.jsx("button",{type:"button",onClick:()=>u(t),className:"btn btn-secondary btn-touch shrink-0","aria-label":`Copy ${a}`,children:i?"Copied":"Copy"})]})}function cC(t=navigator,a=window){var r;return(r=a.matchMedia)!=null&&r.call(a,"(display-mode: standalone)").matches?!0:t.standalone===!0}function fC(t=navigator.userAgent,a=typeof document<"u"&&navigator.maxTouchPoints>1){return/iPad|iPhone|iPod/.test(t)?!0:/Macintosh/.test(t)&&a}let xs=null,nS=!1;const gh=new Set;function wm(){for(const t of gh)t()}function dC(t){t.preventDefault(),xs=t,wm()}function hC(){xs=null,nS=!0,wm()}let yb=!1;function mC(){yb||typeof window>"u"||(yb=!0,window.addEventListener("beforeinstallprompt",dC),window.addEventListener("appinstalled",hC))}mC();function vb(t){return gh.add(t),()=>{gh.delete(t)}}function pC(){const t=b.useSyncExternalStore(vb,()=>xs,()=>null),a=b.useSyncExternalStore(vb,()=>nS,()=>!1),[r,i]=b.useState({standalone:!0,ios:!1});b.useEffect(()=>{i({standalone:cC(),ios:fC()})},[]);const f=r.standalone||a?"installed":t!==null||r.ios?"available":"unsupported",h=b.useCallback(async()=>{const m=xs;if(!m)return"unavailable";try{return await m.prompt(),(await m.userChoice).outcome}catch{return"unavailable"}finally{xs===m&&(xs=null,wm())}},[]);return{state:f,isIOSDevice:r.ios,promptInstall:h}}function gC(){const{state:t,isIOSDevice:a,promptInstall:r}=pC(),i=ae(m=>{var p;return((p=m.getActiveVault())==null?void 0:p.url)??null}),[u,f]=b.useState(!1);if(t!=="available")return null;const h=async()=>{await r()==="unavailable"&&a&&f(!0)};return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",onClick:h,className:"min-h-11 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-fg-muted hover:text-accent focus-visible:outline-2 focus-visible:outline-accent",children:"Install app"}),u?c.jsxs("dialog",{open:!0,"aria-labelledby":"ios-install-title",className:"fixed inset-0 z-50 m-auto max-w-sm rounded-2xl border border-border bg-card p-6 text-fg shadow-lift",children:[c.jsx("h2",{id:"ios-install-title",className:"mb-3 font-serif text-xl",children:"Add Parachute to your home screen"}),c.jsxs("ol",{className:"mb-5 list-decimal space-y-2 pl-5 text-sm text-fg-muted",children:[c.jsx("li",{children:"Tap the Share icon in Safari's toolbar."}),c.jsxs("li",{children:["Choose ",c.jsx("strong",{className:"text-fg",children:"Add to Home Screen"}),"."]}),c.jsx("li",{children:"Tap Add. Parachute will open standalone from your home screen."})]}),i?c.jsxs("div",{className:"mb-5 rounded-md border border-border bg-bg-soft/60 p-3",children:[c.jsx("p",{className:"mb-2 text-sm text-fg-muted",children:"The installed app may ask for your vault address — here it is, ready to paste:"}),c.jsx(oC,{value:i,label:"vault address"})]}):null,c.jsx("div",{className:"flex justify-end",children:c.jsx("button",{type:"button",onClick:()=>f(!1),className:"min-h-11 rounded-lg bg-accent px-3 py-1.5 text-sm font-medium text-(--color-on-accent) hover:bg-accent-hover",children:"Got it"})})]}):null]})}const yh="notes:textSize",Cr=["default","larger","largest"];function yC(t){return t==="default"||t==="larger"||t==="largest"}function Ss(){try{const t=localStorage.getItem(yh);return yC(t)?t:"default"}catch{return"default"}}function vC(t){try{t==="default"?localStorage.removeItem(yh):localStorage.setItem(yh,t)}catch{}}function aS(t,a=document.documentElement){t==="default"?a.removeAttribute("data-text-size"):a.setAttribute("data-text-size",t)}function jd(t){return t==="larger"?"Larger":t==="largest"?"Largest":"Default"}function bC(t){const a=Cr.indexOf(t);return Cr[(a+1)%Cr.length]??"default"}function xC(t){const a=Cr.indexOf(t),r=Cr.length;return Cr[(a-1+r)%r]??"default"}const vh="notes:text-size-change";function io(t){vC(t),aS(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(vh,{detail:t}))}function SC(){return b.useEffect(()=>{const t=a=>{if((a.metaKey||a.ctrlKey)&&!(a.altKey||a.shiftKey)){if(a.key==="="||a.key==="+"){a.preventDefault(),io(bC(Ss()));return}if(a.key==="-"||a.key==="_"){a.preventDefault(),io(xC(Ss()));return}if(a.key==="0"){a.preventDefault(),io("default");return}}};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[]),null}const Nd=8;function wC(){const[t,a]=b.useState(()=>Ss()),[r,i]=b.useState(!1),u=b.useRef(null),f=b.useRef(null),[h,m]=b.useState("down"),[p,y]=b.useState(null),S=b.useCallback(v=>{a(v),io(v)},[]);return b.useEffect(()=>{const v=T=>{T.key==="notes:textSize"&&a(Ss())},x=T=>{const j=T.detail;a(j||Ss())};return window.addEventListener("storage",v),window.addEventListener(vh,x),()=>{window.removeEventListener("storage",v),window.removeEventListener(vh,x)}},[]),b.useEffect(()=>{if(!r)return;const v=x=>{u.current&&(u.current.contains(x.target)||i(!1))};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[r]),b.useLayoutEffect(()=>{if(!r)return;const v=()=>{const x=u.current,T=f.current;if(!x||!T)return;const j=x.getBoundingClientRect(),_=T.getBoundingClientRect(),C=_.height||T.offsetHeight,O=_.width||T.offsetWidth,B=window.innerHeight-j.bottom;m(B<C+Nd?"up":"down");const H=j.right-O,k=Nd,Y=Math.max(k,window.innerWidth-O-Nd),Q=Math.min(Math.max(H,k),Y);y(Q-j.left)};return v(),window.addEventListener("resize",v),window.addEventListener("scroll",v,!0),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0)}},[r]),c.jsxs("div",{ref:u,className:"relative",children:[c.jsx("button",{type:"button","aria-label":`Text size: ${jd(t)}. Click to change.`,"aria-expanded":r,title:`Text size: ${jd(t)}`,onClick:()=>i(v=>!v),className:"inline-flex min-h-11 min-w-11 items-center justify-center rounded-lg border border-border bg-card px-2 py-1.5 text-sm text-fg-muted hover:text-accent focus-visible:outline-2 focus-visible:outline-accent",children:c.jsxs("span",{"aria-hidden":"true",className:"font-serif",children:["A",c.jsx("span",{className:"text-xs",children:"a"})]})}),r?c.jsx("div",{role:"dialog",ref:f,"aria-label":"Text size","data-placement":h,className:`enter-rise absolute right-0 z-30 w-40 rounded-xl border border-border bg-card p-2 text-sm shadow-lift ${h==="up"?"bottom-full mb-2":"mt-2"}`,style:p!=null?{left:`${p}px`,right:"auto"}:void 0,children:c.jsx("ul",{className:"flex flex-col gap-0.5",children:Cr.map(v=>{const x=v===t;return c.jsx("li",{children:c.jsxs("button",{type:"button",onClick:()=>{S(v),i(!1)},"aria-pressed":x,className:`flex w-full items-center justify-between rounded px-2 py-1.5 text-left hover:bg-bg/60 ${x?"text-accent":"text-fg-muted"}`,children:[c.jsx("span",{children:jd(v)}),x?c.jsx("span",{"aria-hidden":"true",className:"text-xs",children:"✓"}):null]})},v)})})}):null]})}const bh="lens:theme",Ad=["system","light","dark"];function EC(t){return t==="system"||t==="light"||t==="dark"}function TC(){try{const t=localStorage.getItem(bh);return EC(t)?t:"system"}catch{return"system"}}function jC(t){try{t==="system"?localStorage.removeItem(bh):localStorage.setItem(bh,t)}catch{}}function bb(t,a=document.documentElement){t==="system"?a.removeAttribute("data-theme"):a.setAttribute("data-theme",t)}function NC(t){const a=Ad.indexOf(t);return Ad[(a+1)%Ad.length]}function AC(t){return t==="light"?"Light":t==="dark"?"Dark":"System"}function xh(){const[t,a]=b.useState("system");b.useEffect(()=>{const u=TC();a(u),bb(u)},[]);const r=()=>{const u=NC(t);a(u),jC(u),bb(u)},i=AC(t);return c.jsx("button",{type:"button",onClick:r,"aria-label":`Theme: ${i}. Click to cycle.`,title:`Theme: ${i}`,className:"inline-flex min-h-11 min-w-11 items-center justify-center rounded-lg border border-border bg-card px-2 py-1.5 text-sm text-fg-muted hover:text-accent focus-visible:outline-2 focus-visible:outline-accent",children:c.jsx(_C,{theme:t})})}function _C({theme:t}){return t==="light"?c.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:[c.jsx("circle",{cx:"10",cy:"10",r:"3.5"}),c.jsx("path",{d:"M10 2v2M10 16v2M2 10h2M16 10h2M4.2 4.2l1.4 1.4M14.4 14.4l1.4 1.4M4.2 15.8l1.4-1.4M14.4 5.6l1.4-1.4"})]}):t==="dark"?c.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"currentColor",children:c.jsx("path",{d:"M15.5 11.8a6 6 0 0 1-7.3-7.3 6 6 0 1 0 7.3 7.3z"})}):c.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"none",stroke:"currentColor",strokeWidth:"1.6",children:[c.jsx("circle",{cx:"10",cy:"10",r:"6"}),c.jsx("path",{d:"M10 4v12",fill:"currentColor",stroke:"none"}),c.jsx("path",{d:"M10 4a6 6 0 0 1 0 12",fill:"currentColor",stroke:"none"})]})}function rS(){const t=typeof window<"u"&&window.location?window.location.origin:"(unknown origin)";return c.jsxs("div",{role:"alert","aria-live":"assertive","data-testid":"insecure-context-banner",className:"rounded-md border border-amber-400/40 bg-amber-400/10 px-3 py-3 text-sm text-amber-100",children:[c.jsxs("p",{className:"mb-2 flex items-center gap-2 font-medium text-amber-100",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠"}),"Insecure context — OAuth unavailable"]}),c.jsxs("p",{className:"mb-2 text-xs text-amber-100/90",children:["Your hub URL must be served over HTTPS or accessed at ",c.jsx("code",{children:"http://localhost"}),". This page is at ",c.jsx("code",{className:"font-mono",children:t}),", which the browser treats as insecure for Web Crypto. To connect:"]}),c.jsxs("ul",{className:"ml-4 list-disc space-y-1 text-xs text-amber-100/90",children:[c.jsxs("li",{children:["Use ",c.jsx("code",{children:"http://localhost"})," or ",c.jsx("code",{children:"http://127.0.0.1"})," directly (replace your hub URL with the localhost form), ",c.jsx("strong",{children:"or"})]}),c.jsx("li",{children:"Serve your hub over HTTPS via Tailscale Serve, Cloudflare Tunnel, or a reverse proxy."})]})]})}const RC={vault_taken:"That name's already taken — try another.",vault_limit_reached:"You've reached your plan's vault limit. Upgrade your plan, or free one up first.",invalid_name:"Use 2–63 characters: lowercase letters, numbers, and hyphens.",reserved:"That name is reserved — pick a different one.",not_owner:"That vault isn't linked to this account.",not_found:"That vault couldn't be found.",invalid_scope:"Couldn't open that vault — try again.",not_implemented:"That isn't available yet."},CC="Something went wrong. Try again.";function OC(t){return/^[a-z][a-z0-9_]*$/.test(t)}function MC(t,a=CC){if(!(t instanceof Error))return a;const r=t.message.trim();return r?OC(r)?RC[r]??a:r:a}function mr(t){try{return kh(t)}catch{return t.replace(/\/$/,"")}}function DC(t,a,r,i,u){const f=new Set(r.map(x=>mr(x.url))),h=new Set(t.map(x=>mr(x.url))),m=new Set(t.filter(x=>Qs(x.clientId)).map(x=>x.name)),p=[...t].sort((x,T)=>el(x).localeCompare(el(T))).map(x=>({kind:"device",id:x.id,label:el(x),isActive:x.id===a,hubKnown:f.has(mr(x.url)),vault:x})),y=(u??[]).filter(x=>!(x.url!==void 0&&h.has(mr(x.url)))&&!m.has(x.name)).sort((x,T)=>x.name.localeCompare(T.name)).map(x=>({kind:"account",name:x.name,url:x.url})),S=new Set(y.filter(x=>x.url!==void 0).map(x=>mr(x.url))),v=i===null?[]:r.filter(x=>!h.has(mr(x.url))&&!S.has(mr(x.url))).sort((x,T)=>x.name.localeCompare(T.name)).map(x=>({kind:"hub",name:x.name,url:x.url,hubOrigin:i}));return[...p,...y,...v]}function _d({label:t,here:a}){const r=(t.trim()[0]??"?").toUpperCase();return c.jsx("span",{"aria-hidden":!0,className:`grid h-8 w-8 shrink-0 place-items-center rounded-lg text-sm font-semibold ${a?"bg-grass-soft text-grass-ink":"bg-bg-soft text-fg-muted"}`,children:r})}function Rd({tone:t,children:a}){return c.jsx("span",{"aria-hidden":!0,className:`grid h-8 w-8 shrink-0 place-items-center rounded-full text-sm ${t==="sun"?"bg-sun-soft text-sun-ink":"bg-bg-soft"}`,style:t==="sky"?{color:"var(--color-sky)"}:t==="accent"?{color:"var(--color-accent)"}:void 0,children:a})}function xb({layout:t,onAfterAction:a}){const r=ae(E=>E.vaults),i=ae(E=>E.activeVaultId),u=i?r[i]??null:null,[f,h]=b.useState(null),[m,p]=b.useState(!1),[y,S]=b.useState(null),[v,x]=b.useState(null),[T,j]=b.useState(null),[_,C]=b.useState(null),[O,B]=b.useState(!1),H=b.useMemo(()=>u?q_(u):null,[u]),k=am(),Y=nm(k.data),Q=Ft(E=>E.identityEpoch),G=lt({queryKey:["account","vaults",Q],queryFn:async()=>{try{return(await Zx()).vaults}catch{return null}},staleTime:6e4}),F=G.data??null;b.useEffect(()=>{if(!H)return;const E=new AbortController;return p(!0),Q_(H,fetch.bind(globalThis),E.signal).then(q=>{E.signal.aborted||(h(q),p(!1))}),()=>{E.abort(),p(!1)}},[H]);const Z=b.useMemo(()=>DC(Object.values(r),i,f??[],H,F),[r,i,f,H,F]),le=Z.filter(E=>E.kind==="device"),de=Z.filter(E=>E.kind==="account"),ye=Z.filter(E=>E.kind==="hub"),we=(Y==null?void 0:Y.plan)??null,re=we!==null&&typeof we.vault_limit=="number"&&typeof we.vaults_used=="number"&&we.vaults_used>=we.vault_limit,ee=typeof(we==null?void 0:we.trial_days_left)=="number"?we.trial_days_left:null,M=b.useCallback(E=>{E.isActive||eR(E.id,{toast:!0}),a()},[a]),P=b.useCallback(async E=>{if(!T){j(E.name),C(null);try{await Do(E.name),bm(E.name),a()}catch(q){C(MC(q,"Couldn't open that vault."))}finally{j(null)}}},[T,a]),ne=b.useCallback(async E=>{S(E.name),x(null),B(!1);try{const{authorizeUrl:q}=await pm(E.hubOrigin,void 0,void 0,{params:{vault:E.name}});window.location.assign(q)}catch(q){S(null),q instanceof No?B(!0):x(q.message)}},[]),oe=m||G.isPending,me=c.jsxs(c.Fragment,{children:[le.length>0?c.jsxs("div",{className:"border-b border-border-light",children:[c.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"On this device"}),c.jsx("ul",{className:"pb-2",children:le.map(E=>c.jsx("li",{children:c.jsxs("button",{type:"button",onClick:()=>M(E),className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 text-left hover:bg-bg-soft",children:[c.jsx(_d,{label:E.label,here:!0}),c.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-fg",children:E.label}),E.isActive?c.jsx("span",{className:"shrink-0 text-2xs font-medium text-grass-ink",children:"✓ current"}):null]})},E.id))})]}):null,de.length>0?c.jsxs("div",{className:"border-b border-border-light",children:[c.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"In your account"}),c.jsx("ul",{className:"pb-2",children:de.map(E=>c.jsx("li",{children:c.jsxs("div",{className:"flex w-full items-center gap-2.5 px-3 py-1.5",children:[c.jsx(_d,{label:E.name,here:!1}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-fg-muted",children:E.name}),c.jsx("button",{type:"button",onClick:()=>P(E),disabled:T===E.name,className:"focus-ring shrink-0 rounded-full border border-accent/40 px-2.5 py-1 text-xs font-medium text-accent hover:bg-accent/10 disabled:opacity-60",children:T===E.name?"Opening…":"Open →"})]})},E.name))})]}):null,ye.length>0?c.jsxs("div",{className:"border-b border-border-light",children:[c.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"From your hub"}),c.jsx("ul",{className:"pb-2",children:ye.map(E=>c.jsx("li",{children:c.jsxs("div",{className:"flex w-full items-center gap-2.5 px-3 py-1.5",children:[c.jsx(_d,{label:E.name,here:!1}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-fg-muted",children:E.name}),c.jsx("button",{type:"button",onClick:()=>ne(E),disabled:y===E.name,className:"focus-ring shrink-0 rounded-full border border-accent/40 px-2.5 py-1 text-xs font-medium text-accent hover:bg-accent/10 disabled:opacity-60",children:y===E.name?"Connecting…":"Connect"})]})},E.url))})]}):null,O?c.jsx("div",{className:"border-b border-border-light px-3 py-2",children:c.jsx(rS,{})}):null,v||_?c.jsx("div",{className:"border-b border-border-light px-3 py-2 text-xs text-(--color-danger)",children:v??_}):null,c.jsxs("div",{className:"border-b border-border-light py-2",children:[re&&we?c.jsxs(_e,{to:"/account",onClick:a,className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 hover:bg-bg-soft",children:[c.jsx(Rd,{tone:"sun",children:"↑"}),c.jsxs("span",{className:"min-w-0 flex-1 leading-snug text-fg-muted",children:[we.vaults_used," of ",we.vault_limit," vaults on your plan"]}),c.jsx("span",{className:"shrink-0 text-sm font-semibold text-accent",children:"Upgrade →"})]}):c.jsxs(_e,{to:"/add-vault/create",onClick:a,className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 hover:bg-bg-soft",children:[c.jsx(Rd,{tone:"accent",children:"+"}),c.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-accent",children:"Create a vault"})]}),c.jsxs(_e,{to:"/add",onClick:a,className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 hover:bg-bg-soft",children:[c.jsx(Rd,{tone:"sky",children:"⌂"}),c.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold",style:{color:"var(--color-sky)"},children:"Connect your own"})]})]}),c.jsxs("div",{className:"px-3 py-2",children:[ee!==null?c.jsxs(_e,{to:"/account",onClick:a,className:"focus-ring mb-1 block text-xs text-sun-ink hover:underline",children:["Free trial ·"," ",ee===0?"ends today":`${ee} day${ee===1?"":"s"} left`]}):null,c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx(_e,{to:"/vaults",onClick:a,className:"focus-ring text-xs text-fg-muted hover:text-accent",children:"Manage vaults →"}),oe?c.jsx("span",{className:"text-[10px] text-fg-dim",children:"Looking for more vaults…"}):null]})]})]});return t==="inline"?c.jsx("section",{"aria-label":"Vaults",className:"text-sm",children:me}):c.jsx("div",{role:"dialog","aria-label":"Vaults",className:"enter-rise absolute left-0 z-30 mt-2 w-72 overflow-hidden rounded-2xl border border-border bg-card text-sm shadow-lift",children:me})}function Em({variant:t="header",onOpenNavSheet:a,onAction:r,collapsed:i=!1}){const u=ae(x=>x.vaults),f=ae(x=>x.activeVaultId),h=f?u[f]??null:null,[m,p]=b.useState(!1),y=b.useRef(null);b.useEffect(()=>{if(!m)return;const x=j=>{y.current&&(y.current.contains(j.target)||p(!1))},T=j=>{j.key==="Escape"&&p(!1)};return document.addEventListener("mousedown",x),document.addEventListener("keydown",T),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",T)}},[m]);const S=b.useCallback(()=>p(!1),[]),v=h?el(h):"Choose vault";if(t==="sheet")return c.jsx(xb,{layout:"inline",onAfterAction:r??(()=>{})});if(t==="rail"){const x=(v.trim()[0]??"?").toUpperCase();return c.jsxs("div",{ref:y,className:"relative",children:[c.jsxs("button",{type:"button","aria-label":`Active vault: ${v}`,"aria-expanded":m,"aria-haspopup":"dialog",onClick:()=>p(T=>!T),title:v,className:`focus-ring flex w-full items-center rounded-xl border border-border bg-card text-left shadow-sm hover:border-accent/50 ${i?"justify-center px-0 py-2":"gap-2.5 px-2.5 py-2"}`,children:[c.jsx("span",{"aria-hidden":!0,className:"grid h-7 w-7 shrink-0 place-items-center rounded-lg bg-grass-soft font-round text-sm font-semibold text-grass-ink",children:x}),i?null:c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 flex-1 truncate font-round font-semibold text-fg",children:v}),c.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-xs text-fg-dim",children:"▾"})]})]}),m?c.jsx(xb,{layout:"popover",onAfterAction:S}):null]})}return c.jsxs("button",{type:"button","aria-label":`Active vault: ${v}`,"aria-haspopup":"dialog",onClick:a,title:v,className:"flex min-w-0 max-w-[12rem] items-center gap-1.5 rounded-lg border border-border bg-card px-2.5 py-1.5 text-sm text-fg hover:border-accent/50",children:[c.jsx("span",{"aria-hidden":!0,className:"inline-block h-2 w-2 shrink-0 rounded-full bg-accent"}),c.jsx("span",{className:"min-w-0 truncate",children:v}),c.jsx("span",{"aria-hidden":!0,className:"ml-1 shrink-0 text-xs text-fg-dim",children:"▾"})]})}function kC({open:t,onClose:a,initialFocus:r}){return t?c.jsx(LC,{onClose:a,initialFocus:r}):null}function LC({onClose:t,initialFocus:a}){const r=ae(x=>Object.keys(x.vaults).length>0),i=Sm(),u=Ge(),f=b.useRef(null),h=b.useRef(null),m=b.useRef(null),p=i.filter(x=>x.id!=="foot"),y=i.find(x=>x.id==="foot");b.useEffect(()=>{var j;const x=document.activeElement,T=a==="switcher"?((j=h.current)==null?void 0:j.querySelector("button, a"))??f.current:f.current;return T==null||T.focus(),()=>{var _;return(_=x==null?void 0:x.focus)==null?void 0:_.call(x)}},[a]),b.useEffect(()=>{const x=T=>{if(T.key==="Escape"){t();return}if(T.key!=="Tab"||!f.current)return;const j=Array.from(f.current.querySelectorAll('a[href], button:not([disabled]), input, select, textarea, [tabindex]:not([tabindex="-1"])'));if(j.length===0)return;const _=j[0],C=j[j.length-1],O=document.activeElement;if(!(O instanceof HTMLElement)||!j.includes(O)){T.preventDefault(),(T.shiftKey?C:_).focus();return}T.shiftKey&&document.activeElement===_?(T.preventDefault(),C.focus()):!T.shiftKey&&document.activeElement===C&&(T.preventDefault(),_.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t]),b.useEffect(()=>{const x=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=x}},[]);const S=x=>{m.current=f.current&&f.current.scrollTop<=0?x.touches[0].clientY:null},v=x=>{m.current!==null&&x.touches[0].clientY-m.current>64&&(m.current=null,t())};return c.jsxs("div",{className:"fixed inset-0 z-40 lg:hidden",children:[c.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"enter-fade absolute inset-0 h-full w-full cursor-default bg-black/40"}),c.jsxs("div",{role:"dialog",ref:f,"aria-modal":"true","aria-label":"Menu",tabIndex:-1,onTouchStart:S,onTouchMove:v,className:"enter-rise glass-panel absolute inset-x-0 bottom-0 max-h-[85dvh] overflow-y-auto rounded-t-[var(--radius-2xl)] shadow-lift",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[c.jsx("div",{"aria-hidden":!0,className:"sticky top-0 z-10 flex justify-center pt-2.5 pb-1.5",children:c.jsx("span",{className:"h-1 w-10 rounded-full bg-border"})}),r?c.jsx("div",{ref:h,"data-nav-band":"switcher",className:"border-b border-border-light",children:c.jsx(Em,{variant:"sheet",onAction:t})}):null,p.length>0?c.jsx("nav",{"aria-label":"Primary",className:"px-3 pb-1",children:p.map(x=>c.jsx(UC,{band:x},x.id))}):null,c.jsxs("div",{"data-nav-band":"foot",className:"border-t border-border px-3 py-3",children:[y==null?void 0:y.items.map(x=>c.jsx(sS,{item:x,loc:u},x.id)),c.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 px-3",children:[c.jsx(gC,{}),c.jsx(wC,{}),c.jsx(xh,{})]})]})]})]})}function UC({band:t}){const a=Ge();return c.jsxs("div",{"data-nav-band":t.id,children:[t.label?c.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[c.jsx("span",{children:t.label}),t.sublabel?c.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.items.map(r=>c.jsx(sS,{item:r,loc:a},r.id))]})}function sS({item:t,loc:a}){const r=t.match(a);return c.jsxs(_e,{to:t.to,"data-nav-item":t.id,"aria-current":r?"page":void 0,className:`focus-ring flex items-center gap-3 rounded-lg px-3 py-2.5 font-round text-base transition-colors duration-(--dur-quick) ease-out ${r?"bg-grass-soft font-semibold text-grass-ink":"font-medium text-fg-muted hover:bg-bg hover:text-fg"}`,children:[c.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})}const Sb={rows:[],byKind:{},total:0,pendingCount:0,needsHumanCount:0,authHalt:null};function iS(t,a,r=2e3){const[i,u]=b.useState(Sb),f=b.useRef(!1);return b.useEffect(()=>{if(f.current=!1,!t||!a){u(Sb);return}let h=null;const m=async()=>{try{const[p,y]=await Promise.all([U0(t,a),Ks(t,L0)]);if(f.current)return;const S={};let v=0,x=0;for(const j of p){const _=j.mutation.kind;S[_]=(S[_]??0)+1,j.status==="needs-human"?x+=1:v+=1}const T=y&&y.vaultId===a?y:null;u({rows:p,byKind:S,total:p.length,pendingCount:v,needsHumanCount:x,authHalt:T})}catch{}};return m(),h=setInterval(m,r),()=>{f.current=!0,h&&clearInterval(h)}},[t,a,r]),i}const zC=[["y",365*24*60*60*1e3],["mo",720*60*60*1e3],["w",10080*60*1e3],["d",1440*60*1e3],["h",3600*1e3],["m",60*1e3]];function Tm(t,a=new Date){if(!t)return"";const i=new Date(t).getTime();if(Number.isNaN(i))return"";const u=a.getTime()-i,f=Math.abs(u);for(const[h,m]of zC)if(f>=m){const p=Math.floor(f/m);return u>=0?`${p}${h} ago`:`in ${p}${h}`}return"just now"}const VC={"create-note":"new notes","update-note":"note edits","delete-note":"deletions","upload-attachment":"uploads","link-attachment":"attachment links","delete-attachment":"attachment removals"},BC=.8;function HC({onDismiss:t}){const{db:a,isOnline:r,isDraining:i,lastSyncedAt:u}=Zt(),f=ae(O=>O.activeVaultId),h=aa(O=>O.push),m=iS(a,f),[p,y]=b.useState(null),S=Dr(O=>f?O.byVault[f]??null:null),[,v]=b.useState(0);b.useEffect(()=>{const O=setInterval(()=>v(B=>B+1),15e3);return()=>clearInterval(O)},[]),b.useEffect(()=>{let O=!1;return w2().then(B=>{O||B.supported&&typeof B.usage=="number"&&typeof B.quota=="number"&&y({usage:B.usage,quota:B.quota})}),()=>{O=!0}},[]);const x=(S==null?void 0:S.state)==="down",T=m.authHalt?"Reconnect needed":x?"Vault not reachable":r?i?"Syncing…":m.total>0?"Sync pending":"All caught up":"Offline — changes queued",j=async O=>{a&&(await $2(a,O),h("Retrying…","success"))},_=async(O,B)=>{a&&confirm(`Discard this ${wb(B.mutation)}? It cannot be recovered.`)&&(await Q2(a,O),h("Row discarded.","success"))},C=async()=>{if(!a||!f||!confirm(`Clear every pending row for this vault (${m.total} total)? Destructive.`))return;const O=await G2(a,f);h(`Cleared ${O} pending row${O===1?"":"s"}.`,"success")};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("header",{className:"flex items-baseline justify-between",children:[c.jsx("h3",{className:"font-serif text-base text-fg",children:T}),t?c.jsx("button",{type:"button",onClick:t,"aria-label":"Close sync status",className:"text-xs text-fg-dim hover:text-accent",children:"×"}):null]}),m.authHalt?c.jsxs("div",{className:"rounded-md border border-red-500/30 bg-red-500/5 p-3 text-xs text-red-300",children:[c.jsx("p",{className:"mb-2",children:m.authHalt.message||"Vault rejected the current session."}),c.jsx(_e,{to:"/add",onClick:t,className:"inline-block rounded-lg bg-accent px-3 py-1.5 text-xs font-medium text-(--color-on-accent) hover:bg-accent-hover",children:"Reconnect to resume sync"})]}):null,m.total===0?c.jsx("p",{className:"text-xs text-fg-dim",children:"Nothing pending in this vault."}):c.jsxs("section",{children:[c.jsx("h4",{className:"mb-1 text-xs uppercase tracking-wider text-fg-dim",children:"Queue"}),c.jsx("ul",{className:"space-y-0.5 text-xs",children:Object.entries(m.byKind).map(([O,B])=>c.jsxs("li",{className:"flex justify-between",children:[c.jsx("span",{className:"text-fg-muted",children:VC[O]??O}),c.jsx("span",{className:"tabular-nums text-fg-dim",children:B})]},O))})]}),m.needsHumanCount>0?c.jsxs("section",{children:[c.jsx("h4",{className:"mb-1 text-xs uppercase tracking-wider text-fg-dim",children:"Needs your help"}),c.jsx("ul",{className:"space-y-1.5",children:m.rows.filter(O=>O.status==="needs-human").map(O=>c.jsxs("li",{className:"rounded border border-amber-500/30 bg-amber-500/5 p-2 text-xs",children:[c.jsx("p",{className:"font-medium text-amber-200",children:wb(O.mutation)}),O.lastError?c.jsx("p",{className:"mt-0.5 break-words text-amber-100/70",children:O.lastError}):null,c.jsxs("div",{className:"mt-1 flex gap-2",children:[c.jsx("button",{type:"button",onClick:()=>j(O.seq),className:"text-accent hover:underline",children:"Retry"}),c.jsx("button",{type:"button",onClick:()=>_(O.seq,O),className:"text-red-300 hover:underline",children:"Discard"})]})]},O.seq))})]}):null,c.jsx("section",{className:"text-xs text-fg-dim",children:c.jsxs("p",{children:["Last synced:"," ",c.jsx("span",{className:"text-fg-muted",children:u?Tm(new Date(u).toISOString()):"never"})]})}),p?c.jsx(qC,{usage:p.usage,quota:p.quota}):null,m.total>0?c.jsx("div",{className:"flex justify-end border-t border-border pt-3",children:c.jsx("button",{type:"button",onClick:C,className:"text-xs text-red-400 hover:underline",children:"Clear all pending"})}):null]})}function wb(t){switch(t.kind){case"create-note":return`Create note (${t.payload.path??"untitled"})`;case"update-note":return`Update note ${t.targetId}`;case"update-settings":return`Update settings (${t.notePath})`;case"delete-note":return`Delete note ${t.targetId}`;case"upload-attachment":return`Upload ${t.filename}`;case"link-attachment":return`Link attachment to ${t.noteId}`;case"delete-attachment":return`Remove attachment from ${t.noteId}`}}function qC({usage:t,quota:a}){const r=a>0?t/a:0,i=r>=BC;return c.jsxs("section",{className:"text-xs",children:[c.jsxs("div",{className:"flex justify-between text-fg-dim",children:[c.jsx("span",{children:"Offline cache"}),c.jsx("span",{className:i?"text-amber-300":"text-fg-muted",children:$C(t)})]}),i?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"mt-1 h-1.5 w-full overflow-hidden rounded-full bg-border/40",children:c.jsx("div",{className:"h-full bg-amber-400",style:{width:`${Math.min(100,Math.round(r*100))}%`}})}),c.jsx("p",{className:"mt-1 text-amber-300",children:"This browser's offline storage is nearly full. Sync what you can and consider clearing stuck rows."})]}):null]})}function $C(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function QC(t){return t.authHalt?"halted":t.unreachable?"unreachable":t.isOnline?t.isDraining?"syncing":"online":"offline"}function IC(){const{db:t,isOnline:a,isDraining:r}=Zt(),i=ae(x=>x.activeVaultId),u=iS(t,i),f=Dr(x=>i?x.byVault[i]??null:null),[h,m]=b.useState(!1),p=b.useRef(null);b.useEffect(()=>{if(!h)return;const x=T=>{p.current&&(p.current.contains(T.target)||m(!1))};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[h]);const y=QC({isOnline:a,isDraining:r,authHalt:u.authHalt!==null,unreachable:(f==null?void 0:f.state)==="down"}),S=KC(y),v=u.total>0?u.total:null;return c.jsxs("div",{ref:p,className:"relative",children:[c.jsxs("button",{type:"button","aria-label":`Sync status: ${S}${v?`, ${v} pending`:""}`,"aria-expanded":h,onClick:()=>m(x=>!x),className:"flex min-h-11 min-w-11 items-center justify-center gap-1.5 rounded-lg border border-border bg-card px-2 py-1.5 text-sm text-fg-muted hover:text-accent",children:[c.jsx(GC,{tone:y}),c.jsx("span",{className:"hidden text-xs sm:inline",children:S}),v!==null?c.jsx("span",{"aria-label":`${v} pending`,className:"rounded-full bg-accent/20 px-1.5 text-[10px] font-medium tabular-nums text-accent",children:v}):null]}),h?c.jsx("div",{role:"dialog","aria-label":"Sync status details",className:"enter-rise absolute right-0 z-30 mt-2 w-80 rounded-xl border border-border bg-card p-4 text-sm shadow-lift",children:c.jsx(HC,{onDismiss:()=>m(!1)})}):null]})}function KC(t){switch(t){case"online":return"Online";case"offline":return"Offline";case"syncing":return"Syncing…";case"halted":return"Reconnect";case"unreachable":return"Vault down"}}function GC({tone:t}){const a=t==="online"?"var(--color-grass)":t==="offline"?"var(--color-warning)":t==="syncing"?"var(--color-sky)":t==="unreachable"?"color-mix(in srgb, var(--color-danger) 70%, var(--color-bg))":"var(--color-danger)";return c.jsx("span",{"aria-hidden":!0,className:`inline-block h-2 w-2 rounded-full ${t==="syncing"?"animate-pulse":""}`,style:{backgroundColor:a}})}function YC(){const t=Ge(),a=ae(u=>Object.keys(u.vaults).length>0),[r,i]=b.useState(null);return b.useEffect(()=>{i(null)},[t.pathname]),!a&&t.pathname==="/"?null:c.jsxs(c.Fragment,{children:[c.jsx("header",{className:"sticky top-0 z-10 border-b border-border bg-bg/90 backdrop-blur lg:hidden",style:{paddingTop:"env(safe-area-inset-top)"},children:c.jsxs("nav",{className:"flex items-center justify-between gap-3 px-4 py-3",children:[a?c.jsx("div",{className:"min-w-0 flex-1",children:c.jsx(Em,{variant:"header",onOpenNavSheet:()=>i("switcher")})}):c.jsx(_e,{to:"/",className:"focus-ring min-w-0 shrink truncate font-serif text-lg tracking-tight text-fg hover:text-accent",children:"Parachute"}),c.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a?c.jsx(IC,{}):null,c.jsx("button",{type:"button",onClick:()=>i("menu"),"aria-label":"Open menu","aria-expanded":r!==null,"aria-haspopup":"dialog",className:"focus-ring flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-card text-fg-muted hover:text-accent",children:c.jsx("span",{"aria-hidden":"true",className:"font-mono text-base leading-none",children:"☰"})})]})]})}),c.jsx(kC,{open:r!==null,onClose:()=>i(null),initialFocus:r==="switcher"?"switcher":void 0})]})}function PC(){const{mirror:t}=Zt();return t.state==="hydrating"&&t.progress?c.jsx(FC,{done:t.progress.done}):t.state==="offline"&&t.lastSyncedAt!==null?c.jsxs(lS,{children:["Offline — showing your saved vault · updated ",XC(t.lastSyncedAt)]}):null}function FC({done:t}){var u;const a=(u=B0().data)==null?void 0:u.stats,r=a==null?void 0:a.totalNotes,i=typeof r=="number"&&r>0?`${t} of ~${r}`:`${t}`;return c.jsxs(lS,{live:"off",children:["Saving your vault for offline · ",i]})}function lS({children:t,live:a}){return c.jsx("output",{"aria-live":a,className:"block border-b border-border bg-bg-soft px-4 py-1.5 text-center text-xs text-fg-muted md:px-6",children:t})}function XC(t){return Tm(new Date(t).toISOString())}const uS=10,ZC="lens:recents:";function oS(t){return ZC+t}function cS(t){try{const a=localStorage.getItem(oS(t));if(!a)return[];const r=JSON.parse(a);return Array.isArray(r)?r.filter(i=>typeof i=="object"&&i!==null&&typeof i.id=="string"&&typeof i.viewedAt=="number").slice(0,uS):[]}catch{return[]}}function e5(t,a,r=Date.now()){try{const i=cS(t).filter(f=>f.id!==a),u=[{id:a,viewedAt:r},...i].slice(0,uS);localStorage.setItem(oS(t),JSON.stringify(u))}catch{}}const JC=new Set([" ","/","-","_",".","\\"]);function nl(t,a){if(!t)return{score:0,indices:[]};if(!a)return null;const r=t.toLowerCase(),i=a.toLowerCase();let u=0,f=0,h=-2,m=!0;const p=[];for(let y=0;y<i.length&&u<r.length;y+=1){const S=i[y]??"";if(S===r[u]){p.push(y);let v=1;y===0?v+=4:m&&(v+=2),h===y-1&&(v+=3),f+=v,h=y,u+=1}m=JC.has(S)}return u<r.length?null:(f-=Math.floor(i.length/20),{score:f,indices:p})}const Cd=20,Eb=[{id:"new",label:"New note",description:"Open the unified create surface (text + voice)",keywords:["new","create","compose","capture","voice","memo"],action:{type:"navigate",to:"/new"}},{id:"graph",label:"Map",description:"Full-vault map view",keywords:["graph","map","visualize"],action:{type:"navigate",to:"/map"}},{id:"today",label:"Recent",description:"Your recent notes, grouped by day",keywords:["today","now","daily","home","recent"],action:{type:"navigate",to:"/"}},{id:"calendar",label:"Calendar",description:"Month grid of note activity",keywords:["calendar","month","date"],action:{type:"navigate",to:"/calendar"}},{id:"tags",label:"Tags",description:"Browse all tags",keywords:["tags"],action:{type:"navigate",to:"/tags"}},{id:"notes",label:"All notes",description:"The full notes browser",keywords:["notes","all","browse","files"],action:{type:"navigate",to:"/notes"}},{id:"pinned",label:"Pinned",description:"Notes tagged as pinned",keywords:["pinned","star","favorites"],action:{type:"navigate",to:"/notes?view=pinned"}},{id:"archived",label:"Archived",description:"Notes tagged as archived",keywords:["archived","archive"],action:{type:"navigate",to:"/notes?view=archived"}},{id:"untagged",label:"Untagged",description:"Notes with no tags — quick-tag inline",keywords:["untagged","unfiled","inbox"],action:{type:"navigate",to:"/notes?view=untagged"}},{id:"orphaned",label:"Orphaned",description:"Notes with no inbound or outbound links",keywords:["orphaned","orphans","isolated","unlinked"],action:{type:"navigate",to:"/notes?view=orphaned"}}];function WC(t,a){let r=null;for(const i of t){const u=nl(a,i);u&&(r===null||u.score>r)&&(r=u.score)}return r}function eO(t,a){const r=PA(t),i=nl(a,r),u=t.path?nl(a,t.path):null;let f=null;i&&(f=i.score+2),u&&(f===null||u.score>f)&&(f=u.score);for(const h of t.tags??[]){const m=nl(a,h);m&&(f===null||m.score>f)&&(f=m.score)}return f}function tO(t){const a=t.query.trim(),r=a.startsWith(">"),i=(r?a.slice(1):a).trim();if(a.length===0){const y=new Map(t.notes.map(x=>[x.id,x])),S=[];for(const x of t.recents){const T=y.get(x.id);if(!T)continue;const j=dh(T);S.push({kind:"note",id:T.id,title:j.text,titleKind:j.kind,path:T.path,score:0})}const v=Eb.map(x=>({kind:"command",id:x.id,label:x.label,description:x.description,action:x.action,score:0}));return[...S,...v].slice(0,Cd)}const u=Eb.flatMap(y=>{const S=WC([y.label,...y.keywords],i);return S===null?[]:[{kind:"command",id:y.id,label:y.label,description:y.description,action:y.action,score:S+(r?1e3:0)}]});if(r)return u.sort((y,S)=>S.score-y.score).slice(0,Cd);const f=t.notes.flatMap(y=>{const S=eO(y,i);if(S===null)return[];const v=dh(y);return[{kind:"note",id:y.id,title:v.text,titleKind:v.kind,path:y.path,score:S}]}),m=[...t.tags.flatMap(y=>{const S=nl(i,y.name);return S?[{kind:"tag",name:y.name,count:y.count,score:S.score}]:[]})].sort((y,S)=>S.score-y.score),p=[...u,...f].sort((y,S)=>S.score-y.score);return[...m,...p].slice(0,Cd)}const nO=150;function aO({onClose:t}){const a=ae(k=>k.activeVaultId),r=Mr(),i=b.useRef(null),u=b.useRef(null),f=b.useId(),h=b.useId(),[m,p]=b.useState(""),[y,S]=b.useState(""),[v,x]=b.useState(0),T=j_(!0),j=__(),_=b.useMemo(()=>a?cS(a):[],[a]);b.useEffect(()=>{const k=setTimeout(()=>S(m),nO);return()=>clearTimeout(k)},[m]);const C=b.useMemo(()=>tO({query:y,notes:T.data??[],tags:j.data??[],recents:_}),[y,T.data,j.data,_]);b.useEffect(()=>{x(0)},[C.length]),b.useEffect(()=>{var k;(k=i.current)==null||k.focus()},[]);const O=b.useCallback(k=>{k.kind==="note"?r(`/n/${encodeURIComponent(k.id)}`):k.kind==="tag"?r(`/tags/${encodeURIComponent(k.name)}`):r(k.action.to),t()},[r,t]),B=b.useCallback(k=>{if(k.key==="Escape"){k.preventDefault(),t();return}if(k.key==="ArrowDown"){k.preventDefault(),x(Y=>Math.min(C.length-1,Y+1));return}if(k.key==="ArrowUp"){k.preventDefault(),x(Y=>Math.max(0,Y-1));return}if(k.key==="Enter"){k.preventDefault();const Y=C[v];Y&&O(Y);return}},[C,v,O,t]);b.useEffect(()=>{var Y,Q;const k=(Y=u.current)==null?void 0:Y.querySelector(`[data-qs-idx="${v}"]`);(Q=k==null?void 0:k.scrollIntoView)==null||Q.call(k,{block:"nearest"})},[v]);const H=T.isPending;return c.jsx("dialog",{open:!0,"aria-labelledby":f,className:"qs-scrim-fade fixed inset-0 z-50 m-0 h-full max-h-full w-full max-w-full bg-[color-mix(in_srgb,var(--color-fg)_32%,transparent)] p-0 backdrop-blur-[3px] lg:flex lg:px-6 lg:pb-8",onMouseDown:k=>{k.target===k.currentTarget&&t()},children:c.jsxs("div",{className:"flex h-full w-full flex-col bg-bg/95 backdrop-blur-md lg:mx-auto lg:h-auto lg:w-full lg:max-w-xl lg:flex-col-reverse lg:self-end lg:bg-transparent lg:backdrop-blur-none",children:[c.jsxs("div",{className:"enter-rise flex items-center gap-2 px-3 pt-[max(0.75rem,env(safe-area-inset-top))] pb-2 lg:p-0",children:[c.jsxs("div",{className:"glass-panel flex min-w-0 flex-1 items-center gap-2.5 rounded-full border border-border px-4 py-2.5 shadow-soft transition-shadow duration-(--dur-quick) ease-out focus-within:shadow-lift lg:px-5 lg:py-3",children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-fg-dim",children:c.jsx(co,{width:18,height:18})}),c.jsx("input",{id:f,ref:i,type:"text",value:m,onChange:k=>p(k.target.value),onKeyDown:B,placeholder:"Search your vault…","aria-label":"Quick switch query","aria-controls":h,"aria-activedescendant":C[v]?`qs-opt-${v}`:void 0,autoComplete:"off",spellCheck:!1,className:"min-w-0 flex-1 bg-transparent text-base text-fg placeholder:text-fg-dim focus:outline-none"}),c.jsxs("span",{"aria-hidden":"true","data-testid":"smart-slot-reserved",className:"hidden shrink-0 select-none items-center gap-1 rounded-full border border-border-light px-2.5 py-1 text-xs text-fg-dim opacity-70 lg:flex",children:[c.jsx(zx,{width:13,height:13}),"Smart"]})]}),c.jsx("button",{type:"button",onClick:t,className:"focus-ring shrink-0 rounded-full px-3 py-2 text-sm text-fg-muted hover:text-accent lg:hidden",children:"Cancel"})]}),c.jsxs("div",{className:"enter-rise glass-panel flex min-h-0 flex-1 flex-col lg:mb-3 lg:max-h-[55vh] lg:flex-none lg:rounded-[var(--radius-2xl)] lg:border lg:border-border lg:shadow-lift",children:[c.jsx("div",{id:h,ref:u,role:"listbox",tabIndex:-1,"aria-label":"Quick switch results","aria-live":"polite",className:"min-h-0 flex-1 overflow-y-auto py-1 lg:max-h-[50vh]",children:H&&C.length===0?c.jsx("div",{className:"px-4 py-3 text-sm text-fg-dim",children:"Loading notes…"}):C.length===0?c.jsx("div",{className:"px-4 py-3 text-sm text-fg-dim",children:m.trim().length===0?"Start typing to search.":"No matches."}):C.map((k,Y)=>c.jsx(sO,{entry:k,index:Y,selected:Y===v,onPick:()=>O(k),onHover:()=>x(Y)},rO(k)))}),c.jsxs("div",{className:"hidden items-center justify-between border-t border-border-light px-4 py-2 text-xs text-fg-dim lg:flex",children:[c.jsxs("span",{children:[c.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"↑↓"})," navigate"," ",c.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"↵"})," open"," ",c.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"esc"})," close"," ",c.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:">"})," commands"]}),c.jsx("span",{className:"tabular-nums",children:C.length>0?`${C.length} result${C.length===1?"":"s"}`:""})]})]})]})})}function rO(t){return t.kind==="note"?`note:${t.id}`:t.kind==="tag"?`tag:${t.name}`:`cmd:${t.id}`}function sO({entry:t,index:a,selected:r,onPick:i,onHover:u}){const f=r?"bg-accent/10 text-fg":"text-fg-muted";return c.jsx("div",{id:`qs-opt-${a}`,role:"option",tabIndex:-1,"aria-selected":r,"data-qs-idx":a,onMouseEnter:u,onMouseDown:h=>{h.preventDefault(),i()},className:`mx-1.5 flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-sm ${f}`,children:t.kind==="note"?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"note"}),c.jsx("span",{className:t.titleKind==="timestamp"?"truncate title-timestamp":"truncate font-medium",children:t.title}),t.path?c.jsx("span",{className:"ml-auto truncate font-mono text-xs text-fg-dim",children:t.path}):null]}):t.kind==="tag"?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"tag"}),c.jsxs("span",{className:"font-mono",children:["#",t.name]}),c.jsx("span",{className:"ml-auto text-xs tabular-nums text-fg-dim",children:t.count})]}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-xs uppercase tracking-wider text-accent",children:"cmd"}),c.jsx("span",{className:"font-medium",children:t.label}),c.jsx("span",{className:"ml-auto text-xs text-fg-dim",children:t.description})]})})}function iO(){const t=tl(f=>f.open),a=tl(f=>f.setOpen),r=tl(f=>f.toggle),i=ae(f=>f.activeVaultId);b.useEffect(()=>{const f=h=>{h.key==="k"&&(h.metaKey||h.ctrlKey)&&!h.altKey&&!h.shiftKey&&(h.preventDefault(),r())};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r]);const u=b.useRef(i);return b.useEffect(()=>{u.current!==i&&(u.current=i,a(!1))},[i,a]),!t||i===null?null:c.jsx(aO,{onClose:()=>a(!1)})}const Tb="parachute.rail-collapsed";function lO(){const[t,a]=b.useState(()=>{try{return localStorage.getItem(Tb)==="1"}catch{return!1}}),r=b.useCallback(()=>{a(i=>{const u=!i;try{localStorage.setItem(Tb,u?"1":"0")}catch{}return u})},[]);return[t,r]}function uO(){const t=ae(h=>h.getActiveVault()),a=Sm(),[r,i]=lO();if(!t)return null;const u=a.filter(h=>h.id!=="foot"),f=a.find(h=>h.id==="foot");return c.jsxs("aside",{"aria-label":"Primary",className:`glass-panel sticky top-0 hidden h-dvh shrink-0 flex-col border-r border-border transition-[width] duration-(--dur-move) ease-out lg:flex ${r?"w-16":"w-60"}`,style:{paddingTop:"env(safe-area-inset-top)"},children:[c.jsxs("div",{className:r?"flex flex-col items-stretch gap-2 p-3":"p-3",children:[c.jsxs("div",{className:r?"":"flex items-start gap-1.5",children:[c.jsx("div",{className:"min-w-0 flex-1",children:c.jsx(Em,{variant:"rail",collapsed:r})}),c.jsx("button",{type:"button",onClick:i,"aria-label":r?"Expand the sidebar":"Collapse the sidebar","aria-expanded":!r,title:r?"Expand":"Collapse",className:`focus-ring grid shrink-0 place-items-center rounded-lg text-fg-dim hover:bg-bg hover:text-fg-muted ${r?"mx-auto mt-2 h-8 w-8":"h-9 w-7"}`,children:c.jsx("span",{"aria-hidden":!0,className:`transition-transform duration-(--dur-move) ease-out ${r?"rotate-180":""}`,children:c.jsx(Lj,{width:16,height:16})})})]}),c.jsx(cO,{collapsed:r})]}),c.jsx("nav",{"aria-label":"Your vault",className:"flex-1 overflow-y-auto px-3 pb-3",children:u.map(h=>c.jsx(oO,{band:h,collapsed:r},h.id))}),c.jsxs("div",{"data-nav-band":"foot",className:"border-t border-border p-3",children:[f==null?void 0:f.items.map(h=>r?c.jsx(Sh,{item:h,collapsed:!0},h.id):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("div",{className:"min-w-0 flex-1",children:c.jsx(Sh,{item:h,collapsed:!1})}),c.jsx(xh,{})]},h.id)),r?c.jsx("div",{className:"mt-1 flex justify-center",children:c.jsx(xh,{})}):null]})]})}function oO({band:t,collapsed:a}){return c.jsxs("div",{"data-nav-band":t.id,children:[t.label&&!a?c.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[c.jsx("span",{children:t.label}),t.sublabel?c.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.label&&a?c.jsx("div",{"aria-hidden":!0,className:"mx-2 mt-3 mb-2 border-t border-border-light"}):null,t.items.map(r=>c.jsx(Sh,{item:r,collapsed:a},r.id))]})}function Sh({item:t,collapsed:a}){const r=Ge(),i=t.match(r);return c.jsxs(_e,{to:t.to,"data-nav-item":t.id,"aria-current":i?"page":void 0,"aria-label":a?t.label:void 0,title:a?t.label:void 0,className:`focus-ring flex items-center rounded-lg font-round text-sm transition-colors duration-(--dur-quick) ease-out ${a?"justify-center px-0 py-2":"gap-3 px-3 py-2"} ${i?"bg-grass-soft font-semibold text-grass-ink":"font-medium text-fg-muted hover:bg-bg hover:text-fg"}`,children:[c.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),a?null:c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})]})}function cO({collapsed:t}){const a=tl(r=>r.setOpen);return t?c.jsx("button",{type:"button",onClick:()=>a(!0),"aria-label":"Search",title:"Search (⌘K)",className:"focus-ring mx-auto grid h-9 w-9 place-items-center rounded-lg border border-border bg-card text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:border-accent/50 hover:text-fg-muted",children:c.jsx(co,{width:16,height:16})}):c.jsxs("button",{type:"button",onClick:()=>a(!0),className:"focus-ring mt-2 flex w-full items-center gap-2.5 rounded-lg border border-border bg-card px-3 py-2 text-left font-round text-sm text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:border-accent/50 hover:text-fg-muted",children:[c.jsx("span",{"aria-hidden":!0,className:"grid h-4 w-4 shrink-0 place-items-center",children:c.jsx(co,{width:16,height:16})}),c.jsx("span",{className:"flex-1",children:"Search…"}),c.jsx("kbd",{className:"shrink-0 rounded border border-border px-1.5 py-0.5 font-round text-[10px] text-fg-dim",children:"⌘K"})]})}function fO(){const t=ae(m=>m.activeVaultId!==null),{pathname:a}=Ge(),[r,i]=b.useState(!1),u=b.useRef(null),f=b.useRef(null),h=b.useId();return b.useEffect(()=>{i(!1)},[a]),b.useEffect(()=>{if(!r)return;const m=y=>{var S;y.key==="Escape"&&(i(!1),(S=f.current)==null||S.focus())},p=y=>{u.current&&y.target instanceof Node&&!u.current.contains(y.target)&&i(!1)};return document.addEventListener("keydown",m),document.addEventListener("pointerdown",p),()=>{document.removeEventListener("keydown",m),document.removeEventListener("pointerdown",p)}},[r]),!t||Z0(a)||a==="/new"?null:c.jsxs("div",{ref:u,className:"fixed top-6 right-6 z-30 hidden lg:block",children:[c.jsx("button",{ref:f,type:"button",onClick:()=>i(m=>!m),"aria-label":r?"Close create menu":"Create","aria-expanded":r,"aria-controls":h,title:r?void 0:"Create",className:"focus-ring grid h-12 w-12 place-items-center rounded-full bg-accent text-(--color-on-accent) shadow-lift transition-transform duration-(--dur-move) ease-out hover:scale-105 hover:bg-accent-hover motion-reduce:hover:scale-100",children:c.jsx("span",{"aria-hidden":"true",className:`transition-transform duration-(--dur-move) ease-out ${r?"rotate-45":""}`,children:c.jsx(Kh,{width:24,height:24,strokeWidth:2})})}),r?c.jsxs("div",{id:h,"aria-label":"Create",className:"mt-3 flex flex-col items-end gap-3",children:[c.jsx(Od,{to:"/new",label:"New note",icon:c.jsx(Oj,{width:18,height:18})}),c.jsx(Od,{to:"/new?voice=1",label:"Voice note",icon:c.jsx(Mj,{width:18,height:18})}),c.jsx(Od,{to:"/import",label:"Import notes",icon:c.jsx(Vx,{width:18,height:18})})]}):null]})}function Od({to:t,label:a,icon:r}){return c.jsxs(_e,{to:t,"data-speed-dial-verb":a,className:"focus-ring group flex items-center gap-3 rounded-full",children:[c.jsx("span",{className:"rounded-full border border-border bg-card px-3.5 py-1.5 text-sm font-medium text-fg shadow-soft transition-colors duration-(--dur-quick) ease-out group-hover:border-accent/50",children:a}),c.jsx("span",{"aria-hidden":"true",className:"grid h-11 w-11 place-items-center rounded-full bg-fg text-bg shadow-soft transition-transform duration-(--dur-move) ease-out group-hover:scale-105 motion-reduce:group-hover:scale-100",children:r})]})}const dO=4e3;function hO(){const t=aa(r=>r.toasts),a=aa(r=>r.dismiss);return b.useEffect(()=>{if(t.length===0)return;const r=t.map(i=>window.setTimeout(()=>a(i.id),i.durationMs??dO));return()=>{for(const i of r)window.clearTimeout(i)}},[t,a]),t.length===0?null:c.jsx("output",{"aria-live":"polite",className:"pointer-events-none fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 flex-col items-center gap-2",children:t.map(r=>c.jsxs("div",{className:`enter-rise pointer-events-auto flex max-w-md items-center gap-3 rounded-lg border px-4 py-2 text-sm shadow-lift backdrop-blur ${r.tone==="error"?"border-(--color-danger-border) bg-(--color-danger-soft) text-(--color-danger)":r.tone==="success"?"border-accent/40 bg-accent/10 text-accent":"border-border bg-card text-fg-muted"}`,children:[c.jsx("span",{children:r.message}),c.jsx("button",{type:"button",onClick:()=>a(r.id),"aria-label":"Dismiss",className:"focus-ring text-fg-dim hover:text-fg",children:"×"})]},r.id))})}function mO(t={}){const{immediate:a=!1,onNeedReload:r,onNeedRefresh:i,onOfflineReady:u,onRegistered:f,onRegisteredSW:h,onRegisterError:m}=t;let p,y;const S=async(x=!0)=>{await y};async function v(){if("serviceWorker"in navigator){if(p=await Qe(async()=>{const{Workbox:x}=await import("./workbox-window.prod.es5-BBnX5xw4.js");return{Workbox:x}},[]).then(({Workbox:x})=>new x("/sw.js",{scope:"/",type:"classic"})).catch(x=>{m==null||m(x)}),!p)return;p.addEventListener("activated",x=>{(x.isUpdate||x.isExternal)&&(r?r():window.location.reload())}),p.addEventListener("installed",x=>{x.isUpdate||u==null||u()}),p.register({immediate:a}).then(x=>{h?h("/sw.js",x):f==null||f(x)}).catch(x=>{m==null||m(x)})}}return y=v(),S}function pO(t={}){const{immediate:a=!0,onNeedReload:r,onNeedRefresh:i,onOfflineReady:u,onRegistered:f,onRegisteredSW:h,onRegisterError:m}=t,[p,y]=b.useState(!1),[S,v]=b.useState(!1),[x]=b.useState(()=>mO({immediate:a,onNeedReload:r,onOfflineReady(){v(!0),u==null||u()},onNeedRefresh(){y(!0),i==null||i()},onRegistered:f,onRegisteredSW:h,onRegisterError:m}));return{needRefresh:[p,y],offlineReady:[S,v],updateServiceWorker:x}}const jb={BASE_URL:"/"};function gO(t,a){const r=t&&t.length>0?t:a;return!r||r===""||r==="/"?"":r.replace(/\/$/,"")}function yO(){const t=typeof import.meta<"u"&&jb?jb:void 0,a=t?t.VITE_BASE_PATH:void 0,r=t?t.BASE_URL:void 0;return gO(a,r)}const vO=yO();function bO(t){return pl()===vO}async function xO(t=typeof navigator>"u"?void 0:navigator,a){if(!t||!("serviceWorker"in t))return 0;const r=t.serviceWorker;if(!r||typeof r.getRegistrations!="function")return 0;const i=pl(),u=await r.getRegistrations();let f=0;for(const h of u)try{const p=new URL(h.scope).pathname.replace(/\/$/,"")||"/";if(p===i||!(/^\/notes$/.test(p)||/^\/surface\/[a-z0-9][a-z0-9_-]*$/.test(p)))continue;await h.unregister(),f+=1,typeof console<"u"&&console.info(`[notes-ui] unregistered stale service worker at scope ${h.scope} (runtime mount is ${i})`)}catch(m){typeof console<"u"&&console.warn(`[notes-ui] failed to inspect/unregister SW: ${String(m)}`)}return f}function SO(){return pO({onRegisteredSW(t,a){if(!a)return;const r=3600*1e3;setInterval(()=>{a.update().catch(()=>{})},r)},onNeedReload(){BE()}}),null}function wO(){return bO()?c.jsx(SO,{}):null}function EO(){const t=ae(u=>u.activeVaultId),a=ae(u=>u.getActiveVault()),r=Rr(u=>t?u.byVault[t]??null:null),i=Dr(u=>t?u.byVault[t]??null:null);return!a||!t?null:r&&!Qs(a.clientId)?c.jsx(TO,{reason:r.reason,vaultIssuer:a.issuer??a.url,vaultScope:a.scope,vaultId:t}):i&&i.state==="down"?c.jsx(jO,{vaultUrl:a.url,vaultId:t}):null}function TO({reason:t,vaultIssuer:a,vaultScope:r,vaultId:i}){const[u,f]=b.useState(!1),[h,m]=b.useState(null),[p,y]=b.useState(!1);async function S(){m(null),y(!1),f(!0);try{const{authorizeUrl:v}=await pm(a,r,void 0,{priorHaltedVaultId:i});window.location.assign(v)}catch(v){v instanceof No?y(!0):m(v instanceof Error?v.message:String(v))}finally{f(!1)}}return c.jsxs("div",{role:"alert","aria-live":"assertive",className:"border-b border-red-500/40 bg-red-500/10 px-4 py-3 text-sm text-red-200 md:px-6",children:[c.jsxs("div",{className:"mx-auto flex max-w-5xl flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[c.jsxs("div",{children:[c.jsx("p",{className:"font-medium text-red-100",children:"Vault session expired"}),c.jsx("p",{className:"text-xs text-red-200/80",children:t}),h?c.jsx("p",{className:"mt-1 text-xs text-red-300",children:h}):null]}),c.jsx("button",{type:"button",onClick:S,disabled:u,className:"self-start rounded-lg bg-red-500/30 px-3 py-1.5 text-xs font-medium text-red-50 hover:bg-red-500/50 disabled:cursor-not-allowed disabled:opacity-60 md:self-auto",children:u?"Starting OAuth…":"Reconnect to vault"})]}),p?c.jsx("div",{className:"mx-auto mt-2 max-w-5xl",children:c.jsx(rS,{})}):null]})}function jO({vaultUrl:t,vaultId:a}){const r=ke(),i=pt(),u=Dr(y=>y.resetToHealthy),[f,h]=b.useState(!1);async function m(){if(r){h(!0);try{await r.vaultInfo(!1),i.invalidateQueries({queryKey:["notes",a]}),i.invalidateQueries({queryKey:["tags",a]}),i.invalidateQueries({queryKey:["vaultInfo",a]}),i.invalidateQueries({queryKey:["note",a]})}catch{}finally{h(!1)}}}const p=AO(t)?"Try `parachute start vault` in a terminal.":null;return c.jsx("div",{role:"alert","aria-live":"polite",className:"border-b border-red-500/30 bg-red-500/5 px-4 py-3 text-sm text-red-200 md:px-6",children:c.jsxs("div",{className:"mx-auto flex max-w-5xl flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[c.jsxs("div",{children:[c.jsx("p",{className:"font-medium text-red-100",children:"Vault not reachable"}),c.jsxs("p",{className:"text-xs text-red-200/80",children:["Notes can't sync until it's back online.",p?` ${p}`:""]})]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",onClick:m,disabled:f||!r,className:"self-start rounded-lg bg-red-500/20 px-3 py-1.5 text-xs font-medium text-red-50 hover:bg-red-500/40 disabled:cursor-not-allowed disabled:opacity-60 md:self-auto",children:f?"Retrying…":"Retry now"}),c.jsx("button",{type:"button",onClick:()=>u(a),className:"self-start rounded-lg px-3 py-1.5 text-xs text-red-200/80 hover:text-red-100 md:self-auto","aria-label":"Dismiss banner",title:"Dismiss",children:"Dismiss"})]})]})})}const NO=/^(10|192\.168|172\.(1[6-9]|2\d|3[0-1]))\./;function AO(t){try{const r=new URL(t).hostname.replace(/^\[/,"").replace(/\]$/,"");return!!(r==="localhost"||r==="127.0.0.1"||r==="::1"||r.endsWith(".local")||NO.test(r))}catch{return!1}}function wh({icon:t,title:a,description:r,action:i,className:u=""}){return c.jsxs("div",{className:`card p-10 text-center ${u}`.trim(),children:[t?c.jsx("div",{className:"mb-3 flex justify-center text-fg-dim","aria-hidden":"true",children:t}):null,c.jsx("p",{className:"text-fg-muted",children:a}),r?c.jsx("p",{className:"mt-1 text-sm text-fg-dim",children:r}):null,i?c.jsx("div",{className:"mt-4 flex justify-center",children:i}):null]})}const _O="parachute:door-descriptor";function fS(){const t=typeof window<"u"&&window.location?window.location.origin:"";return`${_O}:${t}`}let Pt,Eh=null,Th=!1,xo=!1;const lo=new Set,RO=["monthly","quarterly","yearly"];function CO(t){if(!t||typeof t!="object"||Array.isArray(t))return null;const a=t;if(typeof a.available!="boolean"||a.price!==void 0&&typeof a.price!="number"||a.label!==void 0&&typeof a.label!="string")return null;const r={available:a.available};return typeof a.price=="number"&&(r.price=a.price),typeof a.label=="string"&&(r.label=a.label),r}function OO(t){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return;const a=t,r={};let i=!1;for(const u of RO){if(!(u in a))continue;const f=CO(a[u]);f&&(r[u]=f,i=!0)}return i?r:void 0}function MO(t){const a=t,{intervals:r,...i}=a,u=OO(r);return u!==void 0?{...i,intervals:u}:i}function dS(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;const a=t,r=a.auth,i=!!r&&Array.isArray(r.methods)&&r.methods.length>0&&r.methods.every(S=>typeof S=="string")&&typeof r.signin_path=="string"&&r.signin_path.startsWith("/"),u=a.plans===void 0||Array.isArray(a.plans)&&a.plans.every(S=>!!S&&typeof S=="object"),f=u&&Array.isArray(a.plans)?a.plans.map(S=>MO(S)):void 0;if(i&&u)return f?{...a,plans:f}:a;const{auth:h,plans:m,...p}=a,y={...p};return i&&(y.auth=a.auth),u&&f&&(y.plans=f),y}async function DO(t){try{const a=await t("/.well-known/parachute-account");return a.ok?dS(await a.json()):null}catch{return null}}function hS(){try{const t=localStorage.getItem(fS());if(t==null)return;const a=dS(JSON.parse(t));return a===null?void 0:a}catch{return}}function kO(t){try{localStorage.setItem(fS(),JSON.stringify(t))}catch{}}function LO(t){Th||(Th=!0,Eh=DO(t).then(a=>{if(a!==null){const r=JSON.stringify(Pt)!==JSON.stringify(a);if(Pt=a,kO(a),r)for(const i of lo)i(a)}else if(Pt===void 0){Pt=null;for(const r of lo)r(null)}return xo=!0,lo.clear(),Pt??null}).finally(()=>{Eh=null}))}async function mS(t=fetch.bind(globalThis),a){if(Pt===void 0){const r=hS();r!==void 0&&(Pt=r)}return a&&!xo&&lo.add(a),LO(t),Pt!==void 0?Pt:Eh??null}function UO(){if(Pt===void 0){const t=hS();t!==void 0&&(Pt=t)}return Pt??null}function zO(){Pt===null&&xo&&(Th=!1,xo=!1)}function t5(t){return t.length===0?{kind:"first-vault"}:t.length===1&&t[0]?{kind:"welcome-back",vault:t[0]}:{kind:"picker",vaults:t}}async function VO({hasLocalActiveVault:t,fetchImpl:a=fetch.bind(globalThis)}){let r;try{r=await xl(a)}catch{return{kind:"front-door"}}if(!r.signed_in)return{kind:"front-door"};r.email&&ax(r.email),r.password_change_required&&Ft.getState().markGate("force_change_password");try{const i=await Fx(r.csrf,a);sx(i.token,r.email??r.username??null)}catch(i){if(BO(i))return{kind:"signed-in",email:r.email,username:r.username,vaults:[]}}try{const{vaults:i}=await Zx(a);return{kind:"signed-in",email:r.email,username:r.username,vaults:i}}catch(i){return{kind:"net-error",message:i instanceof Error?i.message:"Unknown error"}}}function BO(t){return t instanceof bl?t.status===403&&t.message==="force_change_password"?(Ft.getState().markGate("force_change_password"),!0):t.status===423?(Ft.getState().markGate("admin_locked"),!0):!1:!1}function HO({children:t}){const[a]=b.useState(()=>new IN({defaultOptions:{queries:{retry:(r,i)=>{var u;if(!(i instanceof Error))return r<2;if(i instanceof $a)return!1;if(i instanceof Jn){const f=ae.getState().activeVaultId;return(f?(u=Dr.getState().byVault[f])==null?void 0:u.state:void 0)==="down"?!1:r<1}return r<2},refetchOnWindowFocus:!1,staleTime:1e4}}}));return c.jsx(KN,{client:a,children:t})}const qO=[/^\/api\//,/^\/oauth\/(?!callback)/,/^\/\.well-known\//,/^\/signup/,/^\/login/,/^\/logout/,/^\/auth\//,/^\/console/,/^\/admin/,/^\/account\//,/^\/billing/,/^\/unsubscribe/,/^\/health/,/^\/vault\//,/^\/u\//];function $O(t){return qO.some(a=>a.test(t))}function Ps({size:t=24,className:a}){return c.jsxs("svg",{width:t,height:t,viewBox:"0 0 64 64","aria-hidden":"true",className:a,children:[c.jsx("path",{d:"M8 30 Q32 2 56 30 Q49 37 42 30 Q37 38 32 30 Q27 38 22 30 Q15 37 8 30 Z",fill:"var(--color-accent-light)"}),c.jsx("path",{d:"M8 30 Q32 2 56 30",fill:"none",stroke:"var(--color-accent)",strokeWidth:"1.4"}),c.jsx("line",{x1:"8",y1:"30",x2:"30",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),c.jsx("line",{x1:"22",y1:"30",x2:"30",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),c.jsx("line",{x1:"42",y1:"30",x2:"34",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),c.jsx("line",{x1:"56",y1:"30",x2:"34",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),c.jsx("rect",{x:"26",y:"50",width:"12",height:"10",rx:"2.5",fill:"var(--color-sun)",stroke:"var(--color-sun-ink)",strokeWidth:"1"})]})}function QO({size:t=22}){return c.jsxs(_e,{to:"/",className:"focus-ring inline-flex items-center gap-2 rounded-lg font-round font-bold text-fg hover:text-accent",children:[c.jsx(Ps,{size:t}),c.jsx("span",{children:"Parachute"})]})}const pS="/welcome";function Md({signedIn:t,netError:a,onRetry:r}={}){return t?c.jsx(JO,{email:t.email,username:t.username,vaults:t.vaults}):a?c.jsx(WO,{message:a,onRetry:r}):c.jsx(PO,{})}function Tl({children:t}){return c.jsxs("div",{className:"relative flex min-h-[calc(100dvh-4rem)] flex-col",children:[c.jsx("div",{className:"flex items-center px-6 pt-6 sm:px-10",children:c.jsx(QO,{})}),c.jsx("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-10 text-center",children:c.jsx("div",{className:"mx-auto w-full max-w-md",children:t})})]})}function gS(){return c.jsx("div",{className:"mt-8 border-t border-border pt-6",children:c.jsxs("p",{className:"font-round text-sm text-fg-muted",children:["Self-hosting?"," ",c.jsx(_e,{to:"/add",className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Connect your own vault →"})," ",c.jsx("span",{className:"text-fg-dim",children:"(your notes stay on your server)"})]})})}function IO(t){var r;if(!t)return"neutral";const a=((r=t.auth)==null?void 0:r.methods)??[];return t.auth!=null&&!a.includes("magic_link")?"hub":t.door==="cloud"||a.includes("magic_link")?"cloud":"neutral"}function KO(t){var i;if(!t||t.length===0)return null;let a=null,r=null;for(const u of t){const f=(i=u.intervals)==null?void 0:i.yearly;f!=null&&f.available&&typeof f.price=="number"&&f.price>0&&(a=a===null?f.price:Math.min(a,f.price)),typeof u.price_month=="number"&&u.price_month>0&&(r=r===null?u.price_month:Math.min(r,u.price_month))}return a!==null?`Plans from $${a} a year.`:r!==null?`Plans from $${r} a month.`:null}const GO="Three months";function YO(t){const a=typeof t=="string"?t.trim():"";return`${a&&a.length<=40?a:GO} free, no card.`}function PO(){const[t,a]=b.useState(()=>UO());b.useEffect(()=>{let i=!0;return zO(),mS(void 0,u=>{i&&a(u)}).then(u=>{i&&a(u)}),()=>{i=!1}},[]);const r=IO(t);return r==="hub"&&(t!=null&&t.auth)?c.jsx(ZO,{auth:t.auth,signupPath:t.signup_path}):r==="cloud"?c.jsx(XO,{plans:t==null?void 0:t.plans,trialLengthLabel:t==null?void 0:t.trial_length_label}):c.jsx(FO,{})}function FO(){return c.jsxs(Tl,{children:[c.jsx(Ps,{size:60,className:"mx-auto mb-6 drop-in"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),c.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",c.jsx("span",{className:"accent-word",children:"land."})]}),c.jsx("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:"Sign in to your parachute."}),c.jsx(_e,{to:"/add",className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Sign in →"})]})}function XO({plans:t,trialLengthLabel:a}){const r=Mr(),[i]=Qh(),u=i.get("link")==="expired",[f,h]=b.useState(lE()??""),[m,p]=b.useState(!1),[y,S]=b.useState(null),v=/.+@.+\..+/.test(f.trim()),x=KO(t),T=YO(a);async function j(_){if(_.preventDefault(),!(!v||m)){p(!0),S(null);try{const C=await xl();await iN(f.trim(),C.csrf,pS),ax(f.trim()),r("/check-email")}catch(C){p(!1),S(C instanceof Error?`Couldn't send the link: ${C.message}`:"Couldn't send the link. Please try again.")}}}return c.jsxs(Tl,{children:[c.jsx(Ps,{size:60,className:"mx-auto mb-6 drop-in"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),c.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",c.jsx("span",{className:"accent-word",children:"land."})]}),u?c.jsxs("p",{className:"mx-auto mb-6 max-w-sm rounded-xl border border-sun bg-sun-soft px-4 py-3 text-sm text-sun-ink",children:["That link has ",c.jsx("span",{className:"font-serif italic",children:"expired."})," No harm done — we'll send a fresh one."]}):null,c.jsx("form",{onSubmit:j,className:"mx-auto w-full max-w-sm",children:c.jsxs("div",{className:"composer flex flex-col gap-3 p-4 text-left",children:[c.jsx("label",{htmlFor:"email",className:"eyebrow",children:"Sign in or create your account"}),c.jsx("input",{id:"email",type:"email",inputMode:"email",autoComplete:"email",autoFocus:!0,value:f,onChange:_=>h(_.target.value),placeholder:"you@example.com","aria-label":"Email address",className:"input input-on-bg"}),c.jsx("button",{type:"submit",disabled:!v||m,className:"btn btn-primary btn-lg justify-center rounded-full shadow-soft",children:m?"Sending your link…":"Email me a sign-in link"})]})}),c.jsx("p",{className:"mx-auto mt-3 max-w-sm font-round text-sm text-fg-muted",children:"One link does both — if you're new, it creates your account, and the email will say so. No password."}),c.jsxs("p",{className:"mx-auto mt-3 max-w-sm font-round text-xs text-fg-dim",children:[T,x?` ${x}`:""]}),y?c.jsx("p",{className:"mx-auto mt-3 max-w-sm rounded-lg border border-danger-border bg-danger-soft px-3 py-2 text-sm text-danger",children:y}):null,c.jsx(gS,{})]})}function ZO({auth:t,signupPath:a}){const r=Mr(),[i,u]=b.useState(!1),f=typeof window<"u"?window.location.host:"";async function h(){if(!i){u(!0);try{const p=await I0(window.location.origin)??window.location.origin,{authorizeUrl:y}=await pm(p);window.location.assign(y)}catch{u(!1),r("/add")}}}function m(){const p=encodeURIComponent(px(pS));window.location.assign(`${t.signin_path}?next=${p}`)}return c.jsxs(Tl,{children:[c.jsx(Ps,{size:60,className:"mx-auto mb-6 drop-in"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),c.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",c.jsx("span",{className:"accent-word",children:"land."})]}),c.jsxs("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:["Sign in to ",c.jsx("span",{className:"font-semibold text-fg",children:f||"your parachute"}),"."]}),c.jsx("button",{type:"button",onClick:h,disabled:i,className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:i?"Opening…":"Open your parachute →"}),c.jsx("p",{className:"mx-auto mt-6 max-w-sm font-round text-sm text-fg-muted",children:c.jsx("button",{type:"button",onClick:m,className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Manage this parachute →"})}),a?c.jsxs("p",{className:"mx-auto mt-3 max-w-sm font-round text-sm text-fg-muted",children:["New here?"," ",c.jsx("a",{href:a,className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Create your account →"})]}):c.jsx("p",{className:"mx-auto mt-3 max-w-sm font-round text-xs text-fg-dim",children:"Accounts on this parachute are created by its operator."}),c.jsx(gS,{})]})}function JO({email:t,username:a,vaults:r}){const i=Mr(),[u,f]=b.useState(!1),h=r.length===1?r[0]:null;async function m(){if(!(!h||u)){f(!0);try{await Do(h.name),bm(h.name),i("/")}catch{i("/welcome",{replace:!0})}}}async function p(){try{const y=await xl();await fN(y.csrf)}finally{Oh(),i("/",{replace:!0}),window.location.assign("/")}}return c.jsxs(Tl,{children:[c.jsx(Ps,{size:56,className:"mx-auto mb-6"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Signed in"}),c.jsxs("h1",{className:"hero-title mb-6",style:{fontSize:"clamp(1.8rem, 4vw, 2.4rem)"},children:["You're already signed in as"," ",c.jsx("span",{className:"accent-word",children:t??a??"your account"}),"."]}),c.jsxs("div",{className:"flex flex-col items-center gap-4",children:[h?c.jsx("button",{type:"button",onClick:m,disabled:u,className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:u?`Opening ${h.name}…`:`Open ${h.name} →`}):c.jsx(_e,{to:"/welcome",className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Choose a vault →"}),c.jsx("button",{type:"button",onClick:p,className:"font-round text-sm font-semibold text-fg-dim hover:text-accent",children:"Not you? Sign out"})]})]})}function WO({message:t,onRetry:a}){return c.jsxs(Tl,{children:[c.jsx(Ps,{size:56,className:"mx-auto mb-6"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Almost there"}),c.jsxs("h1",{className:"hero-title mb-4",style:{fontSize:"clamp(1.8rem, 4vw, 2.4rem)"},children:["You're signed in — we just couldn't fetch your ",c.jsx("span",{className:"accent-word",children:"vaults."})]}),c.jsx("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:t}),c.jsx("button",{type:"button",onClick:()=>a?a():window.location.reload(),className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Try again"})]})}function eM({tags:t,input:a,onInputChange:r,onAdd:i,onRemove:u}){return c.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-sm",children:[c.jsx("span",{className:"shrink-0 text-xs uppercase tracking-wider text-fg-dim",children:"Tags"}),t.map(f=>c.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-full border border-border bg-bg/60 px-2 py-0.5 text-xs text-fg-muted",children:[c.jsx("span",{className:"min-w-0 break-all",children:f}),c.jsx("button",{type:"button",onClick:()=>u(f),"aria-label":`Remove tag ${f}`,className:"text-fg-dim hover:text-red-400",children:"×"})]},f)),c.jsx("input",{type:"text",value:a,onChange:f=>r(f.target.value),onKeyDown:f=>{f.key==="Enter"||f.key===","?(f.preventDefault(),i(a)):f.key==="Backspace"&&a===""&&t.length>0&&u(t[t.length-1])},onBlur:()=>{a.trim()&&i(a)},placeholder:"add tag…",className:"min-w-24 flex-1 rounded-lg border border-transparent bg-transparent px-1 py-0.5 text-xs text-fg focus:border-border focus:outline-none","aria-label":"Add tag"})]})}function So(t){return t.trim().replace(/^#/,"")}function tM({capability:t,className:a="mb-4 text-xs text-fg-dim"}){const r=typeof(t==null?void 0:t.minutes_remaining)=="number";return c.jsx("p",{className:a,"data-testid":"voice-unavailable",children:r?"Voice transcription comes with the Voice plan.":"Voice transcription isn't enabled on this vault."})}const nM=["audio/webm;codecs=opus","audio/mp4","audio/ogg;codecs=opus"],aM=32e3;function n5(t=nM){if(typeof MediaRecorder>"u")return null;for(const a of t)if(MediaRecorder.isTypeSupported(a))return a;return null}function rM(t){return t.startsWith("audio/webm")?"webm":t.startsWith("audio/mp4")?"m4a":t.startsWith("audio/ogg")?"ogg":t.startsWith("audio/wav")?"wav":"bin"}function a5(t){const a=t.now??(()=>Date.now()),r=t.releaseStreamOnStop??!0,i=t.MediaRecorderCtor??MediaRecorder,u=new i(t.stream,{mimeType:t.mimeType,audioBitsPerSecond:aM}),f=[];let h="idle",m=0,p=0;u.ondataavailable=S=>{S.data&&S.data.size>0&&f.push(S.data),t.onData&&t.onData(f.reduce((v,x)=>v+x.size,0))};const y=()=>{if(r)for(const S of t.stream.getTracks())S.stop()};return{get state(){return h},get mimeType(){return t.mimeType},start(){if(h!=="idle")throw new Error(`Cannot start from ${h}`);u.start(t.dataIntervalMs),m=a(),h="recording"},pause(){h==="recording"&&(u.pause(),p+=a()-m,h="paused")},resume(){h==="paused"&&(u.resume(),m=a(),h="recording")},async stop(){if(h==="idle"||h==="stopped")throw new Error(`Cannot stop from ${h}`);h==="recording"&&(p+=a()-m);const S=new Promise(v=>{u.onstop=async()=>{const x=await iM(f);v({data:x,mimeType:t.mimeType,durationMs:p})}});return u.stop(),h="stopped",y(),S},cancel(){if(h==="recording"||h==="paused")try{u.stop()}catch{}h="stopped",f.length=0,y()}}}async function sM(t){const a=t;return typeof a.arrayBuffer=="function"?a.arrayBuffer():new Promise((r,i)=>{const u=new FileReader;u.onload=()=>r(u.result),u.onerror=()=>i(u.error??new Error("FileReader error")),u.readAsArrayBuffer(t)})}async function iM(t){if(t.length===0)return new ArrayBuffer(0);const a=await Promise.all(t.map(f=>sM(f))),r=a.reduce((f,h)=>f+h.byteLength,0),i=new Uint8Array(r);let u=0;for(const f of a)i.set(new Uint8Array(f),u),u+=f.byteLength;return i.buffer}async function r5(){var t;if(typeof navigator>"u"||!((t=navigator.mediaDevices)!=null&&t.getUserMedia)){const a=new Error("Microphone is not available in this browser.");throw a.kind="unavailable",a}try{return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(a){const r=new Error(a instanceof Error?a.message:"Microphone permission denied."),i=a instanceof DOMException?a.name:"";throw r.kind=i==="NotFoundError"||i==="OverconstrainedError"?"no-device":"permission-denied",r}}function s5(t,a=new Date,r){const i=a.toISOString().replace(/[:.]/g,"-").replace(/Z$/,""),u=r&&r>0?`-part${r}`:"";return`memo-${i}${u}.${rM(t)}`}function Nb(t=new Date){const a=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),u=String(t.getHours()).padStart(2,"0"),f=String(t.getMinutes()).padStart(2,"0"),h=String(t.getSeconds()).padStart(2,"0");return`Notes/${a}/${r}-${i}/${u}-${f}-${h}`}const lM=/(?:^|\s)#([a-zA-Z][\w-]*)/g;function uM(t){const a=new Set;for(const r of t.matchAll(lM)){const i=So(r[1]??"");i&&a.add(i)}return[...a]}function oM(t){const a=Array.from(new Set([...t.tags,...uM(t.content)].filter(i=>i.length>0))),r={content:t.content,path:t.path.trim(),metadata:{source:"text"}};return a.length&&(r.tags=a),r}function cM(t,a,r,i,u=600){const f=b.useRef(r);f.current=r;const h=b.useRef(i);h.current=i;const m=b.useMemo(()=>JSON.stringify(r),[r]);b.useEffect(()=>{if(!t||!a)return;if(!i){Gx(t,a);return}const p=window.setTimeout(()=>Id(t,a,f.current),u);return()=>window.clearTimeout(p)},[m,i,t,a,u]),b.useEffect(()=>{if(!t||!a)return;const p=()=>{h.current&&Id(t,a,f.current)},y=()=>{document.visibilityState==="hidden"&&p()};return window.addEventListener("pagehide",p),document.addEventListener("visibilitychange",y),()=>{window.removeEventListener("pagehide",p),document.removeEventListener("visibilitychange",y)}},[t,a])}const fM={tags:[{name:"capture",description:"Notes captured directly by the user (text or voice)."}]};function dM(t,a){const r=t??[],i=a??[];if(r.length!==i.length)return!1;for(let u=0;u<r.length;u++)if(r[u]!==i[u])return!1;return!0}function hM(t,a){if(!a)return{name:t.name,status:"missing",expected:t,actual:null,differences:[]};const r=[];(a.description??"")!==t.description&&r.push("description");const i=t.parent_names??null;return dM(a.parent_names,i)||r.push("parent_names"),{name:t.name,status:r.length===0?"ok":"misaligned",expected:t,actual:a,differences:r}}async function mM(t){const a=await t.listTagsWithSchema(),r=new Map(a.map(h=>[h.name,h])),i=fM.tags.map(h=>hM(h,r.get(h.name))),u=i.filter(h=>h.status==="missing"),f=i.filter(h=>h.status==="misaligned");return{ok:u.length===0&&f.length===0,missing:u,misaligned:f,rows:i}}const Dd=new Set;async function pM(t,a){for(const r of a)await t.updateTag(r.name,{description:r.description,...r.parent_names?{parent_names:r.parent_names}:{}})}async function gM(t,a){if(!Dd.has(t)){Dd.add(t);try{const i=(await mM(a)).missing.map(u=>u.expected);i.length>0&&await pM(a,i)}catch(r){Dd.delete(t),typeof console<"u"&&console.warn(`[schema-ensure] failed to ensure required schema for vault ${t}:`,r)}}}const yS="home-composer-input";function vS({vault:t,focused:a=!1}){var ee;const r=aa(M=>M.push),i=z_(),u=ke(),{roles:f}=wl(t.id),h=H0(),m=((ee=h.capability)==null?void 0:ee.enabled)===!1,p=b.useRef(Nb()),[y]=b.useState(()=>nN(t.id,Xu)),[S,v]=b.useState(()=>y?{...y.body,path:y.body.path||p.current}:{content:"",path:p.current,tags:[]}),[x,T]=b.useState(!1),[j,_]=b.useState(null),[C,O]=b.useState(""),B=b.useRef(y!==null),H=b.useRef(null);b.useEffect(()=>{B.current||(v(M=>{const P=H.current?M.tags.filter(oe=>oe!==H.current):M.tags,ne=P.includes(f.captureText)?P:[...P,f.captureText];return ne===M.tags?M:{...M,tags:ne}}),H.current=f.captureText)},[f.captureText]);const k=!B.current&&(S.tags.length===0||S.tags.length===1&&S.tags[0]===f.captureText),Y=S.content.trim().length>0||!k||S.path.trim().length>0&&S.path!==p.current;cM(t.id,Xu,S,Y);const Q=b.useRef(S);Q.current=S;const G=b.useRef(Y);G.current=Y;const F=b.useCallback(()=>{G.current&&Id(t.id,Xu,Q.current)},[t.id]);b.useEffect(()=>()=>F(),[F]);const Z=b.useRef(null);b.useEffect(()=>{const M=Z.current;M&&(M.style.height="",S.content&&(M.style.height=`${M.scrollHeight}px`))},[S.content]);const le=x||S.content.length>0,de=S.content.trim().length>0&&S.path.trim().length>0&&!i.isPending,ye=M=>{const P=So(M);!P||S.tags.includes(P)||(B.current=!0,v(ne=>({...ne,tags:[...ne.tags,P]})),O(""))},we=M=>{B.current=!0,v(P=>({...P,tags:P.tags.filter(ne=>ne!==M)}))},re=()=>{de&&(u&&gM(t.id,u),_(null),i.mutate(oM({content:S.content,path:S.path,tags:S.tags}),{onSuccess:()=>{var M;Gx(t.id,Xu),p.current=Nb(),B.current=!1,H.current=f.captureText,O(""),v({content:"",path:p.current,tags:[f.captureText]}),(M=Z.current)==null||M.blur(),T(!1),r(`Saved to ${t.name}`,"success")},onError:M=>{_(M instanceof Uo?"Session expired. Reconnect to save.":M instanceof Error?M.message:"Couldn't save — try again.")}}))};return c.jsxs("form",{"aria-label":"Write a note",className:`composer mb-6 px-5 py-4 ${a?"composer-focus":""}`,onSubmit:M=>{M.preventDefault(),re()},onFocus:()=>T(!0),onBlur:M=>{F(),M.currentTarget.contains(M.relatedTarget)||T(!1)},children:[c.jsx("textarea",{id:yS,ref:Z,rows:1,value:S.content,onChange:M=>v(P=>({...P,content:M.target.value})),onKeyDown:M=>{(M.metaKey||M.ctrlKey)&&M.key==="Enter"&&(M.preventDefault(),re())},"aria-label":"What's on your mind?",placeholder:"What's on your mind?",className:"block max-h-[45vh] w-full resize-none overflow-y-auto border-0 bg-transparent text-fg text-lg outline-none [transition:min-height_var(--dur-move)_ease] placeholder:text-fg-dim",style:{minHeight:le?"6.5rem":"1.75rem"}}),le?c.jsx("div",{className:"mt-2",children:c.jsx(eM,{tags:S.tags,input:C,onInputChange:O,onAdd:ye,onRemove:we})}):null,c.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[le?c.jsx(_e,{to:"/new",onClick:F,className:"focus-ring rounded text-fg-dim text-xs hover:text-accent",children:"Open full editor →"}):c.jsxs("span",{className:"font-round text-fg-dim text-xs",children:["Autosaves to ",t.name]}),c.jsxs("div",{className:"flex items-center gap-2",children:[le?c.jsx("button",{type:"submit",disabled:!de,className:"btn btn-primary btn-touch",title:"Save (⌘⏎)",children:i.isPending?"Saving…":`Save to ${t.name}`}):null,m?null:c.jsx(_e,{to:"/new?voice=1",onClick:F,"aria-label":"Record a voice note",className:"focus-ring grid h-9 w-9 shrink-0 place-items-center rounded-full border border-border bg-bg-soft text-base transition-colors duration-(--dur-quick) ease-out hover:border-accent/50 hover:bg-accent/10",children:c.jsx("span",{"aria-hidden":"true",children:"🎙"})})]})]}),m&&le?c.jsx(tM,{capability:h.capability,className:"mt-2 text-xs text-fg-dim"}):null,j?c.jsx("p",{role:"alert",className:"mt-2 text-danger text-xs",children:j}):null]})}function bS(){const t=Sm(),a=Ge(),r=t.find(i=>i.id==="notes");return!r||r.items.length===0?null:c.jsx("nav",{"aria-label":"Lenses",className:"-mx-5 mb-6 flex gap-2 overflow-x-auto px-5 pb-1 md:-mx-8 md:px-8 lg:hidden",children:r.items.map(i=>{const u=i.match(a);return c.jsx(_e,{to:i.to,"data-nav-item":i.id,"aria-current":u?"page":void 0,className:`focus-ring shrink-0 whitespace-nowrap rounded-full border px-3.5 py-1.5 font-round text-sm transition-colors ${u?"border-transparent bg-grass-soft font-semibold text-grass-ink":"border-border bg-card font-medium text-fg-muted hover:text-fg"}`,children:i.label},i.id)})})}const yM={mcp:"MCP",api:"API",cli:"CLI",operator:"operator"};function Ab(t){const a=yM[t];if(a)return a;if(t.startsWith("agent:"))return"agent";if(t.startsWith("surface:")){const r=t.slice(8);return r?r.charAt(0).toUpperCase()+r.slice(1):"surface"}return t}function vM(t){const a=t.createdVia?`via ${Ab(t.createdVia)}`:null,r=t.lastUpdatedVia?`via ${Ab(t.lastUpdatedVia)}`:null;if(!a&&!r)return null;const i=t.createdBy??t.createdVia??null,u=t.lastUpdatedBy??t.lastUpdatedVia??null,f=u!==null&&u!==i,h=f&&a&&r?`created ${a} · updated ${r}`:a??r??"",m=[t.createdBy?`createdBy: ${t.createdBy}`:null,t.createdVia?`createdVia: ${t.createdVia}`:null,t.lastUpdatedBy?`lastUpdatedBy: ${t.lastUpdatedBy}`:null,t.lastUpdatedVia?`lastUpdatedVia: ${t.lastUpdatedVia}`:null].filter(p=>!!p).join(" · ");return{compact:h,created:a,updated:r,differs:f,raw:m}}function bM({note:t,variant:a="compact",className:r}){const i=vM(t);return i?a==="detail"?c.jsxs("div",{className:`space-y-0.5 text-xs text-fg-dim${r?` ${r}`:""}`,title:i.raw,children:[i.created?c.jsxs("p",{children:["created ",i.created]}):null,i.updated&&i.differs?c.jsxs("p",{children:["updated ",i.updated]}):null]}):c.jsx("span",{className:`shrink-0 text-xs text-fg-dim${r?` ${r}`:""}`,title:i.raw,children:i.compact}):null}function xS({note:t,pinnedTag:a,archivedTag:r,trailing:i,footer:u}){const f=dh(t),h=!!t.path&&t.path.replace(/\.md$/i,"")!==f.text,m=t.updatedAt??t.createdAt,p=(t.tags??[]).includes(a),y=(t.tags??[]).includes(r);return c.jsxs("li",{className:y?"opacity-60 italic":void 0,children:[c.jsxs("div",{className:"note-row items-stretch","data-note-id":t.id,children:[c.jsx("span",{"aria-hidden":"true",className:"note-dot"}),c.jsxs(_e,{to:`/n/${encodeURIComponent(t.id)}`,className:"focus-ring block min-h-11 min-w-0 flex-1 md:min-h-0",children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[c.jsxs("span",{className:"flex min-w-0 items-baseline gap-1.5",children:[p?c.jsx("span",{className:"shrink-0 text-accent","aria-label":"pinned",title:"pinned",children:"★"}):null,c.jsx("span",{className:f.kind==="timestamp"?"min-w-0 truncate text-base title-timestamp":"min-w-0 truncate text-base font-medium text-fg",children:f.text})]}),c.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[c.jsx("span",{className:"text-xs tabular-nums text-fg-dim",children:Tm(m)}),c.jsx(bM,{note:t})]})]}),h?c.jsx("p",{className:"mt-0.5 min-w-0 truncate note-id",children:t.path}):null,t.preview?c.jsx("p",{className:"mt-1 truncate text-sm text-fg-muted",children:t.preview}):null,t.tags&&t.tags.length>0?c.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:t.tags.map(S=>c.jsxs("span",{className:"chip chip-tag max-w-full break-all",children:["#",S]},S))}):null]}),i?c.jsx("div",{className:"shrink-0 self-center",children:i}):null]}),u?c.jsx("div",{className:"pl-4",children:u}):null]})}function SS({children:t,"aria-label":a}){return c.jsx("ol",{"aria-label":a,className:"flex flex-col gap-0.5",children:t})}const xM="lens:path-tree-expanded:";function wS(t){return xM+t}function _b(t){try{const a=localStorage.getItem(wS(t));if(!a)return new Set;const r=JSON.parse(a);return Array.isArray(r)?new Set(r.filter(i=>typeof i=="string")):new Set}catch{return new Set}}function SM(t,a){try{localStorage.setItem(wS(t),JSON.stringify([...a].sort()))}catch{}}function wM(t){const[a,r]=b.useState(()=>t?_b(t):new Set);b.useEffect(()=>{r(t?_b(t):new Set)},[t]);const i=b.useCallback(u=>{t&&r(f=>{const h=new Set(f);return h.has(u)?h.delete(u):h.add(u),SM(t,h),h})},[t]);return{expanded:a,toggle:i}}function EM(t,a){return{name:t,fullPath:a,count:0,children:[],childMap:new Map}}function ES(t){const a=t.split("/").filter(r=>r.length>0);return a.length<=1?[]:a.slice(0,-1)}function TM(t){const a=new Map;for(const i of t){if(!i)continue;const u=ES(i);if(u.length===0)continue;let f=a,h="";for(const m of u){h=h?`${h}/${m}`:m;let p=f.get(m);p||(p=EM(m,h),f.set(m,p)),p.count+=1,f=p.childMap}}const r=i=>i.map(u=>({name:u.name,fullPath:u.fullPath,count:u.count,children:r([...u.childMap.values()])})).sort((u,f)=>u.name.localeCompare(f.name));return r([...a.values()])}const jM=5,NM=20;function AM(t){const a=new Set;let r=0;for(const i of t){if(!i)continue;const u=ES(i);if(u.length!==0&&(r+=1,a.add(u[0]),a.size>=jM||r>=NM))return!0}return!1}function _M({paths:t,vaultId:a,currentPrefix:r,onSelect:i}){const u=b.useMemo(()=>TM(t),[t]),{expanded:f,toggle:h}=wM(a),m=b.useMemo(()=>RM(r),[r]);return u.length===0?c.jsxs("aside",{"aria-label":"Path tree",children:[c.jsx("h2",{className:"mb-2 text-xs uppercase tracking-wider text-fg-dim",children:"Folders"}),c.jsx("p",{className:"text-xs text-fg-dim",children:"No folders yet."})]}):c.jsxs("aside",{"aria-label":"Path tree",className:"md:sticky md:top-6 md:self-start",children:[c.jsxs("div",{className:"mb-2 flex items-baseline justify-between",children:[c.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"Folders"}),r?c.jsx("button",{type:"button",onClick:()=>i(""),className:"text-xs text-fg-dim hover:text-accent",children:"Clear"}):null]}),c.jsx("ul",{className:"space-y-0.5",children:u.map(p=>c.jsx(TS,{node:p,depth:0,expanded:f,forcedOpen:m,currentPrefix:r,onToggle:h,onSelect:i},p.fullPath))})]})}function TS({node:t,depth:a,expanded:r,forcedOpen:i,currentPrefix:u,onToggle:f,onSelect:h}){const m=t.children.length>0,p=r.has(t.fullPath)||i.has(t.fullPath),y=u===t.fullPath;return c.jsxs("li",{children:[c.jsxs("div",{className:`flex items-center gap-1 rounded-lg px-1 py-0.5 text-sm ${y?"bg-accent/10 text-accent":"text-fg-muted hover:text-accent"}`,style:{paddingLeft:`${a*.75+.25}rem`},children:[m?c.jsx("button",{type:"button",onClick:()=>f(t.fullPath),"aria-label":`${p?"Collapse":"Expand"} ${t.fullPath}`,"aria-expanded":p,className:"flex h-4 w-4 items-center justify-center text-fg-dim hover:text-accent",children:c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:p?"▾":"▸"})}):c.jsx("span",{"aria-hidden":"true",className:"inline-block h-4 w-4"}),c.jsxs("button",{type:"button",onClick:()=>h(t.fullPath),"aria-current":y?"true":void 0,className:"flex flex-1 items-baseline gap-1.5 truncate text-left",children:[c.jsx("span",{className:"truncate",children:t.name}),c.jsx("span",{className:"text-xs text-fg-dim",children:t.count})]})]}),m&&p?c.jsx("ul",{className:"space-y-0.5",children:t.children.map(S=>c.jsx(TS,{node:S,depth:a+1,expanded:r,forcedOpen:i,currentPrefix:u,onToggle:f,onSelect:h},S.fullPath))}):null]})}function RM(t){const a=new Set;if(!t)return a;const r=t.split("/").filter(u=>u.length>0);let i="";for(const u of r)i=i?`${i}/${u}`:u,a.add(i);return a}function ul(t){return t<10?`0${t}`:String(t)}function qo(t=new Date){return`${t.getFullYear()}-${ul(t.getMonth()+1)}-${ul(t.getDate())}`}function jS(t){if(!t)return null;const a=new Date(t);return Number.isNaN(a.getTime())?null:qo(a)}function wo(t){if(!t||!/^\d{4}-\d{2}-\d{2}$/.test(t))return null;const[a,r,i]=t.split("-").map(Number),u=new Date(a,r-1,i);return Number.isNaN(u.getTime())?null:u}function NS(t,a){const r=wo(t);return r?(r.setDate(r.getDate()+a),`${r.getFullYear()}-${ul(r.getMonth()+1)}-${ul(r.getDate())}`):t}function i5(t=new Date){return`${t.getFullYear()}-${ul(t.getMonth()+1)}`}function l5(t){if(!t||!/^\d{4}-\d{2}$/.test(t))return null;const[a,r]=t.split("-").map(Number);return r<1||r>12?null:{year:a,month:r}}function u5(t,a,r){const i=t*12+(a-1)+r;return{year:Math.floor(i/12),month:i%12+1}}function o5(t,a){const i=new Date(t,a-1,1).getDay(),u=new Date(t,a-1,1-i),f=[];for(let h=0;h<42;h++)f.push(new Date(u.getFullYear(),u.getMonth(),u.getDate()+h));return f}function c5(t,a=new Date){var h;const r=((h=t.match(/^\d{4}-\d{2}-\d{2}/))==null?void 0:h[0])??null,i=wo(r);if(!i)return t;const u=wo(qo(a));if(!u)return t;const f=Math.round((i.getTime()-u.getTime())/864e5);return f===0?"Today":f===-1?"Yesterday":f===1?"Tomorrow":i.toLocaleDateString(void 0,i.getFullYear()===a.getFullYear()?{month:"short",day:"numeric"}:{month:"short",day:"numeric",year:"numeric"})}function CM(t){const a=wo(t);return a?a.toLocaleDateString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"}):t}function f5(t,a){return new Date(t,a-1,1).toLocaleDateString(void 0,{year:"numeric",month:"long"})}function OM(t){const a=new Map;for(const i of t){const u=jS(i.updatedAt??i.createdAt);if(!u)continue;const f=a.get(u);f?f.push(i):a.set(u,[i])}const r=i=>i.updatedAt??i.createdAt;return Array.from(a.entries()).sort(([i],[u])=>i<u?1:i>u?-1:0).map(([i,u])=>({key:i,notes:u.sort((f,h)=>r(f)<r(h)?1:r(f)>r(h)?-1:0)}))}function MM(t){const a=qo();return t===a?"Today":t===NS(a,-1)?"Yesterday":CM(t)}function jm({children:t}){return c.jsxs("h2",{className:"eyebrow mb-2 flex items-center gap-3",children:[c.jsx("span",{className:"shrink-0",children:t}),c.jsx("span",{"aria-hidden":"true",className:"h-px flex-1 bg-border"})]})}function DM({notes:t}){const a=ae(u=>u.getActiveVault()),{roles:r}=wl((a==null?void 0:a.id)??null),i=b.useMemo(()=>OM(t),[t]);return c.jsx("div",{className:"space-y-8",children:i.map(u=>c.jsxs("section",{children:[c.jsx(jm,{children:c.jsx(_e,{to:`/today?date=${u.key}`,className:"hover:text-accent",children:MM(u.key)})}),c.jsx(SS,{children:u.notes.map(f=>c.jsx(xS,{note:f,pinnedTag:r.pinned,archivedTag:r.archived},f.id))})]},u.key))})}const Nm="application/x-parachute-note";function AS(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(pointer: fine)").matches}function kM(t,a){t.setData(Nm,a),t.effectAllowed="move"}function eo(t){return t?Array.from(t.types??[]).includes(Nm):!1}function LM(t){if(!t)return null;const a=t.getData(Nm);return a===""?null:a}function d5(t){const[a]=b.useState(AS),r=b.useRef(!1),i=b.useCallback(h=>{h.dataTransfer&&(kM(h.dataTransfer,t),r.current=!0)},[t]),u=b.useCallback(()=>{window.setTimeout(()=>{r.current=!1},0)},[]),f=b.useCallback(h=>{r.current&&(h.preventDefault(),h.stopPropagation(),r.current=!1)},[]);return a?{canDrag:!0,sourceProps:{draggable:!0,onDragStart:i,onDragEnd:u,onClickCapture:f}}:{canDrag:!1,sourceProps:{}}}function h5(t){const[a,r]=b.useState(!1),i=b.useRef(0),u=b.useCallback(p=>{eo(p.dataTransfer)&&(p.preventDefault(),i.current+=1,r(!0))},[]),f=b.useCallback(p=>{eo(p.dataTransfer)&&(p.preventDefault(),p.dataTransfer&&(p.dataTransfer.dropEffect="move"))},[]),h=b.useCallback(p=>{eo(p.dataTransfer)&&(i.current=Math.max(0,i.current-1),i.current===0&&r(!1))},[]),m=b.useCallback(p=>{if(!eo(p.dataTransfer))return;p.preventDefault(),i.current=0,r(!1);const y=LM(p.dataTransfer);y&&t(y)},[t]);return{isOver:a,targetProps:{onDragEnter:u,onDragOver:f,onDragLeave:h,onDrop:m}}}function m5(){const t=b.useRef(new Map),a=b.useCallback((i,u)=>(t.current.set(i,u),()=>{t.current.get(i)===u&&t.current.delete(i)}),[]),r=b.useCallback((i,u)=>{var f;(f=t.current.get(i))==null||f(u)},[]);return{register:a,dispatch:r}}const UM=10;function Eo(t){return Object.keys(t.fields??{}).length}function zM(t,a){const r=new Map;for(const p of t){const y=p.name.indexOf("/");if(y>0){const S=p.name.slice(0,y),v=r.get(S)??[];v.push(p),r.set(S,v)}}const i=new Set;for(const[p,y]of r)y.length>=2&&i.add(p);const u=new Map,f=[];for(const p of t){const y=p.name.indexOf("/"),S=y>0?p.name.slice(0,y):p.name;if(y>0&&i.has(S)){let x=u.get(S);x||(x={kind:"group",prefix:S,totalCount:0,children:[]},u.set(S,x)),x.children.push({...p,pinned:a.has(p.name)}),x.totalCount+=p.count??0}else if(i.has(p.name)){let x=u.get(p.name);x||(x={kind:"group",prefix:p.name,totalCount:0,children:[]},u.set(p.name,x)),x.selfTag={...p,pinned:a.has(p.name)},x.totalCount+=p.count??0}else f.push({kind:"leaf",name:p.name,label:p.name,count:p.count??0,pinned:a.has(p.name),fields:p.fields})}for(const p of u.values())p.children.sort((y,S)=>y.pinned!==S.pinned?y.pinned?-1:1:(S.count??0)-(y.count??0)||y.name.localeCompare(S.name));const h=[...f,...Array.from(u.values())],m=p=>{var v,x;if(p.kind==="leaf")return{pinned:p.pinned,count:p.count,label:p.label};const y=(((v=p.selfTag)==null?void 0:v.pinned)??!1)||p.children.some(T=>T.pinned),S=Math.max(((x=p.selfTag)==null?void 0:x.count)??0,...p.children.map(T=>T.count??0))||0;return{pinned:y,count:S,label:p.prefix}};return h.sort((p,y)=>{const S=m(p),v=m(y);return S.pinned!==v.pinned?S.pinned?-1:1:v.count-S.count||S.label.localeCompare(v.label)}),h}function Rb(t){var a;return t.kind==="leaf"?t.pinned:(((a=t.selfTag)==null?void 0:a.pinned)??!1)||t.children.some(r=>r.pinned)}function Cb(t,a){return t.kind==="leaf"?a.has(t.name.toLowerCase()):(t.selfTag?a.has(t.selfTag.name.toLowerCase()):!1)||t.children.some(i=>a.has(i.name.toLowerCase()))}function VM(t,a,r){const i=t.filter(p=>Cb(p,a)),u=t.filter(p=>!Cb(p,a)),f=u.filter(Rb),h=u.filter(p=>!Rb(p)),m=Math.max(0,r-i.length);return[...i,...[...f,...h].slice(0,m)]}function BM({tags:t,pinnedTags:a,selected:r,onToggle:i,onClear:u,isLoading:f}){const[h,m]=b.useState(""),[p,y]=b.useState(!1),S=b.useRef(null);b.useEffect(()=>{var Q;AS()&&((Q=S.current)==null||Q.focus())},[]);const v=b.useMemo(()=>new Set(a.map(Q=>Q.toLowerCase())),[a]),x=b.useMemo(()=>new Set(r.map(Q=>Q.toLowerCase())),[r]),T=b.useMemo(()=>zM(t,v),[t,v]),j=b.useMemo(()=>VM(T,x,UM),[T,x]),[_,C]=b.useState(new Set),O=Q=>{C(G=>{const F=new Set(G);return F.has(Q)?F.delete(Q):F.add(Q),F})},B=h.trim().toLowerCase(),H=b.useMemo(()=>B?t.filter(Q=>Q.name.toLowerCase().includes(B)).sort((Q,G)=>(G.count??0)-(Q.count??0)||Q.name.localeCompare(G.name)):[],[t,B]),k=Q=>{if(Q.key!=="Enter")return;const G=H[0];G&&(Q.preventDefault(),i(G.name))},Y=Q=>Q.kind==="leaf"?c.jsx("li",{children:c.jsx(To,{name:Q.name,label:Q.label,count:Q.count,pinned:Q.pinned,active:x.has(Q.name.toLowerCase()),fieldCount:Eo(Q),onToggle:()=>i(Q.name)})},Q.name):c.jsx("li",{children:c.jsx(HM,{group:Q,isOpen:_.has(Q.prefix),onToggleOpen:()=>O(Q.prefix),selectedSet:x,onToggleTag:i})},Q.prefix);return c.jsxs("nav",{"aria-label":"Browse by tag",children:[c.jsxs("div",{className:"mb-2 flex items-baseline justify-between",children:[c.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"Tags"}),r.length>0?c.jsx("button",{type:"button",onClick:u,className:"text-xs text-fg-dim hover:text-accent",children:"Clear"}):null]}),c.jsx("input",{ref:S,type:"search",value:h,onChange:Q=>m(Q.target.value),onKeyDown:k,placeholder:"Filter tags…","aria-label":"Filter tags",className:"input mb-2 w-full text-sm"}),f?c.jsx("p",{className:"text-xs text-fg-dim",children:"Loading…"}):t.length===0?c.jsx("p",{className:"text-xs text-fg-dim",children:"No tags in this vault."}):B?H.length===0?c.jsxs("p",{className:"text-xs text-fg-dim",children:['No tags match "',h,'".']}):c.jsx("ul",{className:"max-h-[60vh] space-y-0.5 overflow-y-auto pr-1","aria-label":"Matching tags",children:H.map(Q=>c.jsx("li",{children:c.jsx(To,{name:Q.name,label:Q.name,count:Q.count??0,pinned:v.has(Q.name.toLowerCase()),active:x.has(Q.name.toLowerCase()),fieldCount:Eo(Q),onToggle:()=>i(Q.name)})},Q.name))}):c.jsxs(c.Fragment,{children:[c.jsx("ul",{className:"space-y-0.5","aria-label":"Shortlist",children:j.map(Y)}),T.length>j.length?c.jsxs("button",{type:"button",onClick:()=>y(Q=>!Q),"aria-expanded":p,className:"mt-1 flex items-center gap-1 rounded-lg px-1 py-1 text-xs text-fg-dim hover:text-accent",children:[c.jsx("span",{"aria-hidden":"true",className:"font-mono",children:p?"▾":"▸"}),"All ",t.length," tags"]}):null,p?c.jsx("ul",{className:"mt-2 max-h-[60vh] space-y-0.5 overflow-y-auto border-t border-border pr-1 pt-2","aria-label":"All tags",children:T.map(Y)}):null]})]})}function To({name:t,label:a,count:r,pinned:i,active:u,fieldCount:f,onToggle:h}){return c.jsxs("button",{type:"button",onClick:h,"aria-pressed":u,title:`#${t}`,className:`flex w-full items-center gap-1.5 rounded-lg px-2 py-1 text-left text-sm ${u?"bg-accent/15 text-accent":"text-fg-muted hover:bg-bg/60 hover:text-accent"}`,children:[i?c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-accent",children:"★"}):null,c.jsxs("span",{className:"flex-1 truncate",children:["#",a]}),f?c.jsxs("span",{className:"shrink-0 text-xs text-fg-dim",title:`${f} schema field${f===1?"":"s"}`,children:["⊞ ",f]}):null,c.jsx("span",{className:"shrink-0 text-xs text-fg-dim",children:r})]})}function HM({group:t,isOpen:a,onToggleOpen:r,selectedSet:i,onToggleTag:u}){var y;const f=t.children.some(S=>i.has(S.name.toLowerCase())),h=t.selfTag?i.has(t.selfTag.name.toLowerCase()):!1,m=a||f||h,p=(((y=t.selfTag)==null?void 0:y.pinned)??!1)||t.children.some(S=>S.pinned);return c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center gap-1 rounded-lg px-1 py-0.5",children:[c.jsx("button",{type:"button",onClick:r,"aria-expanded":m,"aria-label":`${m?"Collapse":"Expand"} ${t.prefix}`,className:"flex h-5 w-5 shrink-0 items-center justify-center text-fg-dim hover:text-accent",children:c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:m?"▾":"▸"})}),t.selfTag?c.jsx(To,{name:t.selfTag.name,label:t.prefix,count:t.totalCount,pinned:t.selfTag.pinned,active:h,fieldCount:Eo(t.selfTag),onToggle:()=>u(t.selfTag.name)}):c.jsxs("button",{type:"button",onClick:r,className:"flex flex-1 items-center gap-1.5 truncate rounded-lg px-2 py-1 text-left text-sm text-fg-muted hover:bg-bg/60 hover:text-accent",children:[p?c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-accent",children:"★"}):null,c.jsxs("span",{className:"flex-1 truncate",children:["#",t.prefix,"/"]}),c.jsx("span",{className:"shrink-0 text-xs text-fg-dim",children:t.totalCount})]})]}),m?c.jsx("ul",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:t.children.map(S=>{const v=S.name.slice(t.prefix.length+1)||S.name;return c.jsx("li",{children:c.jsx(To,{name:S.name,label:v,count:S.count??0,pinned:S.pinned,active:i.has(S.name.toLowerCase()),fieldCount:Eo(S),onToggle:()=>u(S.name)})},S.name)})}):null]})}function _S({className:t=""}){return c.jsx("output",{className:`mb-4 block rounded-md border border-border bg-card px-3 py-1.5 text-xs text-fg-muted ${t}`.trim(),children:"Offline — showing what's saved."})}function to({label:t,onRemove:a}){return c.jsxs("span",{className:"chip chip-tag-active",children:[t,c.jsx("button",{type:"button",onClick:a,"aria-label":`Remove refinement ${t}`,className:"focus-ring ml-1 rounded-full",children:"×"})]})}function jh({className:t="",width:a,height:r}){const i={};return a!==void 0&&(i.width=a),r!==void 0&&(i.height=r),c.jsx("div",{className:`skeleton ${t}`.trim(),style:Object.keys(i).length?i:void 0,"aria-hidden":"true"})}function Ob(t,a){const[r,i]=b.useState(t);return b.useEffect(()=>{const u=setTimeout(()=>i(t),a);return()=>clearTimeout(u)},[t,a]),r}function qM(t){const[a,r]=b.useState(!1),[i,u]=b.useState(t);t!==i&&(u(t),r(!1));const f=b.useCallback(()=>r(!0),[]);return{dismissed:a,dismiss:f}}const $M=["auto","always","never"],ol="auto",QM="lens:path-tree:";function RS(t){return QM+t}function IM(t){return typeof t=="string"&&$M.includes(t)?t:ol}function Mb(t){try{const a=localStorage.getItem(RS(t));if(!a)return ol;const r=JSON.parse(a);return IM(r.mode)}catch{return ol}}function KM(t,a){try{localStorage.setItem(RS(t),JSON.stringify({mode:a}))}catch{}}function GM(t){const[a,r]=b.useState(()=>t?Mb(t):ol);b.useEffect(()=>{r(t?Mb(t):ol)},[t]);const i=b.useCallback(u=>{t&&(KM(t,u),r(u))},[t]);return{mode:a,setMode:i}}const jo="UI/Views/",CS="saved-view";function YM(t){var r,i;const a={};return(r=t.search)!=null&&r.trim()&&(a.search=t.search.trim()),t.tags&&t.tags.length>0&&(a.tags=[...t.tags]),t.tags&&t.tags.length>1&&t.tagMatch&&(a.tagMatch=t.tagMatch),(i=t.pathPrefix)!=null&&i.trim()&&(a.pathPrefix=t.pathPrefix.trim()),t.sort&&(a.sort=t.sort),t.showArchived&&(a.showArchived=!0),{kind:CS,filters:a}}function PM(t){const a=t.metadata;if(!a||a.kind!==CS)return null;const r=a.filters??{},i=FM(t.path)??t.id;return{id:t.id,name:i,filters:{search:typeof r.search=="string"?r.search:void 0,tags:Array.isArray(r.tags)?r.tags.filter(u=>typeof u=="string"):void 0,tagMatch:r.tagMatch==="all"?"all":r.tagMatch==="any"?"any":void 0,pathPrefix:typeof r.pathPrefix=="string"?r.pathPrefix:void 0,sort:r.sort==="asc"?"asc":r.sort==="desc"?"desc":void 0,showArchived:r.showArchived===!0},updatedAt:t.updatedAt}}function FM(t){return!t||!t.startsWith(jo)?null:t.slice(jo.length).replace(/\.md$/i,"")||null}function XM(t){const a=t.trim().replace(/[/\\]/g,"-");return`${jo}${a}`}function Nh(t){var r,i;const a=new URLSearchParams;(r=t.search)!=null&&r.trim()&&a.set("search",t.search.trim());for(const u of t.tags??[])a.append("tag",u);return t.tagMatch&&a.set("tag_match",t.tagMatch),(i=t.pathPrefix)!=null&&i.trim()&&a.set("path_prefix",t.pathPrefix.trim()),t.sort&&a.set("sort",t.sort),t.showArchived&&a.set("show_archived","1"),a}function Db(t){const a=t.getAll("tag"),r=t.get("tag_match"),i=t.get("sort");return{search:t.get("search")??void 0,tags:a.length>0?a:void 0,tagMatch:r==="all"?"all":r==="any"?"any":void 0,pathPrefix:t.get("path_prefix")??void 0,sort:i==="asc"?"asc":i==="desc"?"desc":void 0,showArchived:t.get("show_archived")==="1"}}function ZM(t){var a,r;return!!((a=t.search)!=null&&a.trim()||t.tags&&t.tags.length>0||(r=t.pathPrefix)!=null&&r.trim())}function JM(t,a){t.invalidateQueries({queryKey:["savedViews",a]}),t.invalidateQueries({queryKey:["notes",a]}),t.invalidateQueries({queryKey:["tags",a]}),t.invalidateQueries({queryKey:["vaultInfo",a]})}function WM(t){const a=ke(),r=ae(i=>i.activeVaultId);return lt({queryKey:["savedViews",r,t],enabled:!!a&&!!t,queryFn:async()=>{const i=new URLSearchParams;return i.set("tag",t),i.set("path_prefix",jo),i.set("sort","asc"),(await a.queryNotes(i)).map(f=>PM(f)).filter(f=>f!==null).sort((f,h)=>f.name.localeCompare(h.name))},staleTime:3e4})}function e3(t){const a=ke(),r=ae(u=>u.activeVaultId),i=pt();return xn({mutationFn:async u=>{if(!a)throw new Error("No active vault");return a.createNote({path:XM(u.name),content:u.description??"",tags:[t],metadata:YM(u.filters)})},onSuccess:()=>JM(i,r)})}const t3=["pinned","archived","untagged","orphaned"],OS={recent:{label:"Recent",hint:"what you've touched lately"},all:{label:"All notes",hint:"everything, searchable"},pinned:{label:"Pinned",hint:"starred"},archived:{label:"Archive",hint:"set aside, never deleted"},untagged:{label:"Untagged",hint:"notes without any tags"},orphaned:{label:"Orphaned",hint:"notes with no links"}};function n3(t){return t3.find(a=>a===t)}function Ah({preset:t,lens:a}={}){return a==="recent"?c.jsx(s3,{}):c.jsx(a3,{preset:t})}function MS({name:t}){return c.jsxs("header",{className:"mb-6",children:[c.jsx("h1",{className:"page-title",style:{fontSize:"clamp(2rem, 4vw, 2.6rem)"},children:t}),c.jsx("p",{className:"mt-1.5 text-fg-muted",children:"Everything here is yours. Open format. Export anytime."})]})}function a3({preset:t}){var ei,Ya;const a=ae(se=>se.getActiveVault()),{roles:r}=wl((a==null?void 0:a.id)??null),{pinnedTags:i}=F_((a==null?void 0:a.id)??null),[u,f]=Qh(),h=t??n3(u.get("view")),m=b.useMemo(()=>Db(u),[u]),[p,y]=b.useState(m.search??""),[S,v]=b.useState(m.pathPrefix??""),[x,T]=b.useState(m.tags??[]),[j,_]=b.useState(m.tagMatch??"any"),[C,O]=b.useState(m.sort??"desc"),[B,H]=b.useState(m.showArchived??!1),[k,Y]=b.useState(0),Q=b.useMemo(()=>u.toString(),[u]);b.useEffect(()=>{const se=Db(new URLSearchParams(Q));y(se.search??""),v(se.pathPrefix??""),T(se.tags??[]),_(se.tagMatch??"any"),O(se.sort??"desc"),H(se.showArchived??!1)},[Q]);const G=Ob(p,300),F=Ob(S,300);b.useEffect(()=>{if(h)return;const se={search:G,tags:x,tagMatch:j,pathPrefix:F,sort:C,showArchived:B};Nh(se).toString()!==Q&&f(Nh(se),{replace:!0})},[h,G,F,x,j,C,B]);const Z=h==="pinned"||h==="archived"?h:null,{def:le}=ER(Z,r),de=b.useMemo(()=>{if(!Z)return x;const se=le?P0(le.query):[];return Array.from(new Set([...se,...x]))},[Z,le,x]),ye=Z?"all":j;b.useEffect(()=>{Y(0)},[G,F,de,ye,C,B]);const we=b.useMemo(()=>({...n_,search:G,pathPrefix:F,tags:de,tagMatch:ye,sort:C,offset:k,limit:gr+1,...h==="untagged"?{hasTags:!1}:{},...h==="orphaned"?{hasLinks:!1}:{}}),[G,F,de,ye,C,k,h]),re=T_(we,{live:!1}),ee=R_(),M=WM(r.view),P=e3(r.view),ne=aa(se=>se.push),[oe,me]=b.useState(!1),[E,q]=b.useState(!1);b.useEffect(()=>{if(!E)return;const se=ft=>{ft.key==="Escape"&&q(!1)};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[E]);const{mode:X}=GM((a==null?void 0:a.id)??null),[W,pe]=b.useState(!1),Se=!h&&X!=="never",Oe=Se&&W,ut=A_(Oe),Ye=b.useMemo(()=>(ut.data??[]).map(se=>se.path),[ut.data]),Ka=Oe&&(X==="always"||X==="auto"&&AM(Ye)),ia=b.useMemo(()=>({search:G,tags:x,tagMatch:j,pathPrefix:F,sort:C,showArchived:B}),[G,F,x,j,C,B]),Fs=b.useCallback(async se=>{try{await P.mutateAsync({name:se,filters:ia}),ne(`Saved view "${se}".`,"success"),me(!1)}catch(ft){ne(`Could not save view: ${ft.message}`,"error")}},[P,ia,ne]),Jt=b.useMemo(()=>{if(!re.data)return re.data;let se=re.data.slice(0,gr);if(!h&&!B&&(se=se.filter(ft=>!(ft.tags??[]).includes(r.archived))),!h){const ft=r.pinned;se=[...se].sort((Pa,Io)=>{const Fa=(Pa.tags??[]).includes(ft)?0:1,Tt=(Io.tags??[]).includes(ft)?0:1;return Fa-Tt})}return se},[re.data,h,B,r.archived,r.pinned]);if(!a)return c.jsx(fn,{to:"/",replace:!0});const Sn=OS[h??"all"],Xs=k+1,Zs=k+((Jt==null?void 0:Jt.length)??0),jl=k>0,Js=((ei=re.data)==null?void 0:ei.length)??0,Ga=Js>gr,kr=Ga?null:k+Js,Ws=kr!==null?` of ${kr}`:` of ${k+gr}+`,Nl=ZM(ia),$o=(x.length>0?1:0)+(S.trim()?1:0)+(B?1:0)+(C!=="desc"?1:0),St=!h&&!Nl&&$o===0&&!re.isPending&&(((Ya=re.data)==null?void 0:Ya.length)??0)===0&&k===0,Qo=!St,Al=jl||Ga||((Jt==null?void 0:Jt.length)??0)>0;return c.jsxs("div",{className:"page-surface",children:[c.jsx(MS,{name:a.name}),c.jsx(bS,{}),h?null:c.jsx(vS,{vault:a,focused:!1},a.id),c.jsxs("div",{className:"mb-6",children:[c.jsxs("div",{"data-notes-chrome":!0,className:"flex items-center gap-3",children:[c.jsx("input",{type:"search",placeholder:"Search…",value:p,onChange:se=>y(se.target.value),className:"input min-w-0 flex-1","aria-label":"Search notes"}),Qo?c.jsxs("div",{className:"relative",children:[c.jsxs("button",{type:"button",onClick:()=>q(se=>!se),"aria-expanded":E,"aria-controls":"notes-filters",className:"btn btn-secondary btn-touch shrink-0",children:["Filters",c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:E?"▴":"▾"})]}),E?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button","aria-hidden":"true",tabIndex:-1,onClick:()=>q(!1),className:"enter-fade fixed inset-0 z-30 cursor-default bg-black/40 sm:bg-transparent"}),c.jsx("section",{id:"notes-filters","aria-label":"Filters",className:"card enter-rise fixed inset-x-0 bottom-0 z-40 max-h-[70dvh] overflow-y-auto rounded-b-none p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] shadow-lift sm:absolute sm:top-full sm:right-0 sm:left-auto sm:bottom-auto sm:mt-1 sm:max-h-[30rem] sm:w-[26rem] sm:rounded-b-[var(--radius-2xl)] sm:pb-4",children:c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{children:[c.jsx("h2",{className:"eyebrow mb-3",children:"Refine"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("button",{type:"button",onClick:()=>O(se=>se==="desc"?"asc":"desc"),className:"focus-ring block text-fg-muted text-sm hover:text-accent","aria-label":"Toggle sort direction",children:["Sort: ",C==="desc"?"newest":"oldest"," first"]}),h?null:c.jsxs("label",{className:"flex items-center gap-1.5 text-fg-muted text-sm hover:text-accent",children:[c.jsx("input",{type:"checkbox",checked:B,onChange:se=>H(se.target.checked)}),"Show archived"]}),c.jsx("input",{type:"text",placeholder:"Title starts with…",value:S,onChange:se=>v(se.target.value),className:"input w-full font-mono","aria-label":"Filter by path prefix"}),c.jsx(p3,{active:h})]})]}),h!=="untagged"?c.jsxs("div",{children:[c.jsx(BM,{tags:ee.data??[],pinnedTags:i,selected:x,onToggle:se=>T(ft=>ft.includes(se)?ft.filter(Pa=>Pa!==se):[...ft,se]),onClear:()=>T([]),isLoading:ee.isPending}),x.length>1?c.jsxs("fieldset",{className:"mt-3 flex items-center gap-3 text-xs",children:[c.jsx("legend",{className:"sr-only",children:"Match mode"}),c.jsx("span",{className:"text-fg-dim",children:"Match"}),c.jsxs("label",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"radio",name:"tag-match",value:"any",checked:j==="any",onChange:()=>_("any")}),"Any"]}),c.jsxs("label",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"radio",name:"tag-match",value:"all",checked:j==="all",onChange:()=>_("all")}),"All"]})]}):null]}):null,Se?c.jsxs("details",{className:"group",open:W,onToggle:se=>pe(se.currentTarget.open),children:[c.jsxs("summary",{className:"eyebrow flex cursor-pointer list-none items-center justify-between rounded-lg px-1 py-1 hover:text-accent",children:[c.jsx("span",{children:"Folders"}),c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs transition-transform group-open:rotate-90",children:"▸"})]}),c.jsx("div",{className:"mt-2",children:Ka?c.jsx(_M,{paths:Ye,vaultId:a.id,currentPrefix:S,onSelect:se=>v(se)}):ut.isLoading?c.jsx("p",{className:"px-1 text-xs text-fg-dim",children:"Loading…"}):c.jsx("p",{className:"px-1 text-xs text-fg-dim",children:"Not enough folder variety to show a tree yet."})})]}):null,h?null:c.jsx(d3,{views:M.data})]})})]}):null]}):null]}),c.jsx(f3,{selectedTags:x,onRemoveTag:se=>T(ft=>ft.filter(Pa=>Pa!==se)),tagMatch:j,onToggleTagMatch:()=>_(se=>se==="all"?"any":"all"),pathPrefix:S,onClearPathPrefix:()=>v(""),showArchived:B,onClearArchived:()=>H(!1),sort:C,onResetSort:()=>O("desc"),showSave:Nl,onSaveView:()=>me(!0)})]}),St?null:c.jsxs(jm,{children:[Sn.label,c.jsxs("span",{className:"font-sans normal-case tracking-normal text-fg-muted",children:[" ","· ",Sn.hint]})]}),re.isPending?c.jsx(g3,{}):re.isError&&!re.data?c.jsx(y3,{error:re.error,retry:()=>re.refetch()}):Jt&&Jt.length>0?c.jsxs(c.Fragment,{children:[re.isError?c.jsx(_S,{}):null,c.jsx(SS,{"aria-label":"Notes",children:Jt.map(se=>c.jsx(xS,{note:se,pinnedTag:r.pinned,archivedTag:r.archived,trailing:h==="untagged"?c.jsx(m3,{noteId:se.id,existing:se.tags??[],suggestions:ee.data??[]}):void 0},se.id))})]}):c.jsx(v3,{filtering:r_(we)||!!h}),Al?c.jsxs("div",{className:"mt-6 flex items-center justify-between text-fg-dim text-sm",children:[c.jsx("span",{children:re.data&&re.data.length>0?`Showing ${Xs}–${Zs}${Ws}`:re.isFetching?"Loading…":""}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",disabled:!jl,onClick:()=>Y(se=>Math.max(0,se-gr)),className:"btn btn-secondary btn-touch",children:"Previous"}),c.jsx("button",{type:"button",disabled:!Ga,onClick:()=>Y(se=>se+gr),className:"btn btn-secondary btn-touch",children:"Next"})]})]}):null,oe?c.jsx(h3,{existing:M.data??[],isSaving:P.isPending,onCancel:()=>me(!1),onSave:Fs}):null]})}const r3=100;function s3(){var k,Y,Q;const t=ae(G=>G.getActiveVault()),a=N_(),{dismissed:r,dismiss:i}=qM((t==null?void 0:t.id)??null),{roles:u}=wl((t==null?void 0:t.id)??null),f=t!==null&&Qs(t.clientId),h=am({enabled:f}),m=((k=f?nm(h.data):null)==null?void 0:k.plan)??null,p=typeof(m==null?void 0:m.trial_days_left)=="number"?m.trial_days_left:null,y=b.useMemo(()=>{if(!a.data)return;const G=NS(qo(),-13),F=Z=>Z.updatedAt??Z.createdAt;return a.data.filter(Z=>!(Z.tags??[]).includes(u.archived)).filter(Z=>(jS(F(Z))??"")>=G).sort((Z,le)=>F(Z)<F(le)?1:F(Z)>F(le)?-1:0).slice(0,r3)},[a.data,u.archived]);if(!t)return c.jsx(fn,{to:"/",replace:!0});const S=a.data!==void 0,v=h0(a.data),x=m0({hasUserNote:v}),T=sA(x),j=!r&&!T,_=x.filter(G=>!G.done),C=x.length-_.length,O=S&&!v&&j?"fresh":"returning",B=!a.isPending&&(((Y=a.data)==null?void 0:Y.length)??0)===0,H=OS.recent;return c.jsxs("div",{className:"page-surface",children:[c.jsx(MS,{name:t.name}),c.jsx(bS,{}),c.jsx(vS,{vault:t,focused:O==="fresh"},t.id),c.jsx(i3,{daysLeft:p}),O==="fresh"?c.jsx(l3,{}):null,j&&_.length>0?c.jsx(u3,{to:Ub[_[0].id].to,label:Ub[_[0].id].label,done:C,total:x.length,onDismiss:i}):null,c.jsxs("section",{"aria-label":"Recent notes",children:[B?null:c.jsxs(jm,{children:[H.label,c.jsxs("span",{className:"font-sans normal-case tracking-normal text-fg-muted",children:[" ","· ",H.hint]})]}),a.isPending?c.jsx(o3,{}):a.isError&&!a.data?c.jsx("p",{className:"rounded-xl border border-border bg-card px-4 py-3 text-sm text-fg-muted",children:"Couldn't load recent notes. They'll appear once you're back online."}):(((Q=a.data)==null?void 0:Q.length)??0)===0?c.jsxs("div",{className:"rounded-xl border border-border bg-card p-8 text-center shadow-soft",children:[c.jsx("p",{className:"mb-1 font-serif text-fg text-lg",children:"A quiet, empty page."}),c.jsx("p",{className:"mb-5 text-fg-muted text-sm",children:"Anything at all can land here — a thought, a list, a memory."}),c.jsx("button",{type:"button",onClick:()=>{var G;return(G=document.getElementById(yS))==null?void 0:G.focus()},className:"inline-flex rounded-full bg-accent px-5 py-2.5 font-round font-semibold text-on-accent text-sm shadow-soft hover:bg-accent-hover",children:"Write the first one"})]}):((y==null?void 0:y.length)??0)===0?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"rounded-xl border border-border bg-card px-4 py-3 text-sm text-fg-muted",children:"Nothing touched in the last two weeks."}),c.jsx(kb,{})]}):c.jsxs(c.Fragment,{children:[a.isError?c.jsx(_S,{}):null,c.jsx(DM,{notes:y??[]}),c.jsx(kb,{})]})]}),c.jsx(c3,{clientId:t.clientId,trialDaysLeft:p})]})}function kb(){return c.jsxs("p",{className:"mt-6 text-fg-dim text-sm",children:["Looking for older notes?"," ",c.jsx(_e,{to:"/notes",className:"text-accent hover:underline",children:"All notes →"})]})}function i3({daysLeft:t}){return t===null||t>7?null:c.jsxs("div",{className:"nudge-sun mb-6",children:[c.jsx("span",{"aria-hidden":"true",children:"✦"}),c.jsx(_e,{to:"/account",className:"min-w-0 flex-1 truncate hover:underline",children:t===0?"Your trial ends today — see plans →":`Your trial ends in ${t} day${t===1?"":"s"} — see plans →`})]})}function l3(){return c.jsxs("nav",{"aria-label":"Quick actions",className:"mb-6 grid gap-3 sm:grid-cols-2",children:[c.jsx(Lb,{to:"/connect",emoji:"⚡",title:"Connect your AI",description:"Let Claude or ChatGPT read and write your vault."}),c.jsx(Lb,{to:"/import",emoji:"↯",title:"Bring your notes over",description:"Import from Obsidian or plain markdown."})]})}function Lb({to:t,emoji:a,title:r,description:i}){return c.jsxs(_e,{to:t,className:"focus-ring tile flex items-start gap-3 p-4",children:[c.jsx("span",{"aria-hidden":"true",className:"text-lg leading-none",children:a}),c.jsxs("span",{className:"min-w-0",children:[c.jsx("span",{className:"block font-medium text-fg",children:r}),c.jsx("span",{className:"mt-0.5 block text-fg-muted text-sm",children:i})]})]})}const Ub={write:{label:"Write your first note",to:"/new"}};function u3({to:t,label:a,done:r,total:i,onDismiss:u}){return c.jsxs("div",{className:"nudge-sun mb-8",children:[c.jsx("span",{"aria-hidden":"true",children:"✦"}),c.jsxs(_e,{to:t,className:"min-w-0 flex-1 truncate hover:underline",children:["Finish setting up — ",a]}),c.jsxs("span",{className:"font-round text-sm opacity-80",children:[r," / ",i]}),c.jsx("button",{type:"button",onClick:u,"aria-label":"Dismiss setup",className:"ml-1 text-sun-ink/70 hover:text-sun-ink",children:"✕"})]})}function o3(){return c.jsx("div",{className:"space-y-3","aria-busy":"true",children:[0,1,2].map(t=>c.jsx(jh,{className:"h-14 rounded-xl"},t))})}function c3({clientId:t,trialDaysLeft:a}){return Qs(t)?c.jsx("div",{className:"mt-10 border-t border-border pt-4 text-sm",children:c.jsx(_e,{to:"/account",className:"text-fg-dim hover:text-accent",children:a!==null?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"font-medium text-sun-ink",children:["Free trial ·"," ",a===0?"ends today":`${a} day${a===1?"":"s"} left`]})," ","· Manage your account →"]}):"Manage your account →"})}):null}function f3({selectedTags:t,onRemoveTag:a,tagMatch:r,onToggleTagMatch:i,pathPrefix:u,onClearPathPrefix:f,showArchived:h,onClearArchived:m,sort:p,onResetSort:y,showSave:S,onSaveView:v}){const x=u.trim();return!(t.length>0||x.length>0||h||p==="asc")&&!S?null:c.jsxs("div",{"aria-label":"Active filters",className:"mt-3 flex flex-wrap items-center gap-2",children:[t.map(j=>c.jsx(to,{label:`#${j}`,onRemove:()=>a(j)},`tag-${j}`)),t.length>1?c.jsxs("button",{type:"button",onClick:i,"aria-label":`Tag match is currently "${r}" — click to switch`,className:"chip",children:["match ",r,c.jsx("span",{"aria-hidden":"true",className:"ml-1",children:"▾"})]}):null,x?c.jsx(to,{label:`title: ${x}`,onRemove:f}):null,h?c.jsx(to,{label:"archived shown",onRemove:m}):null,p==="asc"?c.jsx(to,{label:"oldest first",onRemove:y}):null,S?c.jsx("button",{type:"button",onClick:v,className:"btn btn-accent-soft btn-sm ml-auto",children:"Save as view…"}):null]})}function d3({views:t}){return!t||t.length===0?null:c.jsxs("details",{className:"group border-t border-border pt-3",children:[c.jsxs("summary",{className:"eyebrow flex cursor-pointer list-none items-center gap-1.5 text-fg-dim hover:text-accent",children:[c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs transition-transform group-open:rotate-90",children:"▸"}),"Saved filters"]}),c.jsx("ul",{className:"mt-2 space-y-0.5","aria-label":"Saved views",children:t.map(a=>c.jsx("li",{children:c.jsx(_e,{to:`/notes?${Nh(a.filters).toString()}`,className:"block truncate rounded-lg px-2 py-1 text-sm text-fg-muted hover:bg-bg-soft hover:text-accent",children:a.name})},a.id))})]})}function h3({existing:t,isSaving:a,onCancel:r,onSave:i}){const[u,f]=b.useState(""),h=u.trim(),m=t.some(y=>y.name.toLowerCase()===h.toLowerCase()),p=h.length>0&&!m&&!a;return c.jsx("div",{className:"dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Save view",children:c.jsxs("div",{className:"dialog-panel max-w-(--w-narrow)",children:[c.jsx("h3",{className:"mb-3 font-serif text-lg text-fg",children:"Save view"}),c.jsxs("label",{className:"block text-sm",children:[c.jsx("span",{className:"mb-1 block text-fg-muted",children:"Name"}),c.jsx("input",{type:"text",value:u,autoFocus:!0,onChange:y=>f(y.target.value),onKeyDown:y=>{y.key==="Enter"&&p&&i(h),y.key==="Escape"&&r()},placeholder:"e.g. Daily journal","aria-label":"View name",className:"input input-on-bg"})]}),m?c.jsx("p",{className:"mt-2 text-xs text-danger",children:"A view with that name already exists."}):null,c.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[c.jsx("button",{type:"button",onClick:r,className:"btn btn-secondary btn-touch",children:"Cancel"}),c.jsx("button",{type:"button",onClick:()=>p&&i(h),disabled:!p,className:"btn btn-primary btn-touch",children:a?"Saving…":"Save"})]})]})})}function m3({noteId:t,existing:a,suggestions:r}){const[i,u]=b.useState(!1),[f,h]=b.useState(""),m=b.useRef(null),p=b.useRef(null),y=U_(t),S=aa(T=>T.push);b.useEffect(()=>{var _;if(!i)return;(_=p.current)==null||_.focus();const T=C=>{var O;(O=m.current)!=null&&O.contains(C.target)||u(!1)},j=C=>{C.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",T),document.addEventListener("keydown",j),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",j)}},[i]);const v=b.useMemo(()=>{const T=So(f).toLowerCase(),j=new Set(a.map(C=>C.toLowerCase())),_=r.filter(C=>!j.has(C.name.toLowerCase()));return T?_.filter(C=>C.name.toLowerCase().includes(T)).slice(0,8):_.slice(0,8)},[f,r,a]),x=b.useCallback(async T=>{const j=So(T);if(j)try{await y.mutateAsync({tags:{add:[j]}}),S(`Added #${j}`,"success"),h(""),u(!1)}catch(_){S(`Could not add tag: ${_.message}`,"error")}},[y,S]);return i?c.jsxs("div",{ref:m,className:"relative",children:[c.jsx("input",{ref:p,type:"text",value:f,onChange:T=>h(T.target.value),onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),x(f))},placeholder:"tag…","aria-label":"Tag name",disabled:y.isPending,className:"input w-32 px-2 py-1 text-xs"}),v.length>0?c.jsx("ul",{className:"absolute right-0 z-20 mt-1 max-h-48 w-44 overflow-y-auto rounded-xl border border-border bg-card text-xs shadow-lift","aria-label":"Tag suggestions",children:v.map(T=>c.jsx("li",{children:c.jsxs("button",{type:"button",onMouseDown:j=>{j.preventDefault(),x(T.name)},className:"flex w-full items-center justify-between px-2 py-1 text-left text-fg hover:bg-bg/60",children:[c.jsx("span",{className:"truncate",children:T.name}),c.jsx("span",{className:"ml-2 shrink-0 text-fg-dim",children:T.count??0})]})},T.name))}):null]}):c.jsx("button",{type:"button",onClick:()=>u(!0),className:"btn btn-sm border border-border bg-bg/60 text-fg-muted hover:border-accent hover:text-accent","aria-label":"Add tag",children:"+ tag"})}function p3({active:t}){const a=[{view:"untagged",label:"Untagged"},{view:"orphaned",label:"Orphaned"}];return c.jsxs("nav",{"aria-label":"Show only",className:"flex flex-wrap items-center gap-2",children:[c.jsx("span",{className:"text-fg-muted text-sm",children:"Show only:"}),a.map(r=>{const i=r.view===t;return c.jsx(_e,{to:i?"/notes":`/notes?view=${r.view}`,"aria-current":i?"page":void 0,className:`chip focus-ring max-w-full ${i?"chip-tag-active font-medium":"chip-tag"}`,children:r.label},r.view)})]})}function g3(){return c.jsx("ol",{className:"flex flex-col gap-0.5","aria-busy":"true",children:[0,1,2,3,4].map(t=>c.jsxs("li",{className:"rounded-xl px-3 py-3",children:[c.jsx(jh,{className:"h-4 w-1/3"}),c.jsx(jh,{className:"mt-2 h-3 w-2/3"})]},t))})}function y3({error:t,retry:a}){const r=t instanceof Uo;return c.jsx(W0,{title:r?"Session expired":"Could not load notes",message:t.message,retry:r?void 0:a,action:r?c.jsx(_e,{to:"/add",className:"btn btn-primary",children:"Reconnect vault"}):void 0})}function v3({filtering:t}){return t?c.jsx(wh,{title:"No notes match these filters."}):c.jsx(wh,{title:"This vault has no notes yet.",action:c.jsx(_e,{to:"/new",className:"btn btn-primary",children:"Create one"})})}const b3=b.lazy(()=>Qe(()=>import("./Account-BS79MR2p.js"),__vite__mapDeps([0,1])).then(t=>({default:t.Account}))),x3=b.lazy(()=>Qe(()=>import("./Activity-BCI-VU_G.js"),[]).then(t=>({default:t.Activity}))),S3=b.lazy(()=>Qe(()=>import("./AddVault-BGmLnyvr.js"),__vite__mapDeps([2,3,4,5])).then(t=>({default:t.AddVault}))),w3=b.lazy(()=>Qe(()=>import("./AddVaultChooser-BOYsRq-6.js"),__vite__mapDeps([6,3,4])).then(t=>({default:t.AddVaultChooser}))),E3=b.lazy(()=>Qe(()=>import("./AddVaultCreate-VvY9DfX7.js"),__vite__mapDeps([7,3,4])).then(t=>({default:t.AddVaultCreate}))),T3=b.lazy(()=>Qe(()=>import("./AddVaultCreate-VvY9DfX7.js"),__vite__mapDeps([7,3,4])).then(t=>({default:t.AddVaultReady}))),j3=b.lazy(()=>Qe(()=>import("./Calendar-CStTh0s6.js"),[]).then(t=>({default:t.Calendar}))),N3=b.lazy(()=>Qe(()=>import("./ConnectAI-_yRQ6PVE.js"),[]).then(t=>({default:t.ConnectAI}))),A3=b.lazy(()=>Qe(()=>import("./DayView-CP-3vwhX.js"),__vite__mapDeps([8,4])).then(t=>({default:t.DayView}))),_3=b.lazy(()=>Qe(()=>import("./Export-BN79ECKv.js"),[]).then(t=>({default:t.Export}))),R3=b.lazy(()=>Qe(()=>import("./Import-CGC0ejYh.js"),__vite__mapDeps([9,10])).then(t=>({default:t.Import}))),C3=b.lazy(()=>Qe(()=>import("./NoteEditor-7Ul1HK8m.js"),__vite__mapDeps([11,10,12,13,14,15])).then(t=>({default:t.NoteEditor}))),O3=b.lazy(()=>Qe(()=>import("./NoteNew-B-Lomu-W.js"),__vite__mapDeps([16,10,12,13,17,18,15])).then(t=>({default:t.NoteNew}))),M3=b.lazy(()=>Qe(()=>import("./NoteView-CCQoXBAK.js"),__vite__mapDeps([19,14,13])).then(t=>({default:t.NoteView}))),D3=b.lazy(()=>Qe(()=>import("./OAuthCallback-DXQknDTs.js"),__vite__mapDeps([20,3,4,5])).then(t=>({default:t.OAuthCallback}))),k3=b.lazy(()=>Qe(()=>import("./Settings-BvqkQbc1.js"),__vite__mapDeps([21,17,18,15])).then(t=>({default:t.Settings}))),L3=b.lazy(()=>Qe(()=>import("./Tags-BKTmTns9.js"),__vite__mapDeps([22,23])).then(t=>({default:t.Tags}))),U3=b.lazy(()=>Qe(()=>import("./TagPage-CHDSvaJ4.js"),__vite__mapDeps([24,25,23])).then(t=>({default:t.TagPage}))),z3=b.lazy(()=>Qe(()=>import("./VaultGraph-CX2MzD9D.js"),[]).then(t=>({default:t.VaultGraph}))),V3=b.lazy(()=>Qe(()=>import("./Vaults-B9uh43KI.js"),__vite__mapDeps([26,1,18])).then(t=>({default:t.Vaults}))),B3=b.lazy(()=>Qe(()=>import("./Welcome-pHYMoace.js"),__vite__mapDeps([27,3,4,1])).then(t=>({default:t.Welcome}))),H3=b.lazy(()=>Qe(()=>import("./CheckEmail-D1qSfrIa.js"),__vite__mapDeps([28,3,4])).then(t=>({default:t.CheckEmail}))),q3=b.lazy(()=>Qe(()=>import("./ViewNew-C6gk4Ujs.js"),[]).then(t=>({default:t.ViewNew}))),$3=b.lazy(()=>Qe(()=>import("./ViewSurface-B-DhVasF.js"),__vite__mapDeps([25,23])).then(t=>({default:t.ViewSurface})));function Q3(){const t=ae(h=>h.getActiveVault()),[a]=Qh(),[r,i]=b.useState(null),u=b.useRef(!1),f=b.useCallback(()=>{u.current=!0,i(null),mS().catch(()=>{}),VO({hasLocalActiveVault:!1}).then(i).catch(()=>i({kind:"front-door"}))},[]);if(b.useEffect(()=>{t||u.current||f()},[t,f]),a.get("add"))return c.jsx(fn,{to:`/add?${a.toString()}`,replace:!0});if(t)return c.jsx(Ah,{lens:"recent"});if(!r)return c.jsx(I3,{});switch(r.kind){case"home":return c.jsx(Ah,{lens:"recent"});case"signed-in":return c.jsx(Md,{signedIn:{email:r.email,username:r.username,vaults:r.vaults}});case"net-error":return c.jsx(Md,{netError:r.message,onRetry:f});default:return c.jsx(Md,{})}}function I3(){return c.jsx("output",{"aria-live":"polite",className:"mx-auto flex min-h-[50dvh] items-center justify-center text-sm text-fg-dim",children:c.jsx("span",{className:"animate-pulse",children:"Loading…"})})}function K3(){return c.jsx("output",{"aria-live":"polite",className:"mx-auto block max-w-5xl px-6 py-10 text-center text-sm text-fg-dim",children:"Loading…"})}function zb({suffix:t=""}){const{id:a}=NT();return a?$O(window.location.pathname)?c.jsx(fn,{to:"/",replace:!0}):c.jsx(fn,{to:`/n/${encodeURIComponent(a)}${t}`,replace:!0}):c.jsx(fn,{to:"/",replace:!0})}function Vb({to:t}){const a=Ge();return c.jsx(fn,{to:`${t}${a.search}`,replace:!0})}function G3(){return c.jsx("div",{className:"page",children:c.jsx(wh,{title:c.jsx("span",{className:"font-serif text-xl text-fg",children:"Page not found"}),description:"That address doesn't match anything in Parachute. It may be mistyped, or the page may have moved.",action:c.jsx(_e,{to:"/notes",className:"btn btn-primary btn-touch",children:"Back to notes"})})})}function Y3(){const{pathname:t}=Ge();return Z0(t)?null:c.jsx("footer",{className:"mx-auto max-w-5xl px-6 py-10 text-center text-sm text-fg-dim",children:c.jsxs("p",{children:["Part of the"," ",c.jsx("a",{href:"https://parachute.computer",className:"focus-ring text-accent hover:underline",children:"Parachute Computer"})," ","ecosystem. AGPL-3.0."]})})}function P3(){const t=ae(r=>r.activeVaultId),a=ke();return W_(t,a),null}function F3(){const t=Ge(),r=bo(i=>i.on)&&tS(t.pathname);return c.jsxs("div",{className:"app-canvas min-h-dvh overflow-x-hidden text-fg",children:[c.jsx(hO,{}),c.jsx(wO,{}),c.jsx(EO,{}),c.jsx(wj,{}),c.jsx(Ej,{}),c.jsx(PC,{}),c.jsx(iC,{}),c.jsxs("div",{className:"lg:flex",children:[r?null:c.jsx(uO,{}),c.jsxs("div",{className:`flex min-w-0 flex-1 flex-col ${r?"":"pb-16 lg:pb-0"}`,children:[r?null:c.jsx(YC,{}),c.jsx(iO,{}),c.jsx("main",{className:"flex-1","data-focus-safe-area":r?"true":void 0,style:r?{paddingTop:"env(safe-area-inset-top)"}:void 0,children:c.jsx(b.Suspense,{fallback:c.jsx(K3,{}),children:c.jsxs(qT,{children:[c.jsx(je,{path:"/",element:c.jsx(Q3,{})}),c.jsx(je,{path:"/check-email",element:c.jsx(Fe,{children:c.jsx(H3,{})})}),c.jsx(je,{path:"/notes",element:c.jsx(Ah,{})}),c.jsx(je,{path:"/all",element:c.jsx(Vb,{to:"/notes"})}),c.jsx(je,{path:"/pinned",element:c.jsx(fn,{to:"/notes?view=pinned",replace:!0})}),c.jsx(je,{path:"/archived",element:c.jsx(fn,{to:"/notes?view=archived",replace:!0})}),c.jsx(je,{path:"/untagged",element:c.jsx(fn,{to:"/notes?view=untagged",replace:!0})}),c.jsx(je,{path:"/orphaned",element:c.jsx(fn,{to:"/notes?view=orphaned",replace:!0})}),c.jsx(je,{path:"/tags",element:c.jsx(Fe,{children:c.jsx(L3,{})})}),c.jsx(je,{path:"/tags/:name",element:c.jsx(Fe,{children:c.jsx(U3,{})})}),c.jsx(je,{path:"/new",element:c.jsx(Fe,{children:c.jsx(O3,{})})}),c.jsx(je,{path:"/capture",element:c.jsx(fn,{to:"/new",replace:!0})}),c.jsx(je,{path:"/import",element:c.jsx(Fe,{children:c.jsx(R3,{})})}),c.jsx(je,{path:"/export",element:c.jsx(Fe,{children:c.jsx(_3,{})})}),c.jsx(je,{path:"/connect",element:c.jsx(Fe,{children:c.jsx(N3,{})})}),c.jsx(je,{path:"/map",element:c.jsx(Fe,{children:c.jsx(z3,{})})}),c.jsx(je,{path:"/graph",element:c.jsx(Vb,{to:"/map"})}),c.jsx(je,{path:"/today",element:c.jsx(Fe,{children:c.jsx(A3,{})})}),c.jsx(je,{path:"/calendar",element:c.jsx(Fe,{children:c.jsx(j3,{})})}),c.jsx(je,{path:"/activity",element:c.jsx(Fe,{children:c.jsx(x3,{})})}),c.jsx(je,{path:"/views/new",element:c.jsx(Fe,{children:c.jsx(q3,{})})}),c.jsx(je,{path:"/views/:id",element:c.jsx(Fe,{children:c.jsx($3,{})})}),c.jsx(je,{path:"/n/:id",element:c.jsx(Fe,{children:c.jsx(M3,{})})}),c.jsx(je,{path:"/n/:id/edit",element:c.jsx(Fe,{children:c.jsx(C3,{})})}),c.jsx(je,{path:"/:id",element:c.jsx(zb,{})}),c.jsx(je,{path:"/:id/edit",element:c.jsx(zb,{suffix:"/edit"})}),c.jsx(je,{path:"/add",element:c.jsx(Fe,{children:c.jsx(S3,{})})}),c.jsx(je,{path:"/add-vault",element:c.jsx(Fe,{children:c.jsx(w3,{})})}),c.jsx(je,{path:"/add-vault/create",element:c.jsx(Fe,{children:c.jsx(E3,{})})}),c.jsx(je,{path:"/add-vault/ready",element:c.jsx(Fe,{children:c.jsx(T3,{})})}),c.jsx(je,{path:"/welcome",element:c.jsx(Fe,{children:c.jsx(B3,{})})}),c.jsx(je,{path:"/oauth/callback",element:c.jsx(Fe,{children:c.jsx(D3,{})})}),c.jsx(je,{path:"/vaults",element:c.jsx(Fe,{children:c.jsx(V3,{})})}),c.jsx(je,{path:"/account",element:c.jsx(Fe,{children:c.jsx(b3,{})})}),c.jsx(je,{path:"/settings",element:c.jsx(Fe,{children:c.jsx(k3,{})})}),c.jsx(je,{path:"*",element:c.jsx(G3,{})})]})})}),r?null:c.jsx(Y3,{})]})]}),r?null:c.jsx(JR,{}),r?null:c.jsx(ZR,{}),r?null:c.jsx(fO,{}),r?c.jsx(lC,{}):null]})}function X3(){V_(),b.useEffect(()=>{aS(Ss())},[]);const t=ae(a=>{var r;return((r=a.getActiveVault())==null?void 0:r.name)??null});return b.useEffect(()=>{document.title=t?`Parachute — ${t}`:"Parachute"},[t]),c.jsx(rC,{children:c.jsx(HO,{children:c.jsxs(N2,{children:[c.jsx(P3,{}),c.jsx(SC,{}),c.jsx(dj,{basename:pl(),children:c.jsx(FR,{children:c.jsx(F3,{})})})]})})})}var kd={exports:{}},Xi={},Ld={exports:{}},Ud={};/**
34
+ `)}const R0=512*1024*1024,ib=200;function hh(t){return t.contentEvicted?0:typeof t.byteSize=="number"&&Number.isFinite(t.byteSize)&&t.byteSize>=0?t.byteSize:WA(t)}function WA(t){var r,i,u,f;let a=(((r=t.content)==null?void 0:r.length)??0)+(((i=t.preview)==null?void 0:i.length)??0);return(u=t.links)!=null&&u.length&&(a+=JSON.stringify(t.links).length),(f=t.attachments)!=null&&f.length&&(a+=JSON.stringify(t.attachments).length),a}function e2(t){var a,r;return!!(t.content||(a=t.links)!=null&&a.length||(r=t.attachments)!=null&&r.length)}function t2(t){const a=t.preview??n2(t.content),i=t.displayTitle??hm(t.content);return{...t,content:void 0,links:void 0,attachments:void 0,contentEvicted:!0,preview:a,displayTitle:i,byteSize:(a==null?void 0:a.length)??0}}function n2(t){if(!t)return;const a=FA(t).replace(/\s+/g," ").trim();if(a)return a.length>ib?`${a.slice(0,ib).trimEnd()}…`:a}function a2(t,a,r){let i=0;for(const h of t)i+=hh(h);const u=i,f=[];if(i>a)for(const h of t){if(i<=a)break;h.contentEvicted||r(h.id)||e2(h)&&(f.push(h),i-=hh(h))}return{toEvict:f,totalBefore:u,totalAfter:i,freedBytes:u-i}}async function r2(t,a,r=R0){const i=await Lo(t,a),u=await fh(t,a),f=N0(u),h=a2(i,r,f);if(h.toEvict.length===0)return{evicted:0,freedBytes:0,totalBytes:h.totalAfter};const m=t.transaction("mirror_notes","readwrite");for(const p of h.toEvict)await m.store.put(t2(p));return await m.done,{evicted:h.toEvict.length,freedBytes:h.freedBytes,totalBytes:h.totalAfter}}async function TD(t,a){const r=await Lo(t,a);let i=0;for(const u of r)i+=hh(u);return i}const s2={includeContent:!0,includeLinks:!0,includeAttachments:!0},lb={includeContent:!1,includeLinks:!1,includeAttachments:!1},i2=6e4,l2=200,u2=1e3,o2=360*60*1e3,c2=1e3;function f2(t){return t instanceof Error?/cursor_invalid|cursor_query_mismatch/i.test(t.message):!1}class d2{constructor(a){fe(this,"timer",null);fe(this,"syncing",!1);fe(this,"sweeping",!1);fe(this,"evicting",!1);fe(this,"subscription",null);fe(this,"db");fe(this,"tickMs");fe(this,"pageLimit");fe(this,"maxDrainPages");fe(this,"sweepEnumLimit");fe(this,"sweepIntervalMs");fe(this,"ceilingBytes");fe(this,"onlineListener");fe(this,"visibilityListener");fe(this,"lastRun",null);this.opts=a,this.db=a.db,this.tickMs=a.tickIntervalMs??i2,this.pageLimit=a.pageLimit??l2,this.maxDrainPages=a.maxDrainPages??c2,this.sweepEnumLimit=a.sweepEnumLimit??u2,this.sweepIntervalMs=a.sweepIntervalMs??o2,this.ceilingBytes=a.ceilingBytes??R0,this.onlineListener=()=>{this.lastRun=this.syncOnce()},this.visibilityListener=()=>{typeof document<"u"&&document.visibilityState==="visible"&&(this.lastRun=this.syncOnce())}}start(){this.timer||(typeof window<"u"&&window.addEventListener("online",this.onlineListener),typeof document<"u"&&document.addEventListener("visibilitychange",this.visibilityListener),this.timer=setInterval(()=>{this.lastRun=this.syncOnce()},this.tickMs),this.lastRun=this.syncOnce())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&window.removeEventListener("online",this.onlineListener),typeof document<"u"&&document.removeEventListener("visibilitychange",this.visibilityListener),this.teardownSubscription()}get isSyncing(){return this.syncing}async syncOnce(){const a={pagesApplied:0,notesApplied:0,reWalked:!1};if(this.syncing)return{...a,skipped:"in-flight"};if(typeof navigator<"u"&&navigator.onLine===!1)return{...a,skipped:"offline"};const r=this.opts.resolveContext();if(!r)return this.teardownSubscription(),{...a,skipped:"no-context"};this.ensureSubscription(r),this.syncing=!0;try{const i=await this.withVaultLock(r.vaultId,()=>({...a,skipped:"locked"}),()=>this.drainCursor(r.client,r.vaultId));return await this.maybeSweep(r,i),await this.maybeEvict(i),i}catch(i){return{...a,error:i instanceof Error?i.message:String(i)}}finally{this.syncing=!1}}async withVaultLock(a,r,i){const u=typeof navigator<"u"?navigator.locks:void 0;return u!=null&&u.request?u.request(`mirror:${a}`,{ifAvailable:!0},async f=>f?i():r()):i()}async drainCursor(a,r){var p,y,S,v,x,T,j,_,C,O;let i=await _A(this.db,r)??"";const u=await go(this.db,r)===void 0;if(u){const B={phase:"hydrating"};await yd(this.db,r,B),(y=(p=this.opts).onStateChange)==null||y.call(p,r,B),(v=(S=this.opts).onProgress)==null||v.call(S,r,0)}let f=0,h=0,m=!1;try{let B=!1;for(;;){const k=i;let Y;try{Y=await a.queryNotesCursor(s2,k,this.pageLimit)}catch(G){if(!m&&f2(G)){await x0(this.db,r),i="",m=!0;continue}throw G}const Q=Y.items??[];if(Q.length>0&&(await UA(this.db,r,Q),h+=Q.length,u&&((T=(x=this.opts).onProgress)==null||T.call(x,r,h))),Q.length>0&&Y.nextCursor===void 0)throw new Error(`mirror drain: ${Q.length}-row page returned no next_cursor — cursor pagination contract violated (stale surface-client?)`);if(Y.nextCursor!==void 0&&(i=Y.nextCursor,await RA(this.db,r,i)),f+=1,Q.length===0){B=!0;break}if(Y.nextCursor===k)break;if(f>=this.maxDrainPages)throw new Error(`mirror drain: exceeded ${this.maxDrainPages} pages without exhausting the cursor`)}B&&await OA(this.db,r,Date.now());const H={phase:"live"};return await yd(this.db,r,H),(_=(j=this.opts).onStateChange)==null||_.call(j,r,H),{pagesApplied:f,notesApplied:h,reWalked:m}}catch(B){const H=B instanceof Error?B.message:String(B),k={phase:"error",lastError:H};return await yd(this.db,r,k),(O=(C=this.opts).onStateChange)==null||O.call(C,r,k),{pagesApplied:f,notesApplied:h,reWalked:m,error:H}}}async maybeSweep(a,r){if(r.error||r.skipped)return;const i=await MA(this.db,a.vaultId);(r.reWalked||i===void 0||Date.now()-i>=this.sweepIntervalMs)&&await this.reconcileSweep()}async maybeEvict(a){a.error||a.skipped||await this.evictIfOverCeiling()}async evictIfOverCeiling(){const a=i=>({evicted:0,freedBytes:0,totalBytes:0,skipped:i});if(this.evicting)return a("in-flight");const r=this.opts.resolveContext();if(!r)return a("no-context");this.evicting=!0;try{return await this.withVaultLock(r.vaultId,()=>a("locked"),()=>r2(this.db,r.vaultId,this.ceilingBytes))}finally{this.evicting=!1}}async reconcileSweep(){const a=i=>({deleted:0,backfilled:0,refetched:0,enumerated:0,aborted:i});if(this.sweeping)return a("in-flight");if(typeof navigator<"u"&&navigator.onLine===!1)return a("offline");const r=this.opts.resolveContext();if(!r)return a("no-context");this.sweeping=!0;try{return await this.withVaultLock(r.vaultId,()=>a("locked"),()=>this.runSweep(r.client,r.vaultId))}finally{this.sweeping=!1}}async runSweep(a,r){const i=await this.enumerateServerIds(a);if(!i.complete)return{deleted:0,backfilled:0,refetched:0,enumerated:i.index.size,aborted:"incomplete-enumeration"};if(i.index.size===0)return{deleted:0,backfilled:0,refetched:0,enumerated:0,aborted:"empty-enumeration"};const u=await fh(this.db,r),f=N0(u),h=await Lo(this.db,r),m=YA(h,i.index,f);await zA(this.db,r,m.toDelete);let p=0,y=0;if(a.getNote){for(const S of m.toBackfill){const v=await a.getNote(S,{includeLinks:!0,includeAttachments:!0});v&&(await ch(this.db,r,v),p+=1)}for(const S of m.toRefetch){const v=await a.getNote(S,{includeLinks:!0,includeAttachments:!0});v&&(await ch(this.db,r,v),y+=1)}}return await this.refreshTags(a,r),await DA(this.db,r,Date.now()),{deleted:m.toDelete.length,backfilled:p,refetched:y,enumerated:i.index.size}}async enumerateServerIds(a){const r=new Map;let i="",u=0;try{for(;;){const f=i,h=await a.queryNotesCursor(lb,f,this.sweepEnumLimit),m=h.items??[];for(const p of m)r.set(p.id,p.updatedAt??p.createdAt??"");if(m.length>0&&h.nextCursor===void 0)return{index:r,complete:!1};if(h.nextCursor!==void 0&&(i=h.nextCursor),m.length===0)break;if(h.nextCursor===f)return{index:r,complete:!1};if(u+=1,u>=this.maxDrainPages)return{index:r,complete:!1}}return{index:r,complete:!0}}catch{return{index:r,complete:!1}}}async refreshTags(a,r){if(a.listTags)try{const i=await a.listTags();await kA(this.db,r,i)}catch{}}ensureSubscription(a){var f;const r=a.client;if(!r.subscribe||((f=this.subscription)==null?void 0:f.vaultId)===a.vaultId)return;this.teardownSubscription();const i=a.vaultId,u=r.subscribe(lb,{onSnapshot:()=>{},onUpsert:()=>{},onRemove:h=>this.applyWsRemove(i,h)});this.subscription={vaultId:i,unsubscribe:u}}teardownSubscription(){var a;(a=this.subscription)==null||a.unsubscribe(),this.subscription=null}async applyWsRemove(a,r){try{if(zs(r)||(await fh(this.db,a)).has(r))return;await w0(this.db,a,r)}catch{}}}const h2="lens-blobs";function m2(){return typeof navigator<"u"&&typeof navigator.storage<"u"&&typeof navigator.storage.getDirectory=="function"}async function vd(){return(await navigator.storage.getDirectory()).getDirectoryHandle(h2,{create:!0})}function jD(){return crypto.randomUUID()}class p2{constructor(){fe(this,"backend","opfs")}async put(a,r,i){const u=await vd(),h=await(await u.getFileHandle(a,{create:!0})).createWritable();await h.write(r),await h.close();const p=await(await u.getFileHandle(`${a}.meta`,{create:!0})).createWritable();await p.write(i),await p.close()}async get(a){try{const r=await vd(),f=await(await(await r.getFileHandle(a)).getFile()).arrayBuffer();let h="application/octet-stream";try{h=await(await(await r.getFileHandle(`${a}.meta`)).getFile()).text()||h}catch{}return{data:f,mimeType:h}}catch(r){if(r instanceof DOMException&&r.name==="NotFoundError")return null;throw r}}async delete(a){const r=await vd();for(const i of[a,`${a}.meta`])try{await r.removeEntry(i)}catch(u){if(u instanceof DOMException&&u.name==="NotFoundError")continue;throw u}}}class g2{constructor(a){fe(this,"backend","idb");this.db=a}async put(a,r,i,u){await this.db.put("blobs",{blobId:a,data:r,mimeType:i,vaultId:u,createdAt:Date.now()})}async get(a){const r=await this.db.get("blobs",a);return r?{data:r.data,mimeType:r.mimeType}:null}async delete(a){await this.db.delete("blobs",a)}}function y2(t){return m2()?new p2:new g2(t)}const v2=3e4;class b2{constructor(a){fe(this,"timer",null);fe(this,"draining",!1);fe(this,"tickMs");fe(this,"onlineListener");fe(this,"lastRun",null);this.opts=a,this.tickMs=a.tickIntervalMs??v2,this.onlineListener=()=>{this.lastRun=this.runOnce()}}start(){this.timer||(typeof window<"u"&&window.addEventListener("online",this.onlineListener),this.timer=setInterval(()=>{this.lastRun=this.runOnce()},this.tickMs),this.lastRun=this.runOnce())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&window.removeEventListener("online",this.onlineListener)}get isDraining(){return this.draining}async runOnce(){var r,i,u,f;if(this.draining||typeof navigator<"u"&&navigator.onLine===!1)return null;const a=this.opts.resolveContext();if(!a)return null;this.draining=!0,(i=(r=this.opts).onDrainStart)==null||i.call(r);try{const h=await B2({db:this.opts.db,client:a.client,vaultId:a.vaultId,blobStore:this.opts.blobStore,...this.opts.mirror&&{mirror:this.opts.mirror}});return(f=(u=this.opts).onDrain)==null||f.call(u,h),h}finally{this.draining=!1}}}async function x2(){var t;if(typeof navigator>"u"||!((t=navigator.storage)!=null&&t.persist))return!1;try{return await navigator.storage.persist()}catch{return!1}}async function S2(){var t;if(typeof navigator>"u"||!((t=navigator.storage)!=null&&t.persisted))return!1;try{return await navigator.storage.persisted()}catch{return!1}}async function w2(){var t;if(typeof navigator>"u"||!((t=navigator.storage)!=null&&t.estimate))return{persisted:!1,usage:null,quota:null,supported:!1};try{const[a,r]=await Promise.all([S2(),navigator.storage.estimate()]);return{persisted:a,usage:r.usage??null,quota:r.quota??null,supported:!0}}catch{return{persisted:!1,usage:null,quota:null,supported:!1}}}const C0="lens:sync:lastSyncedAt";function E2(){try{const t=localStorage.getItem(C0);if(!t)return null;const a=Number(t);return Number.isFinite(a)?a:null}catch{return null}}const T2={enabled:!1,state:"off",lastSyncedAt:null,syncNow:async()=>{},clearOffline:async()=>{}},O0=b.createContext({db:null,blobStore:null,engine:null,isOnline:!0,isDraining:!1,lastSyncedAt:null,mirror:T2});function j2(t,a,r,i){return t?a?r==="error"?"error":r==="hydrating"||r===void 0&&i===null?"hydrating":"synced":"offline":"off"}function Zt(){return b.useContext(O0)}function N2({children:t}){const[a,r]=b.useState(null),[i,u]=b.useState(null),[f,h]=b.useState(typeof navigator<"u"?navigator.onLine:!0),[m,p]=b.useState(!1),[y,S]=b.useState(()=>E2()),v=ke(),x=ae(re=>re.activeVaultId),T=pt(),j=b.useMemo(()=>ra(),[]),[_,C]=b.useState(void 0),[O,B]=b.useState(void 0),[H,k]=b.useState(null);b.useEffect(()=>{let re=!1,ee=null;return NA().then(M=>{if(re){M.close();return}ee=M,r(M),u(y2(M)),x2()}).catch(()=>{}),()=>{re=!0,ee==null||ee.close()}},[]),b.useEffect(()=>{if(typeof window>"u")return;const re=()=>h(!0),ee=()=>h(!1);return window.addEventListener("online",re),window.addEventListener("offline",ee),()=>{window.removeEventListener("online",re),window.removeEventListener("offline",ee)}},[]);const Y=b.useRef(v),Q=b.useRef(x),G=b.useRef(T);Y.current=v,Q.current=x,G.current=T;const F=b.useMemo(()=>!a||!i?null:new b2({db:a,blobStore:i,mirror:$A(a),resolveContext:()=>{const re=Y.current,ee=Q.current;return!re||!ee?null:{client:re,vaultId:ee}},onDrainStart:()=>{p(!0)},onDrain:re=>{if(p(!1),re.drained>0){const ee=Date.now();S(ee);try{localStorage.setItem(C0,String(ee))}catch{}const M=Q.current;G.current.invalidateQueries({queryKey:["notes",M]}),G.current.invalidateQueries({queryKey:["tags",M]}),G.current.invalidateQueries({queryKey:["vaultInfo",M]})}}}),[a,i]);b.useEffect(()=>{if(F)return F.start(),()=>F.stop()},[F]);const Z=b.useMemo(()=>{if(!a||!j)return null;const re=ee=>ee===Q.current;return new d2({db:a,resolveContext:()=>{const ee=Y.current,M=Q.current;return!ee||!M?null:{client:ee,vaultId:M}},onStateChange:(ee,M)=>{re(ee)&&(C(M.phase),M.phase==="live"&&(B(void 0),go(a,ee).then(P=>{re(ee)&&k(P??null)})))},onProgress:(ee,M)=>{re(ee)&&B({done:M})}})},[a,j]);b.useEffect(()=>{if(Z)return Z.start(),()=>Z.stop()},[Z]),b.useEffect(()=>{if(!a||!j||!x){C(void 0),B(void 0),k(null);return}let re=!0;return B(void 0),Promise.all([CA(a,x),go(a,x)]).then(([ee,M])=>{re&&(C(ee==null?void 0:ee.phase),k(M??null))}),()=>{re=!1}},[a,j,x]);const le=b.useCallback(async()=>{await(Z==null?void 0:Z.syncOnce())},[Z]),de=b.useCallback(async()=>{!a||!x||(await HA(a,x),await x0(a,x),await LA(a,x),C(void 0),B(void 0),k(null),T.invalidateQueries({queryKey:["notes",x]}),T.invalidateQueries({queryKey:["notesForDateViews",x]}),T.invalidateQueries({queryKey:["notesForPathTree",x]}),T.invalidateQueries({queryKey:["tags",x]}))},[a,x,T]),ye=b.useMemo(()=>({enabled:j,state:j2(j,f,_,H),progress:O,lastSyncedAt:H,syncNow:le,clearOffline:de}),[j,f,_,O,H,le,de]),we=b.useMemo(()=>({db:a,blobStore:i,engine:F,isOnline:f,isDraining:m,lastSyncedAt:y,mirror:ye}),[a,i,F,f,m,y,ye]);return c.jsx(O0.Provider,{value:we,children:t})}const zt={pinned:"pinned",archived:"archived",captureVoice:"capture",captureText:"capture",view:"view"},ND=["pinned","archived","captureVoice","captureText","view"],A2="lens:tag-roles:";function _2(t){return A2+t}function Fi(t,a){if(typeof t!="string")return a;const r=t.trim().replace(/^#/,"");return r.length>0?r:a}function zo(t){if(!t||typeof t!="object")return{...zt};const a=t;return{pinned:Fi(a.pinned,zt.pinned),archived:Fi(a.archived,zt.archived),captureVoice:Fi(a.captureVoice,zt.captureVoice),captureText:Fi(a.captureText,zt.captureText),view:Fi(a.view,zt.view)}}function R2(t){try{const a=localStorage.getItem(_2(t));return a?zo(JSON.parse(a)):{...zt}}catch{return{...zt}}}const _r=".parachute/notes/settings",M0=1,sa={schemaVersion:M0,tagRoles:{...zt}};function mh(t){if(!t||typeof t!="object")return{...sa,tagRoles:{...zt}};const a=t,r=typeof a.schemaVersion=="number"?a.schemaVersion:M0,i=zo(a.tagRoles);return{schemaVersion:r,tagRoles:i}}function mm(t){if(!t||!t.metadata||typeof t.metadata!="object")return{...sa,tagRoles:{...zt}};const a=t.metadata;return mh(a.notes??a.lens)}function na(t,a){return{schemaVersion:a.schemaVersion??t.schemaVersion,tagRoles:a.tagRoles?zo({...t.tagRoles,...a.tagRoles}):t.tagRoles}}function C2(t,a){if(!t)return{...a,tagRoles:a.tagRoles?{...a.tagRoles}:void 0};const r={};return(a.schemaVersion!==void 0||t.schemaVersion!==void 0)&&(r.schemaVersion=a.schemaVersion??t.schemaVersion),(a.tagRoles||t.tagRoles)&&(r.tagRoles={...t.tagRoles??{},...a.tagRoles??{}}),r}const O2="notes:settings:";function D0(t){return O2+t}function k0(t){return{settings:t??{...sa,tagRoles:{...zt}},serverSettings:t,serverUpdatedAt:null,noteExists:!1,dirtyPatch:null}}function M2(t){try{const a=localStorage.getItem(D0(t));if(!a)return null;const r=JSON.parse(a);if(!r||typeof r!="object")return null;const i=r.serverSettings===null?null:r.serverSettings?mh(r.serverSettings):null,u=r.dirtyPatch??null,f=i??{...sa,tagRoles:{...zt}};return{settings:u?na(f,u):mh(r.settings??f),serverSettings:i,serverUpdatedAt:typeof r.serverUpdatedAt=="string"?r.serverUpdatedAt:null,noteExists:r.noteExists===!0,dirtyPatch:u}}catch{return null}}function Ju(t,a){try{localStorage.setItem(D0(t),JSON.stringify(a))}catch{}}function D2(t){if(typeof localStorage>"u"||!localStorage.getItem(`lens:tag-roles:${t}`))return null;const r={tagRoles:R2(t)};return{settings:na(sa,r),serverSettings:null,serverUpdatedAt:null,noteExists:!1,dirtyPatch:r}}function k2(t){const a=M2(t);if(a)return a;const r=D2(t);return r||k0(null)}async function ub(t,a,r,i){if(!a.noteExists){const u=na(a.serverSettings??sa,r);try{const f=await t.createNote({path:_r,content:"",metadata:{notes:u}},{signal:i});return{server:u,serverUpdatedAt:f.updatedAt??f.createdAt??null,noteExists:!0}}catch(f){if(f instanceof Wn||L2(f))return bd(t,r,i);throw f}}if(a.serverUpdatedAt&&a.serverSettings)try{const u=na(a.serverSettings,r),f=await t.updateNote(_r,{metadata:{notes:u},if_updated_at:a.serverUpdatedAt},{signal:i});return{server:u,serverUpdatedAt:f.updatedAt??a.serverUpdatedAt,noteExists:!0}}catch(u){if(u instanceof Wn)return bd(t,r,i);throw u}return bd(t,r,i)}async function bd(t,a,r){let i=null;try{i=await t.getNote(_r)}catch(p){if(!(p instanceof Sl))throw p;i=null}if(!i){const p=na(sa,a),y=await t.createNote({path:_r,content:"",metadata:{notes:p}},{signal:r});return{server:p,serverUpdatedAt:y.updatedAt??y.createdAt??null,noteExists:!0}}const u=mm(i),f=na(u,a),h=i.updatedAt??i.createdAt,m=await t.updateNote(_r,{metadata:{notes:f},if_updated_at:h},{signal:r});return{server:f,serverUpdatedAt:m.updatedAt??h??null,noteExists:!0}}function L2(t){if(!(t instanceof Error))return!1;const a=t.message.toLowerCase();return a.includes("already exists")||a.includes("duplicate")||a.includes("conflict")}function U2(t){const a=ke(),r=pt(),{db:i}=Zt(),u=b.useMemo(()=>t?k2(t):k0(null),[t]),[f,h]=b.useState(u),[m,p]=b.useState(a?"loading":"offline");b.useEffect(()=>{h(u),p(a?"loading":"offline")},[u,a]);const y=lt({queryKey:["vault-settings",t],enabled:!!t&&!!a,queryFn:async()=>{try{const v=await a.getNote(_r);return v?{server:mm(v),serverUpdatedAt:v.updatedAt??v.createdAt??null,noteExists:!0}:{server:null,serverUpdatedAt:null,noteExists:!1}}catch(v){if(!(v instanceof Sl))throw v;return{server:null,serverUpdatedAt:null,noteExists:!1}}},retry:!1,staleTime:6e4});b.useEffect(()=>{if(!t||!a||!y.data)return;const v=y.data;if(f.dirtyPatch){const T=f.dirtyPatch;(async()=>{try{const j=await ub(a,{serverSettings:v.server,serverUpdatedAt:v.serverUpdatedAt,noteExists:v.noteExists},T),_={settings:j.server,serverSettings:j.server,serverUpdatedAt:j.serverUpdatedAt,noteExists:!0,dirtyPatch:null};h(_),Ju(t,_),p("synced"),r.invalidateQueries({queryKey:["vault-settings",t]})}catch{p("offline")}})();return}const x=v.server?{settings:v.server,serverSettings:v.server,serverUpdatedAt:v.serverUpdatedAt,noteExists:v.noteExists,dirtyPatch:null}:{settings:f.settings,serverSettings:null,serverUpdatedAt:null,noteExists:!1,dirtyPatch:null};h(x),Ju(t,x),p("synced")},[t,a,y.data]),b.useEffect(()=>{y.isError&&p("offline")},[y.isError]);const S=b.useCallback(async v=>{if(!t)return;const x=C2(f.dirtyPatch,v),j={settings:na(f.serverSettings??sa,x),serverSettings:f.serverSettings,serverUpdatedAt:f.serverUpdatedAt,noteExists:f.noteExists,dirtyPatch:x};if(h(j),Ju(t,j),!a){p("offline");return}const _=i?async()=>(await El(i,{kind:"update-settings",notePath:_r,patch:x,baselineUpdatedAt:f.serverUpdatedAt},{vaultId:t}),null):null;try{const C=await Ho(O=>ub(a,{serverSettings:f.serverSettings,serverUpdatedAt:f.serverUpdatedAt,noteExists:f.noteExists},v,O),_);if(C){const O={settings:C.server,serverSettings:C.server,serverUpdatedAt:C.serverUpdatedAt,noteExists:!0,dirtyPatch:null};h(O),Ju(t,O),p("synced"),r.invalidateQueries({queryKey:["vault-settings",t]})}else p(Ys()?"offline":"queued")}catch(C){C instanceof Wn?p("conflict"):p("offline")}},[t,a,i,f,r]);return{settings:f.settings,update:S,status:m}}function wl(t){const{settings:a,update:r}=U2(t),i=b.useCallback(u=>{if(!t)return;const f=u??{...zt};r({tagRoles:zo(f)})},[t,r]);return{roles:a.tagRoles,setRoles:i}}const L0="auth-halted",z2=600*1e3;function V2(t){const a=2**t*1e3;return Math.min(a,z2)}async function El(t,a,r){const i={id:crypto.randomUUID(),vaultId:r.vaultId,mutation:a,createdAt:Date.now(),attemptCount:0,nextAttemptAt:0,status:"pending"},u=await t.add("pending",i);return{...i,seq:u}}async function U0(t,a){return a?t.getAllFromIndex("pending","by-vault",a):t.getAll("pending")}async function B2(t){const a=t.now??(()=>Date.now()),r={drained:0,stashed:0,deferred:0,authHalted:!1};for(;;){const i=await H2(t.db,t.vaultId,a());if(!i)break;try{await q2(t,i),await t.db.delete("pending",i.seq),r.drained+=1}catch(u){if(u instanceof Uo){await Gs(t.db,L0,{vaultId:t.vaultId,at:a(),message:u.message}),r.authHalted=!0,await ob(t.db,i,u,a),r.deferred+=1;break}if(u instanceof Wn){await t.db.put("pending",{...i,status:"needs-human",lastError:`Conflict: current=${u.currentUpdatedAt??"?"} expected=${u.expectedUpdatedAt??"?"}`,attemptCount:i.attemptCount+1}),r.stashed+=1;continue}if(u instanceof pr){await t.db.put("pending",{...i,attemptCount:i.attemptCount+1,lastError:u.message,nextAttemptAt:a()+5e3}),r.deferred+=1;break}if(u instanceof Sl){await t.db.delete("pending",i.seq),r.drained+=1;continue}await ob(t.db,i,u,a),r.deferred+=1;break}}return r}async function H2(t,a,r){let u=await t.transaction("pending","readonly").store.openCursor();for(;u;){const f=u.value;if(f.vaultId===a&&f.status==="pending"&&f.nextAttemptAt<=r)return f;u=await u.continue()}return null}async function ob(t,a,r,i){const u=a.attemptCount+1;await t.put("pending",{...a,attemptCount:u,nextAttemptAt:i()+V2(u),lastError:r instanceof Error?r.message:String(r)})}class pr extends Error{}async function q2(t,a){var i,u,f;const r=a.mutation;switch(r.kind){case"create-note":{const h=await t.client.createNote(r.payload);await oA(t.db,r.localId,h.id,t.vaultId),await((i=t.mirror)==null?void 0:i.localIdLanded(t.vaultId,r.localId,h));return}case"update-note":{const h=await bs(t.db,r.targetId,t.vaultId);if(!h)throw new pr(`Awaiting local id ${r.targetId}`);const m=await I2(t.client,h,r.payload,r.baselineUpdatedAt);m&&await((u=t.mirror)==null?void 0:u.upsert(t.vaultId,m));return}case"update-settings":{await K2(t.client,r.notePath,r.patch);return}case"delete-note":{const h=await bs(t.db,r.targetId,t.vaultId);if(!h)throw new pr(`Awaiting local id ${r.targetId}`);await t.client.deleteNote(h),await((f=t.mirror)==null?void 0:f.remove(t.vaultId,h));return}case"upload-attachment":{const h=await t.blobStore.get(r.blobId);if(!h)throw new pr(`Missing blob ${r.blobId}`);const m=h.mimeType||r.mimeType,p=new File([h.data],r.filename,{type:m}),y=await t.client.uploadStorageFile(p);await fA(t.db,r.blobId,y.path,t.vaultId),await t.blobStore.delete(r.blobId);return}case"link-attachment":{const h=await bs(t.db,r.noteId,t.vaultId);if(!h)throw new pr(`Awaiting local id ${r.noteId}`);let m=r.pathRef;if(g0(r.pathRef)&&(m=await cA(t.db,r.pathRef,t.vaultId),!m))throw new pr(`Awaiting blob ${y0(r.pathRef)}`);await t.client.linkAttachment(h,{path:m,mimeType:r.mimeType,...r.transcribe?{transcribe:!0}:{},...r.segment_index!==void 0?{segment_index:r.segment_index}:{}});return}case"delete-attachment":{const h=await bs(t.db,r.noteId,t.vaultId);if(!h)throw new pr(`Awaiting local id ${r.noteId}`);await t.client.deleteAttachment(h,r.attachmentId);return}}}async function $2(t,a){const r=await t.get("pending",a);r&&await t.put("pending",{...r,status:"pending",attemptCount:0,nextAttemptAt:0,lastError:void 0})}async function Q2(t,a){await t.delete("pending",a)}const xd=3,cb=3;async function I2(t,a,r,i){let u=i;for(let f=0;f<=cb;f++){const h=u?{...r,if_updated_at:u}:{...r};try{return await t.updateNote(a,h)}catch(m){if(m instanceof Wn&&f<cb){if(m.currentUpdatedAt)u=m.currentUpdatedAt;else{const p=await t.getNote(a);if(!p)throw new Sl(`Note ${a} disappeared during retry`);u=p.updatedAt??p.createdAt}continue}if(m instanceof Wn)return await t.updateNote(a,{...r,force:!0});throw m}}}async function K2(t,a,r){for(let i=0;i<=xd;i++){let u=null;try{u=await t.getNote(a)}catch(p){if(!(p instanceof Sl))throw p}if(!u)try{await t.createNote({path:a,content:"",metadata:{notes:na(sa,r)}});return}catch(p){if(p instanceof Wn&&i<xd)continue;throw p}const f=mm(u),h=na(f,r),m=u.updatedAt??u.createdAt;try{await t.updateNote(a,{metadata:{notes:h},if_updated_at:m});return}catch(p){if(p instanceof Wn&&i<xd)continue;if(p instanceof Wn){await t.updateNote(a,{metadata:{notes:h},force:!0});return}throw p}}}async function G2(t,a){const r=await U0(t,a),i=t.transaction("pending","readwrite");for(const u of r)await i.store.delete(u.seq);return await i.done,r.length}let Y2=1;const aa=Ia(t=>({toasts:[],push(a,r,i){const u=Y2++;return t(f=>({toasts:[...f.toasts,{id:u,message:a,tone:r??"info",durationMs:i==null?void 0:i.durationMs}]})),u},dismiss(a){t(r=>({toasts:r.toasts.filter(i=>i.id!==a)}))},clear(){t({toasts:[]})}})),P2=/_Transcript pending(?: \(part \d+\))?\._/,F2=/_Transcription unavailable(?: \(part \d+\))?\._/,X2=/_Monthly voice limit reached[^\n]*\._/;function z0(t){var r;const a={pending:0,failed:0,done:0,total:0};for(const i of t??[]){const u=(r=i.metadata)==null?void 0:r.transcribe_status;(u==="pending"||u==="done"||u==="failed")&&(a[u]+=1,a.total+=1)}return a}function Z2(t){const a=t.content??"",r=X2.test(a),{pending:i,failed:u,total:f}=z0(t.attachments);return f>0?i>0?"pending":u>0?r?"voice-limit":"failed":"none":P2.test(a)?"pending":r?"voice-limit":F2.test(a)?"failed":"none"}function AD(t){const{pending:a,failed:r,done:i,total:u}=z0(t.attachments);return u<=1||a===0?null:{done:i+r,total:u}}function J2(t){return Z2(t)==="pending"}function W2(t){var i,u;const a=(i=t.attachments)==null?void 0:i.map(f=>{var h;return((h=f.metadata)==null?void 0:h.transcribe_status)==="failed"?{...f,metadata:{...f.metadata,transcribe_status:"pending"}}:f}),r=(u=t.content)==null?void 0:u.replace(/_Transcription unavailable( \(part \d+\))?\._/g,(f,h)=>`_Transcript pending${h??""}._`);return{...t,...a?{attachments:a}:{},...r?{content:r}:{}}}const yo="lens:auth-halt:";function fb(){const t={};if(typeof localStorage>"u")return t;try{for(let a=0;a<localStorage.length;a++){const r=localStorage.key(a);if(!(r!=null&&r.startsWith(yo)))continue;const i=localStorage.getItem(r);if(i)try{const u=JSON.parse(i);u!=null&&u.vaultId&&(t[u.vaultId]=u)}catch{}}}catch{}return t}const Rr=Ia(t=>({byVault:fb(),markHalted(a,r){const i={vaultId:a,reason:r,at:Date.now()};try{localStorage.setItem(yo+a,JSON.stringify(i))}catch{}t(u=>({byVault:{...u.byVault,[a]:i}}))},clearHalt(a){try{localStorage.removeItem(yo+a)}catch{}t(r=>{if(!(a in r.byVault))return r;const{[a]:i,...u}=r.byVault;return{byVault:u}})},reloadFromStorage(){t({byVault:fb()})}})),e_=yo,t_=mx;function Vo({queryKey:t,params:a,client:r,enabled:i=!0}){const u=pt(),[f,h]=b.useState(!1),m=a.toString(),p=JSON.stringify(t);return b.useEffect(()=>{if(h(!1),!i||!r)return;const y=new URLSearchParams(m);if(!t_(y))return;let S=!0;const v=zE(r,y),x=v.getList();let T=null;const j=()=>{if(!S)return;const C=v.getState();h(C.status==="live"),C.list!==x&&C.list!==T&&(T=C.list,u.setQueryData(t,C.list))},_=v.subscribe(j);return j(),()=>{S=!1,h(!1),_(),v.close()}},[r,m,p,i,u]),{isLive:f}}const gr=50,n_={search:"",tags:[],tagMatch:"any",pathPrefix:"",sort:"desc",limit:gr,offset:0};function a_(t){const a=new URLSearchParams,r=t.search.trim();r&&a.set("search",r),t.tags.length>0&&(a.set("tag",t.tags.join(",")),t.tags.length>1&&a.set("tag_match",t.tagMatch));const i=t.pathPrefix.trim();return i&&a.set("path_prefix",i),t.hasTags===!1?a.set("has_tags","false"):t.hasTags===!0&&a.set("has_tags","true"),t.hasLinks===!1?a.set("has_links","false"):t.hasLinks===!0&&a.set("has_links","true"),a.set("sort",t.sort),a.set("limit",String(t.limit)),t.offset>0&&a.set("offset",String(t.offset)),a}function r_(t){return t.search.trim().length>0||t.tags.length>0||t.pathPrefix.trim().length>0}const s_=3,Wu=[1e3,2e3,4e3,8e3,16e3,3e4];function i_(t){return{vaultId:t,state:"healthy",consecutiveFailures:0,lastErrorAt:null,lastErrorReason:null,nextProbeAt:null,backoffIndex:0}}function l_(t){const a=Math.min(t,Wu.length-1);return Wu[a]??Wu[Wu.length-1]??3e4}const Dr=Ia(t=>({byVault:{},reportSignal(a,r,i){t(u=>{const f=u.byVault[a]??i_(a);if(r==="healthy"){if(!(a in u.byVault))return u;const{[a]:v,...x}=u.byVault;return{byVault:x}}const h=f.consecutiveFailures+1,m=f.backoffIndex+1,p=h>=s_?"down":"retrying",y=Date.now(),S={vaultId:a,state:p,consecutiveFailures:h,lastErrorAt:y,lastErrorReason:i??null,nextProbeAt:y+l_(m),backoffIndex:m};return{byVault:{...u.byVault,[a]:S}}})},resetToHealthy(a){t(r=>{if(!(a in r.byVault))return r;const{[a]:i,...u}=r.byVault;return{byVault:u}})}})),u_="Parachute Notes";async function V0(t,a=fetch.bind(globalThis)){return fE(t,a)}async function o_(t,a,r=fetch.bind(globalThis)){return dE(t,{clientName:u_,redirectUri:a},r)}const c_="/oauth/callback",f_="vault:read vault:write";function d_(){return pl()}function h_(t=window.location.origin){return`${t.replace(/\/$/,"")}${d_()}${c_}`}function m_(t){let a;try{a=new URL(kh(t))}catch{return}const r=a.pathname.match(/^\/vault\/([^/]+)$/);if(r!=null&&r[1])try{return decodeURIComponent(r[1])}catch{return}}async function pm(t,a=f_,r=fetch.bind(globalThis),i={}){const u=kh(t),f=h_(),h=await V0(u,r);let m=Wj(h.issuer,f);m||(m=(await o_(h.registration_endpoint,f,r)).client_id,eN(h.issuer,f,m));const p=gE(),y=await yE(p),S=vE(),v={issuerUrl:u,issuer:h.issuer,tokenEndpoint:h.token_endpoint,clientId:m,codeVerifier:p,state:S,redirectUri:f,scope:a,startedAt:new Date().toISOString(),...i.priorHaltedVaultId?{priorHaltedVaultId:i.priorHaltedVaultId}:{},...i.redirect?{redirect:i.redirect}:{}};Jj(v);const x=new URL(h.authorization_endpoint);if(x.searchParams.set("response_type","code"),x.searchParams.set("client_id",m),x.searchParams.set("redirect_uri",f),x.searchParams.set("code_challenge",y),x.searchParams.set("code_challenge_method","S256"),x.searchParams.set("state",S),x.searchParams.set("scope",a),i.params)for(const[T,j]of Object.entries(i.params))x.searchParams.has(T)||x.searchParams.set(T,j);if(!x.searchParams.has("vault")){const T=m_(u);T&&x.searchParams.set("vault",T)}return{authorizeUrl:x.toString(),pending:v}}function p_(t){if(typeof t!="string"||t.length===0)return;let a;try{a=new URL(t)}catch{return}if(!(a.protocol!=="http:"&&a.protocol!=="https:"))return t}function g_(t){let a;try{a=JSON.parse(t)}catch{return null}if(typeof a!="object"||a===null)return null;const r=a;if(r.error!=="invalid_client")return null;const i=p_(r.approve_url);return i?{approveUrl:i}:null}async function _D(t,a,r=fetch.bind(globalThis)){const i=Zj();if(!i)throw new Error("No pending OAuth flow. Start the connect flow from the vault page.");if(i.state!==a)throw Fu(),new Error("OAuth state mismatch. The flow was likely interrupted; please try again.");const u=new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:i.codeVerifier,client_id:i.clientId,redirect_uri:i.redirectUri}),f=await r(i.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:u.toString()});if(!f.ok){const m=await f.text();Fu();const p=g_(m);throw p?new xE(p.approveUrl):new Error(`Token exchange failed (${f.status}): ${m}`)}const h=await f.json();if(!h.access_token)throw Fu(),new Error("Token response missing access_token");return Fu(),{pending:i,token:h}}async function y_(t,a=fetch.bind(globalThis)){const r=new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken,client_id:t.clientId}),i=await a(t.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:r.toString()});if(!i.ok){const f=await i.text();throw new cx(i.status,f)}const u=await i.json();if(!u.access_token)throw new Error("Refresh response missing access_token");return u}const Sd=new Map;async function v_(t){const a=Sd.get(t);if(a)return a;const r=b_(t).finally(()=>{Sd.delete(t)});return Sd.set(t,r),r}async function b_(t){const a=ae.getState().vaults[t];if(a){const{isHostedVaultRecord:i,remintHostedVault:u}=await Qe(async()=>{const{isHostedVaultRecord:f,remintHostedVault:h}=await Promise.resolve().then(()=>vN);return{isHostedVaultRecord:f,remintHostedVault:h}},[]);if(i(a.clientId)){try{await u(a.name);const f=Ls(t);if(f!=null&&f.accessToken)return Rr.getState().clearHalt(t),f.accessToken}catch{}return null}}const r=Ls(t);if(!(r!=null&&r.refreshToken)||!(a!=null&&a.tokenEndpoint)||!a.clientId)return null;try{const i=await y_({tokenEndpoint:a.tokenEndpoint,clientId:a.clientId,refreshToken:r.refreshToken}),u=bE(i);return!u.refreshToken&&r.refreshToken&&(u.refreshToken=r.refreshToken),Qx(t,u),Rr.getState().clearHalt(t),u.accessToken}catch(i){if(i instanceof cx&&i.status>=400&&i.status<500){const u=i.oauthError==="invalid_grant"||i.status===400||i.status===401?"Your vault session expired. Reconnect to resume syncing.":`Token refresh failed (${i.status}). Reconnect to resume syncing.`;Rr.getState().markHalted(t,u)}return null}}function ke(){const t=ae(r=>r.getActiveVault()),a=ae(r=>r.activeVaultId);return b.useMemo(()=>{if(!t||!a)return null;const r=Ls(a);return r?new KA({vaultUrl:t.url,accessToken:r.accessToken,onAuthError:()=>v_(a),onAuthRevoked:i=>Rr.getState().markHalted(a,`Vault rejected the current session (${i}).`),onReachability:(i,u)=>Dr.getState().reportSignal(a,i,u)}):null},[t,a])}async function gm(t,a,r,i){const u=()=>t&&a?j0(t,a,r):Promise.resolve(null);if(t&&a&&Ys()){const f=await u();if(f)return f}try{return await i()}catch(f){if(f instanceof il){const h=await u();if(h)return h}throw f}}async function x_(t,a,r,i){const u=()=>t&&a&&r?T0(t,a,r):Promise.resolve(void 0);if(t&&a&&r&&Ys()){const f=await u();if(f)return f}try{return await i()}catch(f){if(f instanceof il){const h=await u();if(h)return h}throw f}}async function S_(t,a,r){const i=()=>t&&a?S0(t,a):Promise.resolve(void 0);if(t&&a&&Ys()){const u=await i();if(u)return u}try{return await r()}catch(u){if(u instanceof il){const f=await i();if(f)return f}throw u}}function ym(t,a,r,i){const[u,f]=b.useState(void 0),h=r.toString();return b.useEffect(()=>{if(!i||!t||!a){f(void 0);return}let m=!0;return j0(t,a,new URLSearchParams(h)).then(p=>{m&&p&&f(p)}).catch(()=>{}),()=>{m=!1}},[i,t,a,h]),u}function w_(t,a,r,i){const[u,f]=b.useState(void 0);return b.useEffect(()=>{if(f(void 0),!i||!t||!a||!r)return;let h=!0;return T0(t,a,r).then(m=>{h&&m&&f(m)}).catch(()=>{}),()=>{h=!1}},[i,t,a,r]),u}function E_(t,a,r){const[i,u]=b.useState(void 0);return b.useEffect(()=>{if(!r||!t||!a){u(void 0);return}let f=!0;return S0(t,a).then(h=>{f&&h&&u(h)}).catch(()=>{}),()=>{f=!1}},[r,t,a]),i}function B0(){const t=ke(),a=ae(r=>r.activeVaultId);return lt({queryKey:["vaultInfo",a],enabled:!!t,queryFn:()=>t.vaultInfo(!0),staleTime:3e4})}function RD(){return H0().capability}function H0(){var m,p,y;const t=ke(),a=ae(S=>S.activeVaultId),r=B0(),i=!!t&&r.isSuccess&&((m=r.data)==null?void 0:m.transcription)===void 0,u=lt({queryKey:["vaultLanding",a],enabled:i,queryFn:()=>t.vaultLanding(),staleTime:5*6e4,retry:!1}),f=r.isSuccess||r.isError,h=!i||u.isSuccess||u.isError;return{capability:((p=r.data)==null?void 0:p.transcription)??((y=u.data)==null?void 0:y.transcription),settled:f&&h}}function T_(t,a){const r=ke(),i=ae(v=>v.activeVaultId),{db:u}=Zt(),f=ra(),h=a==null?void 0:a.live,m=b.useMemo(()=>["notes",i,t],[i,t]),p=b.useMemo(()=>{const v=a_(t);return v.set("include_content","false"),v},[t]),{isLive:y}=Vo({queryKey:m,params:p,client:r,enabled:h}),S=ym(u,i,p,f);return lt({queryKey:m,enabled:!!r,queryFn:()=>f?gm(u,i,p,()=>r.queryNotes(p)):r.queryNotes(p),staleTime:y?Number.POSITIVE_INFINITY:1e4,refetchInterval:y?!1:3e4,refetchOnWindowFocus:!y,placeholderData:f?v=>v??S:t0,networkMode:f?"always":"online"})}const Bo=5e3;function j_(t){const a=ke(),r=ae(i=>i.activeVaultId);return lt({queryKey:["allNotesForSwitcher",r],enabled:!!a&&t,queryFn:()=>{const i=new URLSearchParams;return i.set("include_content","true"),i.set("sort","desc"),i.set("limit",String(Bo)),a.queryNotes(i)},staleTime:6e4})}function N_(){const t=ke(),a=ae(p=>p.activeVaultId),{db:r}=Zt(),i=ra(),u=b.useMemo(()=>["notesForDateViews",a],[a]),f=b.useMemo(()=>{const p=new URLSearchParams;return p.set("sort","desc"),p.set("limit",String(Bo)),p.set("include_content","false"),p},[]),{isLive:h}=Vo({queryKey:u,params:f,client:t}),m=ym(r,a,f,i);return lt({queryKey:u,enabled:!!t,queryFn:()=>i?gm(r,a,f,()=>t.queryNotes(f)):t.queryNotes(f),staleTime:h?Number.POSITIVE_INFINITY:6e4,refetchInterval:h?!1:6e4,refetchOnWindowFocus:!h,placeholderData:i?p=>p??m:void 0,networkMode:i?"always":"online"})}function A_(t){const a=ke(),r=ae(m=>m.activeVaultId),{db:i}=Zt(),u=ra(),f=b.useMemo(()=>{const m=new URLSearchParams;return m.set("sort","desc"),m.set("limit",String(Bo)),m},[]),h=ym(i,r,f,u&&t);return lt({queryKey:["notesForPathTree",r],enabled:!!a&&t,queryFn:()=>u?gm(i,r,f,()=>a.queryNotes(f)):a.queryNotes(f),staleTime:6e4,placeholderData:u?m=>m??h:void 0,networkMode:u?"always":"online"})}function CD(){const t=ke(),a=ae(r=>r.activeVaultId);return lt({queryKey:["allNotesWithLinks",a],enabled:!!t,queryFn:()=>{const r=new URLSearchParams;return r.set("include_links","true"),r.set("sort","desc"),r.set("limit",String(Bo)),t.queryNotes(r)},staleTime:6e4})}function __(){const t=ke(),a=ae(f=>f.activeVaultId),{db:r}=Zt(),i=ra(),u=E_(r,a,i);return lt({queryKey:["tags",a],enabled:!!t,queryFn:()=>i?S_(r,a,()=>t.listTags()):t.listTags(),staleTime:6e4,placeholderData:i?f=>f??u:void 0,networkMode:i?"always":"online"})}function R_(){const t=ke(),a=ae(r=>r.activeVaultId);return lt({queryKey:["tags",a,"with-schema"],enabled:!!t,queryFn:()=>t.listTags({includeSchema:!0}),staleTime:6e4})}function OD(t){const a=ke(),r=ae(i=>i.activeVaultId);return lt({queryKey:["tag",r,t],enabled:!!a&&!!t,queryFn:()=>a.getTag(t),staleTime:3e4})}function MD(){const t=ke(),a=ae(i=>i.activeVaultId),r=pt();return xn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.updateTag(i.name,i.payload)},onSuccess:(i,u)=>{r.setQueryData(["tag",a,u.name],i),r.invalidateQueries({queryKey:["tags",a]})}})}function C_(t,a){return t&&zs(t)&&!(a&&!zs(a.id))?2e3:a&&J2(a)?4e3:!1}function O_(t){const a=ke(),r=ae(m=>m.activeVaultId),{db:i}=Zt(),u=pt(),f=ra(),h=w_(i,r,t,f);return lt({queryKey:["note",r,t],enabled:!!a&&!!t,queryFn:()=>{const m=async()=>{if(t&&zs(t)){const p=i&&r?await bs(i,t,r):null;if(!p){const y=u.getQueryData(["note",r,t]);if(y)return y;throw new Error("This note is still syncing — try again in a moment.")}return a.getNote(p,{includeLinks:!0,includeAttachments:!0})}return a.getNote(t,{includeLinks:!0,includeAttachments:!0})};return f?x_(i,r,t,m):m()},refetchInterval:m=>C_(t,m.state.data),staleTime:1e4,placeholderData:f?h:void 0,networkMode:f?"always":"online"})}const M_=8e3;function Ys(){return typeof navigator<"u"&&navigator.onLine===!1}async function Ho(t,a){if(a&&Ys())return a();const r=new AbortController,i=setTimeout(()=>r.abort(new Error("offline-timeout")),M_);try{return await t(r.signal)}catch(u){if(a)return a();throw u}finally{clearTimeout(i)}}function D_(t,a){const r=new Date().toISOString();return{id:a,path:t.path,createdAt:r,updatedAt:r,tags:t.tags,metadata:t.metadata,content:t.content}}async function k_(t,a,r){const i=uA();return await El(t,{kind:"create-note",localId:i,payload:r},{vaultId:a}),D_(r,i)}async function L_(t,a,r,i,u){const f=u==null?void 0:u.updatedAt;return await El(t,{kind:"update-note",targetId:r,payload:i,...f&&{baselineUpdatedAt:f}},{vaultId:a}),{...u??{id:r,createdAt:new Date().toISOString()},...i.content!==void 0&&{content:i.content},...i.path!==void 0&&{path:i.path},...i.metadata!==void 0&&{metadata:i.metadata},updatedAt:new Date().toISOString()}}function U_(t){const a=ke(),r=ae(f=>f.activeVaultId),{db:i}=Zt(),u=pt();return xn({mutationFn:async f=>{if(!t)throw new Error("No note id");return Ho(m=>{if(!a)throw new Error("No active vault");return a.updateNote(t,f,{signal:m})},i&&r?()=>{const m=u.getQueryData(["note",r,t]);return L_(i,r,t,f,m)}:null)},onSuccess:f=>{u.setQueryData(["note",r,t],f),u.invalidateQueries({queryKey:["notes",r]}),u.invalidateQueries({queryKey:["tags",r]}),f!=null&&f.id&&f.id!==t&&u.setQueryData(["note",r,f.id],f),i&&r&&f&&fm(i,r,f)}})}function z_(){const t=ke(),a=ae(u=>u.activeVaultId),{db:r}=Zt(),i=pt();return xn({mutationFn:async u=>Ho(h=>{if(!t)throw new Error("No active vault");return t.createNote(u,{signal:h})},r&&a?()=>k_(r,a,u):null),onSuccess:u=>{i.setQueryData(["note",a,u.id],u),i.invalidateQueries({queryKey:["notes",a]}),i.invalidateQueries({queryKey:["notesForDateViews",a]}),i.invalidateQueries({queryKey:["hasUserAuthoredNote",a]}),i.invalidateQueries({queryKey:["tags",a]}),i.invalidateQueries({queryKey:["vaultInfo",a]}),r&&a&&fm(r,a,u)}})}function DD(){const t=ke();return xn({mutationFn:async a=>{if(!t)throw new Error("No active vault");return t.uploadStorageFile(a.file,{onProgress:a.onProgress,signal:a.signal})}})}function kD(){const t=ke(),a=ae(i=>i.activeVaultId),r=pt();return xn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.linkAttachment(i.noteId,{path:i.path,mimeType:i.mimeType})},onSuccess:(i,u)=>{r.invalidateQueries({queryKey:["note",a,u.noteId]})}})}function LD(){const t=ke(),a=ae(u=>u.activeVaultId),r=pt(),i=aa(u=>u.push);return xn({mutationFn:async u=>{if(!t)throw new Error("No active vault");await t.retryTranscription(u.serverId)},onMutate:async({cacheId:u})=>{const f=["note",a,u];await r.cancelQueries({queryKey:f});const h=r.getQueryData(f);return h&&r.setQueryData(f,W2(h)),{prev:h,key:f}},onError:(u,f,h)=>{h!=null&&h.prev&&h.key&&r.setQueryData(h.key,h.prev),i("Couldn't retry transcription right now.","error")},onSettled:(u,f,{cacheId:h})=>{r.invalidateQueries({queryKey:["note",a,h]})}})}function UD(){const t=ke(),a=ae(u=>u.activeVaultId),{db:r}=Zt(),i=pt();return xn({mutationFn:async u=>{if(Ys()&&r&&a)return await El(r,{kind:"delete-attachment",noteId:u.noteId,attachmentId:u.attachmentId},{vaultId:a}),u;if(!t)throw new Error("No active vault");return await t.deleteAttachment(u.noteId,u.attachmentId),u},onSuccess:u=>{i.invalidateQueries({queryKey:["note",a,u.noteId]})}})}function zD(){const t=ke(),a=ae(i=>i.activeVaultId),r=pt();return xn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.renameTag(i.oldName,i.newName)},onSuccess:()=>{r.invalidateQueries({queryKey:["tags",a]}),r.invalidateQueries({queryKey:["notes",a]}),r.invalidateQueries({queryKey:["vaultInfo",a]})}})}function VD(){const t=ke(),a=ae(i=>i.activeVaultId),r=pt();return xn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.mergeTags(i.sources,i.target)},onSuccess:()=>{r.invalidateQueries({queryKey:["tags",a]}),r.invalidateQueries({queryKey:["notes",a]}),r.invalidateQueries({queryKey:["vaultInfo",a]})}})}function BD(){const t=ke(),a=ae(u=>u.activeVaultId),{db:r}=Zt(),i=pt();return xn({mutationFn:async u=>Ho(async h=>{if(!t)throw new Error("No active vault");return await t.deleteNote(u,{signal:h}),u},r&&a?async()=>(await El(r,{kind:"delete-note",targetId:u},{vaultId:a}),u):null),onSuccess:u=>{i.removeQueries({queryKey:["note",a,u]}),i.invalidateQueries({queryKey:["notes",a]}),i.invalidateQueries({queryKey:["tags",a]}),i.invalidateQueries({queryKey:["vaultInfo",a]}),i.invalidateQueries({queryKey:["hasUserAuthoredNote",a]}),r&&a&&E0(r,a,u)}})}function V_(){b.useEffect(()=>{if(typeof window>"u")return;function t(a){if(a.key===null){ae.setState({vaults:$d(),activeVaultId:Qd()}),Rr.getState().reloadFromStorage();return}if(a.key===ho){ae.setState({activeVaultId:Qd()});return}if(a.key===Gh){ae.setState({vaults:$d()});return}if(a.key.startsWith(e_)){Rr.getState().reloadFromStorage();return}}return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[])}const HD={search:"",tags:[]};function B_(t){const a=new Map;for(const f of t)a.set(f.id,f);const r=new Map,i=new Map;for(const f of t)for(const h of f.links??[]){if(h.sourceId===h.targetId||!a.has(h.sourceId)||!a.has(h.targetId))continue;const m=`${h.sourceId}|${h.targetId}|${h.relationship}`;r.has(m)||(r.set(m,{source:h.sourceId,target:h.targetId,relationship:h.relationship}),i.set(h.sourceId,(i.get(h.sourceId)??0)+1),i.set(h.targetId,(i.get(h.targetId)??0)+1))}return{nodes:t.map(f=>{var m;const h=f.tags??[];return{id:f.id,path:f.path,title:H_(f),tags:h,topTag:h[0],degree:i.get(f.id)??0,summary:typeof((m=f.metadata)==null?void 0:m.summary)=="string"?f.metadata.summary:void 0}}),edges:[...r.values()]}}function H_(t){return t.path?(t.path.split("/").pop()??t.path).replace(/\.md$/i,""):t.id}function qD(t,a){const r=a.search.trim().toLowerCase();return!(r&&![t.path??"",t.title,t.id].join(" ").toLowerCase().includes(r)||a.tags.length>0&&!a.tags.some(u=>t.tags.includes(u)))}function $D(t){const a=new Map;for(const r of t)for(const i of r.tags)a.set(i,(a.get(i)??0)+1);return[...a.entries()].sort((r,i)=>i[1]-r[1]||r[0].localeCompare(i[0])).map(([r])=>r)}function QD(t){if(!t)return"#8a9a7a";let a=0;for(let i=0;i<t.length;i++)a=a*31+t.charCodeAt(i)&16777215;return`hsl(${a%360}, 40%, 55%)`}function q_(t){try{return new URL(t.issuer).origin}catch{return null}}function $_(t){if(typeof t!="object"||t===null)return!1;const a=t;return typeof a.name=="string"&&typeof a.url=="string"&&typeof a.version=="string"}async function Q_(t,a=fetch.bind(globalThis),r){const i=`${t.replace(/\/$/,"")}/.well-known/parachute.json`;let u;try{u=await a(i,{headers:{Accept:"application/json"},signal:r})}catch{return null}if(!u.ok)return null;let f;try{f=await u.json()}catch{return null}if(typeof f!="object"||f===null)return null;const h=f.vaults;return Array.isArray(h)?h.filter($_):null}const I_=15,K_=2;function G_(t){if(!t||t.length===0)return 0;const a=B_([...t]);let r=0;for(const i of a.nodes)i.degree>0&&r++;return r}function Y_(t,a){return t>=K_||a>=I_}function q0(){const t=ae(u=>Object.keys(u.vaults).length),a=ae(u=>u.activeVaultId),r=lt({queryKey:["allNotesWithLinks",a],queryFn:()=>{throw new Error("useMapEarned reads the query cache only")},enabled:!1}),i=b.useMemo(()=>G_(r.data),[r.data]);return Y_(t,i)}const P_="lens:pinned-tags:";function $0(t){return P_+t}function ph(t){return t.trim().replace(/^#/,"")}function vm(t){const a=new Set,r=[];for(const i of t){const u=ph(i);if(!u)continue;const f=u.toLowerCase();a.has(f)||(a.add(f),r.push(u))}return r}function db(t){try{const a=localStorage.getItem($0(t));if(!a)return[];const r=JSON.parse(a);return Array.isArray(r)?vm(r.filter(i=>typeof i=="string")):[]}catch{return[]}}function hb(t,a){try{localStorage.setItem($0(t),JSON.stringify(vm(a)))}catch{}}function F_(t){const[a,r]=b.useState(()=>t?db(t):[]);b.useEffect(()=>{r(t?db(t):[])},[t]);const i=b.useCallback(h=>{if(!t)return;const m=vm(h);hb(t,m),r(m)},[t]),u=b.useCallback(h=>{if(!t)return;const m=ph(h);m&&r(p=>{const S=p.some(v=>v.toLowerCase()===m.toLowerCase())?p.filter(v=>v.toLowerCase()!==m.toLowerCase()):[...p,m];return hb(t,S),S})},[t]),f=b.useCallback(h=>{const m=ph(h).toLowerCase();return a.some(p=>p.toLowerCase()===m)},[a]);return{pinnedTags:a,setPinnedTags:i,togglePin:u,isPinned:f}}const Q0=2500,X_="http://127.0.0.1:1939";async function wd(t,a=Q0,r=fetch.bind(globalThis)){return Z_(t,a,r)}async function Z_(t,a,r){const i=new AbortController,u=setTimeout(()=>i.abort(),a),f=(h,m)=>r(h,{...m??{},signal:i.signal});try{return await V0(t,f),t}catch{return null}finally{clearTimeout(u)}}async function I0(t,a=Q0,r=fetch.bind(globalThis),i=mE()){if(i){const f=await wd(i,a,r);if(f)return f}const u=await wd(t,a,r);if(u)return u;if(J_(t)){const f=await wd(X_,a,r);if(f)return f}return null}function J_(t){let a;try{a=new URL(t)}catch{return!1}return!(!(a.hostname==="localhost"||a.hostname==="127.0.0.1")||a.port==="1939"&&a.protocol==="http:")}function ID(){const t=ae(i=>Object.keys(i.vaults).length>0),[a,r]=b.useState(()=>({status:t?"skipped":"probing",origin:null}));return b.useEffect(()=>{if(t){r({status:"skipped",origin:null});return}let i=!1;return r({status:"probing",origin:null}),I0(window.location.origin).then(u=>{i||r(u?{status:"found",origin:u}:{status:"not-found",origin:null})}),()=>{i=!0}},[t]),a}function W_(t,a){const r=Dr(u=>t?u.byVault[t]:void 0),i=pt();b.useEffect(()=>{if(!t||!a||!r||r.state==="healthy"||r.nextProbeAt===null)return;const u=Date.now(),f=Math.max(0,r.nextProbeAt-u);let h=!1;const m=setTimeout(()=>{h||a.vaultInfo(!1).then(()=>{i.invalidateQueries({queryKey:["notes",t]}),i.invalidateQueries({queryKey:["tags",t]}),i.invalidateQueries({queryKey:["vaultInfo",t]}),i.invalidateQueries({queryKey:["note",t]})}).catch(()=>{})},f);return()=>{h=!0,clearTimeout(m)}},[t,a,r,i])}function el(t){if(t.name)return t.name;try{return new URL(t.url).host}catch{return t.url}}function bm(t){aa.getState().push(`Now in ${t}`,"success")}function eR(t,a={}){const r=ae.getState(),i=r.vaults[t];if(!i)return!1;const u=r.activeVaultId===t;return r.setActiveVault(t),(a.toast??!0)&&!u&&bm(el(i)),!0}const Ed=25,mb=40;async function tR(t){for(let a=0;a<mb;a++){const r=a*Ed,i=new URLSearchParams;i.set("exclude_tag",d0),i.set("sort","desc"),i.set("limit",String(Ed)),i.set("include_content","false"),r>0&&i.set("offset",String(r));const u=await t.queryNotes(i);if(h0(u))return!0;if(u.length<Ed)return!1}throw new Error(`first-note probe: ${mb} full pages without ending the set — offset paging appears broken`)}function nR(){const t=ke(),a=ae(r=>r.activeVaultId);return lt({queryKey:["hasUserAuthoredNote",a],enabled:!!t,queryFn:()=>tR(t),staleTime:6e4})}const aR=["list","board","calendar","gallery","table"];function rR(t){return typeof t=="string"&&aR.includes(t)}const Td={code:"invalid_query_json",message:"This view's query didn't parse — nothing is being filtered out or shown. Open the note to fix it."};function sR(t){return t.path?dm(t.path):t.id}function K0(t){const a=t.metadata??{},r=rR(a.kind)?a.kind:"list",i=[];let u={};if(typeof a.query=="string"&&a.query.trim().length>0)try{const f=JSON.parse(a.query);f&&typeof f=="object"&&!Array.isArray(f)?u=f:(u=null,i.push(Td))}catch{u=null,i.push(Td)}else a.query!==void 0&&a.query!==null&&typeof a.query!="string"&&(u=null,i.push(Td));return{noteId:t.id,path:t.path,title:sR(t),kind:r,query:u,groupBy:typeof a.group_by=="string"?a.group_by:typeof a.lane_by=="string"?a.lane_by:void 0,dateField:typeof a.date_field=="string"?a.date_field:void 0,fields:iR(a.fields),problems:i}}function iR(t){let a=t;if(typeof t=="string"){if(t.trim().length===0)return;try{a=JSON.parse(t)}catch{return}}if(!Array.isArray(a))return;const r=a.filter(i=>typeof i=="string"&&i.trim().length>0);return r.length>0?r:void 0}function lR(t,a){return(t.tags??[]).includes(a)}function uR(t){const a=t.metadata;return(a==null?void 0:a.kind)==="saved-view"}const oR="Views/All notes",cR="Views/Recent",G0="Views/Pinned",Y0="Views/Archive",fR=[oR,cR,G0,Y0],dR="Views/";function KD(t){const a=t.trim().replace(/[/\\]/g,"-");return`${dR}${a||"Untitled view"}`}const hR={pinned:G0,archived:Y0},mR={pinned:"Pinned",archived:"Archive"};function pR(t){return hR[t]}function gR(t,a){const r=t==="pinned"?a.pinned:a.archived;return{noteId:`builtin:${t}`,title:mR[t],kind:"list",query:{tag:r},problems:[]}}function yR(t,a,r){if(a&&lR(a,r.view)){const i=K0(a);if(i.query!==null)return{def:i,isPackNote:!0}}return{def:gR(t,r),isPackNote:!1}}function vR(t){const a=t.split(".");if(a.length<2)return null;const r=a[1];if(!r)return null;try{const i=r.replace(/-/g,"+").replace(/_/g,"/"),u=i+"=".repeat((4-i.length%4)%4),f=atob(u),h=JSON.parse(f),m=h==null?void 0:h.sub;return typeof m=="string"?m:null}catch{return null}}function pb(t){if(typeof t=="string"||Array.isArray(t)&&t.every(a=>typeof a=="string"))return t}function bR(t){const a=[],r={};let i;for(const[f,h]of Object.entries(t))switch(f){case"tag":r.tag=pb(h);break;case"exclude_tags":r.excludeTag=pb(h);break;case"tag_match":(h==="all"||h==="any")&&(r.tagMatch=h);break;case"metadata":h&&typeof h=="object"&&!Array.isArray(h)&&(r.metadata=h);break;case"order_by":typeof h=="string"&&(r.orderBy=h);break;case"sort":(h==="asc"||h==="desc")&&(r.sort=h);break;case"path_prefix":typeof h=="string"&&(r.pathPrefix=h);break;case"limit":typeof h=="number"&&(r.limit=h);break;case"offset":typeof h=="number"&&(r.offset=h);break;case"search":typeof h=="string"&&(i=h);break;default:a.push({code:"unsupported_query_key",message:`This view uses "${f}", which this app can't run yet; results may be broader than intended.`})}let u;try{u=Vd(r)}catch(f){const h=f instanceof Error?f.message.replace(/^buildNotesQuery: /,""):"a malformed value";a.push({code:"unsupported_query_key",message:`This view's metadata filter couldn't run (${h}) — results run without it.`});const{metadata:m,...p}=r;u=Vd(p)}return i&&u.set("search",i),{params:u,problems:a}}function GD(t){return t.addTags.length>0||t.removeExcludes.length>0||!!t.search||!!t.sort}function YD(t){var r;const a=new URLSearchParams;for(const i of t.addTags)a.append("tag",i);for(const i of t.removeExcludes)a.append("noExclude",i);return(r=t.search)!=null&&r.trim()&&a.set("search",t.search.trim()),t.sort&&a.set("sort",t.sort),a}function PD(t){return{addTags:t.getAll("tag"),removeExcludes:t.getAll("noExclude"),search:t.get("search")??void 0,sort:t.get("sort")==="asc"?"asc":t.get("sort")==="desc"?"desc":void 0}}function ll(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(a=>typeof a=="string"):[]}function xR(t,a){if(t===null)return null;const r={...t};if(a.addTags.length>0&&(r.tag=[...ll(t.tag),...a.addTags],r.tag_match="all"),a.removeExcludes.length>0){const i=ll(t.exclude_tags).filter(u=>!a.removeExcludes.includes(u));r.exclude_tags=i}return a.search&&(r.search=a.search),a.sort&&(r.sort=a.sort),r}function P0(t){return t?ll(t.tag):[]}function SR(t){return P0(t)[0]}function FD(t){if(!t)return[];const a=[];for(const r of ll(t.tag))a.push({kind:"tag",value:r,label:`#${r}`});for(const r of ll(t.exclude_tags))a.push({kind:"exclude",value:r,label:`not #${r}`});return typeof t.search=="string"&&t.search&&a.push({kind:"search",label:`"${t.search}"`}),(t.sort==="asc"||t.sort==="desc")&&a.push({kind:"sort",value:t.sort,label:`sorted by ${t.sort==="desc"?"newest":"oldest"}`}),typeof t.path_prefix=="string"&&t.path_prefix&&a.push({kind:"pathPrefix",value:t.path_prefix,label:`in ${t.path_prefix}`}),a}const XD=O_;function wR(t){const a=ke(),r=ae(h=>h.activeVaultId),i=b.useMemo(()=>{const h=new URLSearchParams;return h.set("tag",t),h.set("sort","asc"),h},[t]),u=b.useMemo(()=>["viewList",r,t],[r,t]),{isLive:f}=Vo({queryKey:u,params:i,client:a,enabled:!!t});return lt({queryKey:u,enabled:!!a&&!!t,queryFn:()=>a.queryNotes(i),staleTime:f?Number.POSITIVE_INFINITY:3e4,refetchInterval:f?!1:3e4,refetchOnWindowFocus:!f})}function ER(t,a){const r=ke(),i=ae(h=>h.activeVaultId),u=t?pR(t):null,f=lt({queryKey:["defaultViewNote",i,u],queryFn:async()=>(await r.queryNotes({path:u}))[0]??null,enabled:!!r&&!!u,staleTime:3e4,refetchOnWindowFocus:!1});return b.useMemo(()=>t?yR(t,f.data??null,a):{def:null,isPackNote:!1},[t,f.data,a])}function ZD(t,a,r){const i=ke(),u=ae(v=>v.activeVaultId),f=(r==null?void 0:r.live)??!0,h=b.useMemo(()=>t?xR(t.query,a):null,[t,a]),m=b.useMemo(()=>h?bR(h):null,[h]),p=b.useMemo(()=>["viewResults",u,t==null?void 0:t.noteId,(m==null?void 0:m.params.toString())??null],[u,t==null?void 0:t.noteId,m]),{isLive:y}=Vo({queryKey:p,params:(m==null?void 0:m.params)??new URLSearchParams,client:m?i:null,enabled:!!m&&f}),S=lt({queryKey:p,enabled:!!i&&!!m,queryFn:()=>i.queryNotes(m.params),staleTime:y?Number.POSITIVE_INFINITY:1e4,refetchInterval:y?!1:3e4,refetchOnWindowFocus:!y,placeholderData:t0});return{data:S.data,isPending:S.isPending,isError:S.isError,error:S.error,refetch:()=>void S.refetch(),problems:(m==null?void 0:m.problems)??[],queryKey:p}}function JD(){const t=ae(a=>a.activeVaultId);return b.useMemo(()=>{if(!t)return null;const a=Ls(t);return a!=null&&a.accessToken?vR(a.accessToken):null},[t])}function WD(t,a){return a&&(t!=null&&t.createdBy)&&t.createdBy===a?"update":"fork"}function F0(t){return t.pathname==="/"||t.pathname==="/today"||t.pathname.startsWith("/n/")}function xm(t){return new URLSearchParams(t.search).get("view")}function TR(t){if(t.pathname!=="/notes")return!1;const a=xm(t);return a!=="pinned"&&a!=="archived"}function jR(t){return t.pathname==="/notes"&&xm(t)==="pinned"}function NR(t){return t.pathname==="/notes"&&xm(t)==="archived"}function AR(t){return F0(t)||t.pathname==="/notes"}const X0="/",_R="/notes",vo="/map";function hn(t){return a=>a.pathname===t}const RR=["/welcome","/check-email","/add","/add-vault","/oauth/callback"];function Z0(t){return RR.some(a=>t===a||t.startsWith(`${a}/`))}const CR={id:"recent",label:"Recent",to:X0,icon:c.jsx(Tj,{}),match:F0},OR={id:"notes",label:"All notes",to:_R,icon:c.jsx(Ih,{}),match:TR},MR={id:"pinned",label:"Pinned",to:"/notes?view=pinned",icon:c.jsx(Dj,{}),match:jR},DR={id:"archive",label:"Archive",to:"/notes?view=archived",icon:c.jsx(kj,{}),match:NR},gb="/views/new",kR={id:"new-view",label:"New view",to:gb,icon:c.jsx(Kh,{}),match:hn(gb)},LR={id:"calendar",label:"Calendar",to:"/calendar",icon:c.jsx(Ux,{}),match:hn("/calendar")},UR={id:"tags",label:"Tags",to:"/tags",icon:c.jsx(jj,{}),match:hn("/tags")},zR={id:"activity",label:"Activity",to:"/activity",icon:c.jsx(_j,{}),match:hn("/activity")},VR={id:"map",label:"Map",to:vo,icon:c.jsx(Bx,{}),match:hn(vo)},BR={id:"vaults",label:"Vaults",to:"/vaults",icon:c.jsx(Rj,{}),match:hn("/vaults")},HR={id:"connect",label:"Connect AI",to:"/connect",icon:c.jsx(zx,{}),match:hn("/connect")},qR={id:"import",label:"Import notes",to:"/import",icon:c.jsx(Vx,{}),match:hn("/import")},$R={id:"export",label:"Export notes",to:"/export",icon:c.jsx(Cj,{}),match:hn("/export")},QR={id:"settings",label:"Settings",to:"/settings",icon:c.jsx(Aj,{}),match:hn("/settings")},IR={write:{label:"Write a note",to:"/new",icon:c.jsx(KR,{}),match:()=>!1}};function KR(){return c.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 place-items-center rounded-full border border-border text-[10px]",children:"✦"})}function GR({daysLeft:t}){return c.jsxs("span",{className:"shrink-0 rounded-full bg-sun-soft px-1.5 py-0.5 font-round text-[10px] font-semibold text-sun-ink",title:`Free trial · ${t} day${t===1?"":"s"} left`,children:[t,"d"]})}function YR(t){const a=[CR,OR,MR,DR],r=[LR,UR,zR];t.mapEarned&&r.push(VR);const i={id:"account",label:"Account & plan",to:"/account",icon:c.jsx(Nj,{}),match:hn("/account"),badge:t.trialDaysLeft!==null?c.jsx(GR,{daysLeft:t.trialDaysLeft}):void 0},u=[{id:"notes",label:"Your notes",items:a},{id:"views",label:"Views",items:[...t.viewItems,kR]},{id:"explore",label:"Explore",items:r},{id:"parachute",label:"Your parachute",items:[i,BR,HR,qR,$R]}];return t.setup&&t.setup.steps.length>0&&u.push({id:"setup",label:"Set up",sublabel:`${t.setup.done} of ${t.setup.total}`,items:t.setup.steps.map(f=>({id:`setup-${f}`,...IR[f]}))}),u.push({id:"foot",items:[QR]}),u}function PR(){var T;const t=ae(j=>j.getActiveVault()),a=q0(),r=nR(),{roles:i}=wl((t==null?void 0:t.id)??null),u=wR(i.view),f=t!==null&&Qs(t.clientId),h=am({enabled:f}),m=((T=f?nm(h.data):null)==null?void 0:T.plan)??null,p=typeof(m==null?void 0:m.trial_days_left)=="number"?m.trial_days_left:null,y=b.useMemo(()=>Array.isArray(u.data)?u.data.filter(j=>!fR.includes(j.path??"")&&!uR(j)).map(j=>{const _=K0(j),C=`/views/${encodeURIComponent(j.id)}`;return{id:`view-${j.id}`,label:_.title,to:C,icon:c.jsx(Gj,{kind:_.kind,hueTag:SR(_.query)}),match:hn(C)}}).sort((j,_)=>j.label.localeCompare(_.label)):[],[u.data]);if(!t)return[];const S=m0({hasUserNote:r.data===!0}),v=S.filter(j=>!j.done),x=r.data===void 0||v.length===0?null:{steps:v.map(j=>j.id),done:S.length-v.length,total:S.length};return YR({mapEarned:a,trialDaysLeft:p,setup:x,viewItems:y})}const J0=b.createContext(null);function FR({children:t}){const a=PR();return c.jsx(J0.Provider,{value:a,children:t})}function Sm(){const t=b.useContext(J0);if(t===null)throw new Error("useNavBands must render under <NavBandsProvider> — the nav model derives once, in the app shell (app#110)");return t}const XR=Ia(t=>({shown:!1,setShown(a){t({shown:a})}}));function ZR(){const t=ae(u=>u.activeVaultId!==null),a=q0(),r=XR(u=>u.shown),{pathname:i}=Ge();return!t||a||i===vo||r?null:c.jsx(_e,{to:vo,"aria-label":"Open the relational map",title:"Your map",className:"focus-ring fixed right-5 bottom-20 z-20 grid h-12 w-12 place-items-center rounded-full border border-border bg-card text-accent shadow-lg hover:border-accent lg:right-6 lg:bottom-6",children:c.jsx(Bx,{width:22,height:22})})}const tl=Ia(t=>({open:!1,setOpen(a){t({open:a})},toggle(){t(a=>({open:!a.open}))}}));function JR(){const t=ae(u=>u.activeVaultId!==null),a=tl(u=>u.setOpen),r=Ge();if(!t)return null;const i=AR(r);return c.jsx("nav",{"aria-label":"Primary",className:"fixed inset-x-0 bottom-0 z-20 border-t border-border bg-bg/95 backdrop-blur lg:hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:c.jsxs("ul",{className:"mx-auto flex max-w-(--w-page) items-stretch justify-around px-2",children:[c.jsx(WR,{to:X0,label:"Notes",active:i,icon:c.jsx(Ih,{})}),c.jsx(tC,{}),c.jsx(eC,{label:"Search",icon:c.jsx(co,{}),onClick:()=>a(!0)})]})})}function WR({to:t,label:a,icon:r,active:i}){return c.jsx("li",{className:"flex-1",children:c.jsxs(_e,{to:t,"aria-label":a,"aria-current":i?"page":void 0,className:`focus-ring flex h-14 flex-col items-center justify-center gap-0.5 text-2xs ${i?"text-accent":"text-fg-muted hover:text-accent"}`,children:[c.jsx("span",{"aria-hidden":"true",children:r}),c.jsx("span",{children:a})]})})}function eC({label:t,icon:a,onClick:r}){return c.jsx("li",{className:"flex-1",children:c.jsxs("button",{type:"button",onClick:r,"aria-label":t,className:"focus-ring flex h-14 w-full flex-col items-center justify-center gap-0.5 text-2xs text-fg-muted hover:text-accent",children:[c.jsx("span",{"aria-hidden":"true",children:a}),c.jsx("span",{children:t})]})})}function tC(){return c.jsx("li",{className:"flex flex-1 items-center justify-center",children:c.jsx(_e,{to:"/new","aria-label":"New note",className:"focus-ring -mt-4 grid h-[3.25rem] w-[3.25rem] place-items-center rounded-full bg-accent text-(--color-on-accent) shadow-lg transition-colors hover:bg-accent-hover",children:c.jsx(Kh,{width:26,height:26,strokeWidth:2})})})}function W0({title:t,message:a,retry:r,retryLabel:i="Try again",action:u,className:f=""}){return c.jsxs("div",{className:`rounded-lg border border-(--color-danger-border) bg-(--color-danger-soft) p-6 ${f}`.trim(),children:[c.jsx("p",{className:"mb-2 font-medium text-(--color-danger)",children:t}),a?c.jsx("p",{className:"mb-4 text-sm text-fg-muted",children:a}):null,r||u?c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r?c.jsx("button",{type:"button",onClick:r,className:"btn btn-secondary btn-touch",children:i}):null,u]}):null]})}class eS extends b.Component{constructor(){super(...arguments);fe(this,"state",{error:null})}static getDerivedStateFromError(r){return{error:r}}componentDidCatch(r,i){console.error("ErrorBoundary caught a render error:",r,i.componentStack)}render(){return this.state.error?this.props.fallback(this.state.error):this.props.children}}function nC({error:t}){return c.jsx("div",{className:"page",children:c.jsx(W0,{title:"Something went wrong",message:c.jsxs(c.Fragment,{children:["This page hit an unexpected error. You can head back to your notes.",c.jsxs("details",{className:"mt-3",children:[c.jsx("summary",{className:"cursor-pointer text-xs text-fg-dim hover:text-fg-muted",children:"Technical detail"}),c.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-xs text-fg-dim",children:t.message})]})]}),action:c.jsx(_e,{to:"/notes",className:"btn btn-secondary btn-touch",children:"Back to notes"})})})}function Fe({children:t}){const a=Ge();return c.jsx(eS,{fallback:r=>c.jsx(nC,{error:r}),children:t},a.key)}function aC({error:t}){return c.jsxs("div",{className:"mx-auto flex min-h-dvh max-w-md flex-col items-center justify-center gap-3 px-6 text-center",children:[c.jsx("p",{className:"font-serif text-xl text-fg",children:"Something went wrong"}),c.jsx("p",{className:"text-sm text-fg-muted",children:"Parachute hit an unexpected error and couldn't recover on its own. Reloading usually fixes it."}),c.jsxs("details",{className:"w-full text-left",children:[c.jsx("summary",{className:"cursor-pointer text-xs text-fg-dim hover:text-fg-muted",children:"Technical detail"}),c.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-xs text-fg-dim",children:t.message})]}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"btn btn-primary btn-touch",children:"Reload"})]})}function rC({children:t}){return c.jsx(eS,{fallback:a=>c.jsx(aC,{error:a}),children:t})}const bo=Ia(t=>({on:!1,setOn(a){t({on:a})},toggle(){t(a=>({on:!a.on}))}})),sC=/^\/n\/[^/]+(\/edit)?$/;function tS(t){return sC.test(t)}function iC(){const t=Ge(),a=bo(i=>i.setOn),r=bo(i=>i.toggle);return b.useEffect(()=>{a(!1)},[t.pathname]),b.useEffect(()=>{const i=u=>{(u.metaKey||u.ctrlKey)&&(u.altKey||u.shiftKey||u.key==="."&&tS(t.pathname)&&(u.preventDefault(),r()))};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[t.pathname,r]),null}function lC(){const t=bo(a=>a.setOn);return c.jsx("button",{type:"button",onClick:()=>t(!1),"aria-label":"Exit focus mode",title:"Exit focus (⌘.)",className:"glass-panel enter-fade focus-ring fixed top-4 right-4 z-30 grid h-10 w-10 place-items-center rounded-full border border-border text-fg-muted shadow-lift hover:text-accent",style:{marginTop:"env(safe-area-inset-top)"},children:c.jsx(Bj,{width:18,height:18})})}function uC(){const t=aa(u=>u.push),[a,r]=b.useState(!1);return{copied:a,copy:async u=>{try{await navigator.clipboard.writeText(u),r(!0),t("Copied to clipboard.","success"),window.setTimeout(()=>r(!1),2e3)}catch{t("Couldn't copy — select and copy manually.","error")}}}}function oC({value:t,label:a,className:r}){const{copied:i,copy:u}=uC();return c.jsxs("div",{className:`flex items-stretch gap-2 ${r??""}`,children:[c.jsx("code",{className:"min-w-0 flex-1 overflow-x-auto rounded-md border border-border bg-bg-soft px-3 py-2 font-mono text-sm text-fg",children:t}),c.jsx("button",{type:"button",onClick:()=>u(t),className:"btn btn-secondary btn-touch shrink-0","aria-label":`Copy ${a}`,children:i?"Copied":"Copy"})]})}function cC(t=navigator,a=window){var r;return(r=a.matchMedia)!=null&&r.call(a,"(display-mode: standalone)").matches?!0:t.standalone===!0}function fC(t=navigator.userAgent,a=typeof document<"u"&&navigator.maxTouchPoints>1){return/iPad|iPhone|iPod/.test(t)?!0:/Macintosh/.test(t)&&a}let xs=null,nS=!1;const gh=new Set;function wm(){for(const t of gh)t()}function dC(t){t.preventDefault(),xs=t,wm()}function hC(){xs=null,nS=!0,wm()}let yb=!1;function mC(){yb||typeof window>"u"||(yb=!0,window.addEventListener("beforeinstallprompt",dC),window.addEventListener("appinstalled",hC))}mC();function vb(t){return gh.add(t),()=>{gh.delete(t)}}function pC(){const t=b.useSyncExternalStore(vb,()=>xs,()=>null),a=b.useSyncExternalStore(vb,()=>nS,()=>!1),[r,i]=b.useState({standalone:!0,ios:!1});b.useEffect(()=>{i({standalone:cC(),ios:fC()})},[]);const f=r.standalone||a?"installed":t!==null||r.ios?"available":"unsupported",h=b.useCallback(async()=>{const m=xs;if(!m)return"unavailable";try{return await m.prompt(),(await m.userChoice).outcome}catch{return"unavailable"}finally{xs===m&&(xs=null,wm())}},[]);return{state:f,isIOSDevice:r.ios,promptInstall:h}}function gC(){const{state:t,isIOSDevice:a,promptInstall:r}=pC(),i=ae(m=>{var p;return((p=m.getActiveVault())==null?void 0:p.url)??null}),[u,f]=b.useState(!1);if(t!=="available")return null;const h=async()=>{await r()==="unavailable"&&a&&f(!0)};return c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",onClick:h,className:"min-h-11 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-fg-muted hover:text-accent focus-visible:outline-2 focus-visible:outline-accent",children:"Install app"}),u?c.jsxs("dialog",{open:!0,"aria-labelledby":"ios-install-title",className:"fixed inset-0 z-50 m-auto max-w-sm rounded-2xl border border-border bg-card p-6 text-fg shadow-lift",children:[c.jsx("h2",{id:"ios-install-title",className:"mb-3 font-serif text-xl",children:"Add Parachute to your home screen"}),c.jsxs("ol",{className:"mb-5 list-decimal space-y-2 pl-5 text-sm text-fg-muted",children:[c.jsx("li",{children:"Tap the Share icon in Safari's toolbar."}),c.jsxs("li",{children:["Choose ",c.jsx("strong",{className:"text-fg",children:"Add to Home Screen"}),"."]}),c.jsx("li",{children:"Tap Add. Parachute will open standalone from your home screen."})]}),i?c.jsxs("div",{className:"mb-5 rounded-md border border-border bg-bg-soft/60 p-3",children:[c.jsx("p",{className:"mb-2 text-sm text-fg-muted",children:"The installed app may ask for your vault address — here it is, ready to paste:"}),c.jsx(oC,{value:i,label:"vault address"})]}):null,c.jsx("div",{className:"flex justify-end",children:c.jsx("button",{type:"button",onClick:()=>f(!1),className:"min-h-11 rounded-lg bg-accent px-3 py-1.5 text-sm font-medium text-(--color-on-accent) hover:bg-accent-hover",children:"Got it"})})]}):null]})}const yh="notes:textSize",Cr=["default","larger","largest"];function yC(t){return t==="default"||t==="larger"||t==="largest"}function Ss(){try{const t=localStorage.getItem(yh);return yC(t)?t:"default"}catch{return"default"}}function vC(t){try{t==="default"?localStorage.removeItem(yh):localStorage.setItem(yh,t)}catch{}}function aS(t,a=document.documentElement){t==="default"?a.removeAttribute("data-text-size"):a.setAttribute("data-text-size",t)}function jd(t){return t==="larger"?"Larger":t==="largest"?"Largest":"Default"}function bC(t){const a=Cr.indexOf(t);return Cr[(a+1)%Cr.length]??"default"}function xC(t){const a=Cr.indexOf(t),r=Cr.length;return Cr[(a-1+r)%r]??"default"}const vh="notes:text-size-change";function io(t){vC(t),aS(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(vh,{detail:t}))}function SC(){return b.useEffect(()=>{const t=a=>{if((a.metaKey||a.ctrlKey)&&!(a.altKey||a.shiftKey)){if(a.key==="="||a.key==="+"){a.preventDefault(),io(bC(Ss()));return}if(a.key==="-"||a.key==="_"){a.preventDefault(),io(xC(Ss()));return}if(a.key==="0"){a.preventDefault(),io("default");return}}};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[]),null}const Nd=8;function wC(){const[t,a]=b.useState(()=>Ss()),[r,i]=b.useState(!1),u=b.useRef(null),f=b.useRef(null),[h,m]=b.useState("down"),[p,y]=b.useState(null),S=b.useCallback(v=>{a(v),io(v)},[]);return b.useEffect(()=>{const v=T=>{T.key==="notes:textSize"&&a(Ss())},x=T=>{const j=T.detail;a(j||Ss())};return window.addEventListener("storage",v),window.addEventListener(vh,x),()=>{window.removeEventListener("storage",v),window.removeEventListener(vh,x)}},[]),b.useEffect(()=>{if(!r)return;const v=x=>{u.current&&(u.current.contains(x.target)||i(!1))};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[r]),b.useLayoutEffect(()=>{if(!r)return;const v=()=>{const x=u.current,T=f.current;if(!x||!T)return;const j=x.getBoundingClientRect(),_=T.getBoundingClientRect(),C=_.height||T.offsetHeight,O=_.width||T.offsetWidth,B=window.innerHeight-j.bottom;m(B<C+Nd?"up":"down");const H=j.right-O,k=Nd,Y=Math.max(k,window.innerWidth-O-Nd),Q=Math.min(Math.max(H,k),Y);y(Q-j.left)};return v(),window.addEventListener("resize",v),window.addEventListener("scroll",v,!0),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0)}},[r]),c.jsxs("div",{ref:u,className:"relative",children:[c.jsx("button",{type:"button","aria-label":`Text size: ${jd(t)}. Click to change.`,"aria-expanded":r,title:`Text size: ${jd(t)}`,onClick:()=>i(v=>!v),className:"inline-flex min-h-11 min-w-11 items-center justify-center rounded-lg border border-border bg-card px-2 py-1.5 text-sm text-fg-muted hover:text-accent focus-visible:outline-2 focus-visible:outline-accent",children:c.jsxs("span",{"aria-hidden":"true",className:"font-serif",children:["A",c.jsx("span",{className:"text-xs",children:"a"})]})}),r?c.jsx("div",{role:"dialog",ref:f,"aria-label":"Text size","data-placement":h,className:`enter-rise absolute right-0 z-30 w-40 rounded-xl border border-border bg-card p-2 text-sm shadow-lift ${h==="up"?"bottom-full mb-2":"mt-2"}`,style:p!=null?{left:`${p}px`,right:"auto"}:void 0,children:c.jsx("ul",{className:"flex flex-col gap-0.5",children:Cr.map(v=>{const x=v===t;return c.jsx("li",{children:c.jsxs("button",{type:"button",onClick:()=>{S(v),i(!1)},"aria-pressed":x,className:`flex w-full items-center justify-between rounded px-2 py-1.5 text-left hover:bg-bg/60 ${x?"text-accent":"text-fg-muted"}`,children:[c.jsx("span",{children:jd(v)}),x?c.jsx("span",{"aria-hidden":"true",className:"text-xs",children:"✓"}):null]})},v)})})}):null]})}const bh="lens:theme",Ad=["system","light","dark"];function EC(t){return t==="system"||t==="light"||t==="dark"}function TC(){try{const t=localStorage.getItem(bh);return EC(t)?t:"system"}catch{return"system"}}function jC(t){try{t==="system"?localStorage.removeItem(bh):localStorage.setItem(bh,t)}catch{}}function bb(t,a=document.documentElement){t==="system"?a.removeAttribute("data-theme"):a.setAttribute("data-theme",t)}function NC(t){const a=Ad.indexOf(t);return Ad[(a+1)%Ad.length]}function AC(t){return t==="light"?"Light":t==="dark"?"Dark":"System"}function xh(){const[t,a]=b.useState("system");b.useEffect(()=>{const u=TC();a(u),bb(u)},[]);const r=()=>{const u=NC(t);a(u),jC(u),bb(u)},i=AC(t);return c.jsx("button",{type:"button",onClick:r,"aria-label":`Theme: ${i}. Click to cycle.`,title:`Theme: ${i}`,className:"inline-flex min-h-11 min-w-11 items-center justify-center rounded-lg border border-border bg-card px-2 py-1.5 text-sm text-fg-muted hover:text-accent focus-visible:outline-2 focus-visible:outline-accent",children:c.jsx(_C,{theme:t})})}function _C({theme:t}){return t==="light"?c.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:[c.jsx("circle",{cx:"10",cy:"10",r:"3.5"}),c.jsx("path",{d:"M10 2v2M10 16v2M2 10h2M16 10h2M4.2 4.2l1.4 1.4M14.4 14.4l1.4 1.4M4.2 15.8l1.4-1.4M14.4 5.6l1.4-1.4"})]}):t==="dark"?c.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"currentColor",children:c.jsx("path",{d:"M15.5 11.8a6 6 0 0 1-7.3-7.3 6 6 0 1 0 7.3 7.3z"})}):c.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"none",stroke:"currentColor",strokeWidth:"1.6",children:[c.jsx("circle",{cx:"10",cy:"10",r:"6"}),c.jsx("path",{d:"M10 4v12",fill:"currentColor",stroke:"none"}),c.jsx("path",{d:"M10 4a6 6 0 0 1 0 12",fill:"currentColor",stroke:"none"})]})}function rS(){const t=typeof window<"u"&&window.location?window.location.origin:"(unknown origin)";return c.jsxs("div",{role:"alert","aria-live":"assertive","data-testid":"insecure-context-banner",className:"rounded-md border border-amber-400/40 bg-amber-400/10 px-3 py-3 text-sm text-amber-100",children:[c.jsxs("p",{className:"mb-2 flex items-center gap-2 font-medium text-amber-100",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠"}),"Insecure context — OAuth unavailable"]}),c.jsxs("p",{className:"mb-2 text-xs text-amber-100/90",children:["Your hub URL must be served over HTTPS or accessed at ",c.jsx("code",{children:"http://localhost"}),". This page is at ",c.jsx("code",{className:"font-mono",children:t}),", which the browser treats as insecure for Web Crypto. To connect:"]}),c.jsxs("ul",{className:"ml-4 list-disc space-y-1 text-xs text-amber-100/90",children:[c.jsxs("li",{children:["Use ",c.jsx("code",{children:"http://localhost"})," or ",c.jsx("code",{children:"http://127.0.0.1"})," directly (replace your hub URL with the localhost form), ",c.jsx("strong",{children:"or"})]}),c.jsx("li",{children:"Serve your hub over HTTPS via Tailscale Serve, Cloudflare Tunnel, or a reverse proxy."})]})]})}const RC={vault_taken:"That name's already taken — try another.",vault_limit_reached:"You've reached your plan's vault limit. Upgrade your plan, or free one up first.",invalid_name:"Use 2–63 characters: lowercase letters, numbers, and hyphens.",reserved:"That name is reserved — pick a different one.",not_owner:"That vault isn't linked to this account.",not_found:"That vault couldn't be found.",invalid_scope:"Couldn't open that vault — try again.",not_implemented:"That isn't available yet."},CC="Something went wrong. Try again.";function OC(t){return/^[a-z][a-z0-9_]*$/.test(t)}function MC(t,a=CC){if(!(t instanceof Error))return a;const r=t.message.trim();return r?OC(r)?RC[r]??a:r:a}function mr(t){try{return kh(t)}catch{return t.replace(/\/$/,"")}}function DC(t,a,r,i,u){const f=new Set(r.map(x=>mr(x.url))),h=new Set(t.map(x=>mr(x.url))),m=new Set(t.filter(x=>Qs(x.clientId)).map(x=>x.name)),p=[...t].sort((x,T)=>el(x).localeCompare(el(T))).map(x=>({kind:"device",id:x.id,label:el(x),isActive:x.id===a,hubKnown:f.has(mr(x.url)),vault:x})),y=(u??[]).filter(x=>!(x.url!==void 0&&h.has(mr(x.url)))&&!m.has(x.name)).sort((x,T)=>x.name.localeCompare(T.name)).map(x=>({kind:"account",name:x.name,url:x.url})),S=new Set(y.filter(x=>x.url!==void 0).map(x=>mr(x.url))),v=i===null?[]:r.filter(x=>!h.has(mr(x.url))&&!S.has(mr(x.url))).sort((x,T)=>x.name.localeCompare(T.name)).map(x=>({kind:"hub",name:x.name,url:x.url,hubOrigin:i}));return[...p,...y,...v]}function _d({label:t,here:a}){const r=(t.trim()[0]??"?").toUpperCase();return c.jsx("span",{"aria-hidden":!0,className:`grid h-8 w-8 shrink-0 place-items-center rounded-lg text-sm font-semibold ${a?"bg-grass-soft text-grass-ink":"bg-bg-soft text-fg-muted"}`,children:r})}function Rd({tone:t,children:a}){return c.jsx("span",{"aria-hidden":!0,className:`grid h-8 w-8 shrink-0 place-items-center rounded-full text-sm ${t==="sun"?"bg-sun-soft text-sun-ink":"bg-bg-soft"}`,style:t==="sky"?{color:"var(--color-sky)"}:t==="accent"?{color:"var(--color-accent)"}:void 0,children:a})}function xb({layout:t,onAfterAction:a}){const r=ae(E=>E.vaults),i=ae(E=>E.activeVaultId),u=i?r[i]??null:null,[f,h]=b.useState(null),[m,p]=b.useState(!1),[y,S]=b.useState(null),[v,x]=b.useState(null),[T,j]=b.useState(null),[_,C]=b.useState(null),[O,B]=b.useState(!1),H=b.useMemo(()=>u?q_(u):null,[u]),k=am(),Y=nm(k.data),Q=Ft(E=>E.identityEpoch),G=lt({queryKey:["account","vaults",Q],queryFn:async()=>{try{return(await Zx()).vaults}catch{return null}},staleTime:6e4}),F=G.data??null;b.useEffect(()=>{if(!H)return;const E=new AbortController;return p(!0),Q_(H,fetch.bind(globalThis),E.signal).then(q=>{E.signal.aborted||(h(q),p(!1))}),()=>{E.abort(),p(!1)}},[H]);const Z=b.useMemo(()=>DC(Object.values(r),i,f??[],H,F),[r,i,f,H,F]),le=Z.filter(E=>E.kind==="device"),de=Z.filter(E=>E.kind==="account"),ye=Z.filter(E=>E.kind==="hub"),we=(Y==null?void 0:Y.plan)??null,re=we!==null&&typeof we.vault_limit=="number"&&typeof we.vaults_used=="number"&&we.vaults_used>=we.vault_limit,ee=typeof(we==null?void 0:we.trial_days_left)=="number"?we.trial_days_left:null,M=b.useCallback(E=>{E.isActive||eR(E.id,{toast:!0}),a()},[a]),P=b.useCallback(async E=>{if(!T){j(E.name),C(null);try{await Do(E.name),bm(E.name),a()}catch(q){C(MC(q,"Couldn't open that vault."))}finally{j(null)}}},[T,a]),ne=b.useCallback(async E=>{S(E.name),x(null),B(!1);try{const{authorizeUrl:q}=await pm(E.hubOrigin,void 0,void 0,{params:{vault:E.name}});window.location.assign(q)}catch(q){S(null),q instanceof No?B(!0):x(q.message)}},[]),oe=m||G.isPending,me=c.jsxs(c.Fragment,{children:[le.length>0?c.jsxs("div",{className:"border-b border-border-light",children:[c.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"On this device"}),c.jsx("ul",{className:"pb-2",children:le.map(E=>c.jsx("li",{children:c.jsxs("button",{type:"button",onClick:()=>M(E),className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 text-left hover:bg-bg-soft",children:[c.jsx(_d,{label:E.label,here:!0}),c.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-fg",children:E.label}),E.isActive?c.jsx("span",{className:"shrink-0 text-2xs font-medium text-grass-ink",children:"✓ current"}):null]})},E.id))})]}):null,de.length>0?c.jsxs("div",{className:"border-b border-border-light",children:[c.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"In your account"}),c.jsx("ul",{className:"pb-2",children:de.map(E=>c.jsx("li",{children:c.jsxs("div",{className:"flex w-full items-center gap-2.5 px-3 py-1.5",children:[c.jsx(_d,{label:E.name,here:!1}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-fg-muted",children:E.name}),c.jsx("button",{type:"button",onClick:()=>P(E),disabled:T===E.name,className:"focus-ring shrink-0 rounded-full border border-accent/40 px-2.5 py-1 text-xs font-medium text-accent hover:bg-accent/10 disabled:opacity-60",children:T===E.name?"Opening…":"Open →"})]})},E.name))})]}):null,ye.length>0?c.jsxs("div",{className:"border-b border-border-light",children:[c.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"From your hub"}),c.jsx("ul",{className:"pb-2",children:ye.map(E=>c.jsx("li",{children:c.jsxs("div",{className:"flex w-full items-center gap-2.5 px-3 py-1.5",children:[c.jsx(_d,{label:E.name,here:!1}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-fg-muted",children:E.name}),c.jsx("button",{type:"button",onClick:()=>ne(E),disabled:y===E.name,className:"focus-ring shrink-0 rounded-full border border-accent/40 px-2.5 py-1 text-xs font-medium text-accent hover:bg-accent/10 disabled:opacity-60",children:y===E.name?"Connecting…":"Connect"})]})},E.url))})]}):null,O?c.jsx("div",{className:"border-b border-border-light px-3 py-2",children:c.jsx(rS,{})}):null,v||_?c.jsx("div",{className:"border-b border-border-light px-3 py-2 text-xs text-(--color-danger)",children:v??_}):null,c.jsxs("div",{className:"border-b border-border-light py-2",children:[re&&we?c.jsxs(_e,{to:"/account",onClick:a,className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 hover:bg-bg-soft",children:[c.jsx(Rd,{tone:"sun",children:"↑"}),c.jsxs("span",{className:"min-w-0 flex-1 leading-snug text-fg-muted",children:[we.vaults_used," of ",we.vault_limit," vaults on your plan"]}),c.jsx("span",{className:"shrink-0 text-sm font-semibold text-accent",children:"Upgrade →"})]}):c.jsxs(_e,{to:"/add-vault/create",onClick:a,className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 hover:bg-bg-soft",children:[c.jsx(Rd,{tone:"accent",children:"+"}),c.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-accent",children:"Create a vault"})]}),c.jsxs(_e,{to:"/add",onClick:a,className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 hover:bg-bg-soft",children:[c.jsx(Rd,{tone:"sky",children:"⌂"}),c.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold",style:{color:"var(--color-sky)"},children:"Connect your own"})]})]}),c.jsxs("div",{className:"px-3 py-2",children:[ee!==null?c.jsxs(_e,{to:"/account",onClick:a,className:"focus-ring mb-1 block text-xs text-sun-ink hover:underline",children:["Free trial ·"," ",ee===0?"ends today":`${ee} day${ee===1?"":"s"} left`]}):null,c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx(_e,{to:"/vaults",onClick:a,className:"focus-ring text-xs text-fg-muted hover:text-accent",children:"Manage vaults →"}),oe?c.jsx("span",{className:"text-[10px] text-fg-dim",children:"Looking for more vaults…"}):null]})]})]});return t==="inline"?c.jsx("section",{"aria-label":"Vaults",className:"text-sm",children:me}):c.jsx("div",{role:"dialog","aria-label":"Vaults",className:"enter-rise absolute left-0 z-30 mt-2 w-72 overflow-hidden rounded-2xl border border-border bg-card text-sm shadow-lift",children:me})}function Em({variant:t="header",onOpenNavSheet:a,onAction:r,collapsed:i=!1}){const u=ae(x=>x.vaults),f=ae(x=>x.activeVaultId),h=f?u[f]??null:null,[m,p]=b.useState(!1),y=b.useRef(null);b.useEffect(()=>{if(!m)return;const x=j=>{y.current&&(y.current.contains(j.target)||p(!1))},T=j=>{j.key==="Escape"&&p(!1)};return document.addEventListener("mousedown",x),document.addEventListener("keydown",T),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",T)}},[m]);const S=b.useCallback(()=>p(!1),[]),v=h?el(h):"Choose vault";if(t==="sheet")return c.jsx(xb,{layout:"inline",onAfterAction:r??(()=>{})});if(t==="rail"){const x=(v.trim()[0]??"?").toUpperCase();return c.jsxs("div",{ref:y,className:"relative",children:[c.jsxs("button",{type:"button","aria-label":`Active vault: ${v}`,"aria-expanded":m,"aria-haspopup":"dialog",onClick:()=>p(T=>!T),title:v,className:`focus-ring flex w-full items-center rounded-xl border border-border bg-card text-left shadow-sm hover:border-accent/50 ${i?"justify-center px-0 py-2":"gap-2.5 px-2.5 py-2"}`,children:[c.jsx("span",{"aria-hidden":!0,className:"grid h-7 w-7 shrink-0 place-items-center rounded-lg bg-grass-soft font-round text-sm font-semibold text-grass-ink",children:x}),i?null:c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 flex-1 truncate font-round font-semibold text-fg",children:v}),c.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-xs text-fg-dim",children:"▾"})]})]}),m?c.jsx(xb,{layout:"popover",onAfterAction:S}):null]})}return c.jsxs("button",{type:"button","aria-label":`Active vault: ${v}`,"aria-haspopup":"dialog",onClick:a,title:v,className:"flex min-w-0 max-w-[12rem] items-center gap-1.5 rounded-lg border border-border bg-card px-2.5 py-1.5 text-sm text-fg hover:border-accent/50",children:[c.jsx("span",{"aria-hidden":!0,className:"inline-block h-2 w-2 shrink-0 rounded-full bg-accent"}),c.jsx("span",{className:"min-w-0 truncate",children:v}),c.jsx("span",{"aria-hidden":!0,className:"ml-1 shrink-0 text-xs text-fg-dim",children:"▾"})]})}function kC({open:t,onClose:a,initialFocus:r}){return t?c.jsx(LC,{onClose:a,initialFocus:r}):null}function LC({onClose:t,initialFocus:a}){const r=ae(x=>Object.keys(x.vaults).length>0),i=Sm(),u=Ge(),f=b.useRef(null),h=b.useRef(null),m=b.useRef(null),p=i.filter(x=>x.id!=="foot"),y=i.find(x=>x.id==="foot");b.useEffect(()=>{var j;const x=document.activeElement,T=a==="switcher"?((j=h.current)==null?void 0:j.querySelector("button, a"))??f.current:f.current;return T==null||T.focus(),()=>{var _;return(_=x==null?void 0:x.focus)==null?void 0:_.call(x)}},[a]),b.useEffect(()=>{const x=T=>{if(T.key==="Escape"){t();return}if(T.key!=="Tab"||!f.current)return;const j=Array.from(f.current.querySelectorAll('a[href], button:not([disabled]), input, select, textarea, [tabindex]:not([tabindex="-1"])'));if(j.length===0)return;const _=j[0],C=j[j.length-1],O=document.activeElement;if(!(O instanceof HTMLElement)||!j.includes(O)){T.preventDefault(),(T.shiftKey?C:_).focus();return}T.shiftKey&&document.activeElement===_?(T.preventDefault(),C.focus()):!T.shiftKey&&document.activeElement===C&&(T.preventDefault(),_.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t]),b.useEffect(()=>{const x=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=x}},[]);const S=x=>{m.current=f.current&&f.current.scrollTop<=0?x.touches[0].clientY:null},v=x=>{m.current!==null&&x.touches[0].clientY-m.current>64&&(m.current=null,t())};return c.jsxs("div",{className:"fixed inset-0 z-40 lg:hidden",children:[c.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"enter-fade absolute inset-0 h-full w-full cursor-default bg-black/40"}),c.jsxs("div",{role:"dialog",ref:f,"aria-modal":"true","aria-label":"Menu",tabIndex:-1,onTouchStart:S,onTouchMove:v,className:"enter-rise glass-panel absolute inset-x-0 bottom-0 max-h-[85dvh] overflow-y-auto rounded-t-[var(--radius-2xl)] shadow-lift",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[c.jsx("div",{"aria-hidden":!0,className:"sticky top-0 z-10 flex justify-center pt-2.5 pb-1.5",children:c.jsx("span",{className:"h-1 w-10 rounded-full bg-border"})}),r?c.jsx("div",{ref:h,"data-nav-band":"switcher",className:"border-b border-border-light",children:c.jsx(Em,{variant:"sheet",onAction:t})}):null,p.length>0?c.jsx("nav",{"aria-label":"Primary",className:"px-3 pb-1",children:p.map(x=>c.jsx(UC,{band:x},x.id))}):null,c.jsxs("div",{"data-nav-band":"foot",className:"border-t border-border px-3 py-3",children:[y==null?void 0:y.items.map(x=>c.jsx(sS,{item:x,loc:u},x.id)),c.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 px-3",children:[c.jsx(gC,{}),c.jsx(wC,{}),c.jsx(xh,{})]})]})]})]})}function UC({band:t}){const a=Ge();return c.jsxs("div",{"data-nav-band":t.id,children:[t.label?c.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[c.jsx("span",{children:t.label}),t.sublabel?c.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.items.map(r=>c.jsx(sS,{item:r,loc:a},r.id))]})}function sS({item:t,loc:a}){const r=t.match(a);return c.jsxs(_e,{to:t.to,"data-nav-item":t.id,"aria-current":r?"page":void 0,className:`focus-ring flex items-center gap-3 rounded-lg px-3 py-2.5 font-round text-base transition-colors duration-(--dur-quick) ease-out ${r?"bg-grass-soft font-semibold text-grass-ink":"font-medium text-fg-muted hover:bg-bg hover:text-fg"}`,children:[c.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})}const Sb={rows:[],byKind:{},total:0,pendingCount:0,needsHumanCount:0,authHalt:null};function iS(t,a,r=2e3){const[i,u]=b.useState(Sb),f=b.useRef(!1);return b.useEffect(()=>{if(f.current=!1,!t||!a){u(Sb);return}let h=null;const m=async()=>{try{const[p,y]=await Promise.all([U0(t,a),Ks(t,L0)]);if(f.current)return;const S={};let v=0,x=0;for(const j of p){const _=j.mutation.kind;S[_]=(S[_]??0)+1,j.status==="needs-human"?x+=1:v+=1}const T=y&&y.vaultId===a?y:null;u({rows:p,byKind:S,total:p.length,pendingCount:v,needsHumanCount:x,authHalt:T})}catch{}};return m(),h=setInterval(m,r),()=>{f.current=!0,h&&clearInterval(h)}},[t,a,r]),i}const zC=[["y",365*24*60*60*1e3],["mo",720*60*60*1e3],["w",10080*60*1e3],["d",1440*60*1e3],["h",3600*1e3],["m",60*1e3]];function Tm(t,a=new Date){if(!t)return"";const i=new Date(t).getTime();if(Number.isNaN(i))return"";const u=a.getTime()-i,f=Math.abs(u);for(const[h,m]of zC)if(f>=m){const p=Math.floor(f/m);return u>=0?`${p}${h} ago`:`in ${p}${h}`}return"just now"}const VC={"create-note":"new notes","update-note":"note edits","delete-note":"deletions","upload-attachment":"uploads","link-attachment":"attachment links","delete-attachment":"attachment removals"},BC=.8;function HC({onDismiss:t}){const{db:a,isOnline:r,isDraining:i,lastSyncedAt:u}=Zt(),f=ae(O=>O.activeVaultId),h=aa(O=>O.push),m=iS(a,f),[p,y]=b.useState(null),S=Dr(O=>f?O.byVault[f]??null:null),[,v]=b.useState(0);b.useEffect(()=>{const O=setInterval(()=>v(B=>B+1),15e3);return()=>clearInterval(O)},[]),b.useEffect(()=>{let O=!1;return w2().then(B=>{O||B.supported&&typeof B.usage=="number"&&typeof B.quota=="number"&&y({usage:B.usage,quota:B.quota})}),()=>{O=!0}},[]);const x=(S==null?void 0:S.state)==="down",T=m.authHalt?"Reconnect needed":x?"Vault not reachable":r?i?"Syncing…":m.total>0?"Sync pending":"All caught up":"Offline — changes queued",j=async O=>{a&&(await $2(a,O),h("Retrying…","success"))},_=async(O,B)=>{a&&confirm(`Discard this ${wb(B.mutation)}? It cannot be recovered.`)&&(await Q2(a,O),h("Row discarded.","success"))},C=async()=>{if(!a||!f||!confirm(`Clear every pending row for this vault (${m.total} total)? Destructive.`))return;const O=await G2(a,f);h(`Cleared ${O} pending row${O===1?"":"s"}.`,"success")};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("header",{className:"flex items-baseline justify-between",children:[c.jsx("h3",{className:"font-serif text-base text-fg",children:T}),t?c.jsx("button",{type:"button",onClick:t,"aria-label":"Close sync status",className:"text-xs text-fg-dim hover:text-accent",children:"×"}):null]}),m.authHalt?c.jsxs("div",{className:"rounded-md border border-red-500/30 bg-red-500/5 p-3 text-xs text-red-300",children:[c.jsx("p",{className:"mb-2",children:m.authHalt.message||"Vault rejected the current session."}),c.jsx(_e,{to:"/add",onClick:t,className:"inline-block rounded-lg bg-accent px-3 py-1.5 text-xs font-medium text-(--color-on-accent) hover:bg-accent-hover",children:"Reconnect to resume sync"})]}):null,m.total===0?c.jsx("p",{className:"text-xs text-fg-dim",children:"Nothing pending in this vault."}):c.jsxs("section",{children:[c.jsx("h4",{className:"mb-1 text-xs uppercase tracking-wider text-fg-dim",children:"Queue"}),c.jsx("ul",{className:"space-y-0.5 text-xs",children:Object.entries(m.byKind).map(([O,B])=>c.jsxs("li",{className:"flex justify-between",children:[c.jsx("span",{className:"text-fg-muted",children:VC[O]??O}),c.jsx("span",{className:"tabular-nums text-fg-dim",children:B})]},O))})]}),m.needsHumanCount>0?c.jsxs("section",{children:[c.jsx("h4",{className:"mb-1 text-xs uppercase tracking-wider text-fg-dim",children:"Needs your help"}),c.jsx("ul",{className:"space-y-1.5",children:m.rows.filter(O=>O.status==="needs-human").map(O=>c.jsxs("li",{className:"rounded border border-amber-500/30 bg-amber-500/5 p-2 text-xs",children:[c.jsx("p",{className:"font-medium text-amber-200",children:wb(O.mutation)}),O.lastError?c.jsx("p",{className:"mt-0.5 break-words text-amber-100/70",children:O.lastError}):null,c.jsxs("div",{className:"mt-1 flex gap-2",children:[c.jsx("button",{type:"button",onClick:()=>j(O.seq),className:"text-accent hover:underline",children:"Retry"}),c.jsx("button",{type:"button",onClick:()=>_(O.seq,O),className:"text-red-300 hover:underline",children:"Discard"})]})]},O.seq))})]}):null,c.jsx("section",{className:"text-xs text-fg-dim",children:c.jsxs("p",{children:["Last synced:"," ",c.jsx("span",{className:"text-fg-muted",children:u?Tm(new Date(u).toISOString()):"never"})]})}),p?c.jsx(qC,{usage:p.usage,quota:p.quota}):null,m.total>0?c.jsx("div",{className:"flex justify-end border-t border-border pt-3",children:c.jsx("button",{type:"button",onClick:C,className:"text-xs text-red-400 hover:underline",children:"Clear all pending"})}):null]})}function wb(t){switch(t.kind){case"create-note":return`Create note (${t.payload.path??"untitled"})`;case"update-note":return`Update note ${t.targetId}`;case"update-settings":return`Update settings (${t.notePath})`;case"delete-note":return`Delete note ${t.targetId}`;case"upload-attachment":return`Upload ${t.filename}`;case"link-attachment":return`Link attachment to ${t.noteId}`;case"delete-attachment":return`Remove attachment from ${t.noteId}`}}function qC({usage:t,quota:a}){const r=a>0?t/a:0,i=r>=BC;return c.jsxs("section",{className:"text-xs",children:[c.jsxs("div",{className:"flex justify-between text-fg-dim",children:[c.jsx("span",{children:"Offline cache"}),c.jsx("span",{className:i?"text-amber-300":"text-fg-muted",children:$C(t)})]}),i?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"mt-1 h-1.5 w-full overflow-hidden rounded-full bg-border/40",children:c.jsx("div",{className:"h-full bg-amber-400",style:{width:`${Math.min(100,Math.round(r*100))}%`}})}),c.jsx("p",{className:"mt-1 text-amber-300",children:"This browser's offline storage is nearly full. Sync what you can and consider clearing stuck rows."})]}):null]})}function $C(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function QC(t){return t.authHalt?"halted":t.unreachable?"unreachable":t.isOnline?t.isDraining?"syncing":"online":"offline"}function IC(){const{db:t,isOnline:a,isDraining:r}=Zt(),i=ae(x=>x.activeVaultId),u=iS(t,i),f=Dr(x=>i?x.byVault[i]??null:null),[h,m]=b.useState(!1),p=b.useRef(null);b.useEffect(()=>{if(!h)return;const x=T=>{p.current&&(p.current.contains(T.target)||m(!1))};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[h]);const y=QC({isOnline:a,isDraining:r,authHalt:u.authHalt!==null,unreachable:(f==null?void 0:f.state)==="down"}),S=KC(y),v=u.total>0?u.total:null;return c.jsxs("div",{ref:p,className:"relative",children:[c.jsxs("button",{type:"button","aria-label":`Sync status: ${S}${v?`, ${v} pending`:""}`,"aria-expanded":h,onClick:()=>m(x=>!x),className:"flex min-h-11 min-w-11 items-center justify-center gap-1.5 rounded-lg border border-border bg-card px-2 py-1.5 text-sm text-fg-muted hover:text-accent",children:[c.jsx(GC,{tone:y}),c.jsx("span",{className:"hidden text-xs sm:inline",children:S}),v!==null?c.jsx("span",{"aria-label":`${v} pending`,className:"rounded-full bg-accent/20 px-1.5 text-[10px] font-medium tabular-nums text-accent",children:v}):null]}),h?c.jsx("div",{role:"dialog","aria-label":"Sync status details",className:"enter-rise absolute right-0 z-30 mt-2 w-80 rounded-xl border border-border bg-card p-4 text-sm shadow-lift",children:c.jsx(HC,{onDismiss:()=>m(!1)})}):null]})}function KC(t){switch(t){case"online":return"Online";case"offline":return"Offline";case"syncing":return"Syncing…";case"halted":return"Reconnect";case"unreachable":return"Vault down"}}function GC({tone:t}){const a=t==="online"?"var(--color-grass)":t==="offline"?"var(--color-warning)":t==="syncing"?"var(--color-sky)":t==="unreachable"?"color-mix(in srgb, var(--color-danger) 70%, var(--color-bg))":"var(--color-danger)";return c.jsx("span",{"aria-hidden":!0,className:`inline-block h-2 w-2 rounded-full ${t==="syncing"?"animate-pulse":""}`,style:{backgroundColor:a}})}function YC(){const t=Ge(),a=ae(u=>Object.keys(u.vaults).length>0),[r,i]=b.useState(null);return b.useEffect(()=>{i(null)},[t.pathname]),!a&&t.pathname==="/"?null:c.jsxs(c.Fragment,{children:[c.jsx("header",{className:"sticky top-0 z-10 border-b border-border bg-bg/90 backdrop-blur lg:hidden",style:{paddingTop:"env(safe-area-inset-top)"},children:c.jsxs("nav",{className:"flex items-center justify-between gap-3 px-4 py-3",children:[a?c.jsx("div",{className:"min-w-0 flex-1",children:c.jsx(Em,{variant:"header",onOpenNavSheet:()=>i("switcher")})}):c.jsx(_e,{to:"/",className:"focus-ring min-w-0 shrink truncate font-serif text-lg tracking-tight text-fg hover:text-accent",children:"Parachute"}),c.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a?c.jsx(IC,{}):null,c.jsx("button",{type:"button",onClick:()=>i("menu"),"aria-label":"Open menu","aria-expanded":r!==null,"aria-haspopup":"dialog",className:"focus-ring flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-card text-fg-muted hover:text-accent",children:c.jsx("span",{"aria-hidden":"true",className:"font-mono text-base leading-none",children:"☰"})})]})]})}),c.jsx(kC,{open:r!==null,onClose:()=>i(null),initialFocus:r==="switcher"?"switcher":void 0})]})}function PC(){const{mirror:t}=Zt();return t.state==="hydrating"&&t.progress?c.jsx(FC,{done:t.progress.done}):t.state==="offline"&&t.lastSyncedAt!==null?c.jsxs(lS,{children:["Offline — showing your saved vault · updated ",XC(t.lastSyncedAt)]}):null}function FC({done:t}){var u;const a=(u=B0().data)==null?void 0:u.stats,r=a==null?void 0:a.totalNotes,i=typeof r=="number"&&r>0?`${t} of ~${r}`:`${t}`;return c.jsxs(lS,{live:"off",children:["Saving your vault for offline · ",i]})}function lS({children:t,live:a}){return c.jsx("output",{"aria-live":a,className:"block border-b border-border bg-bg-soft px-4 py-1.5 text-center text-xs text-fg-muted md:px-6",children:t})}function XC(t){return Tm(new Date(t).toISOString())}const uS=10,ZC="lens:recents:";function oS(t){return ZC+t}function cS(t){try{const a=localStorage.getItem(oS(t));if(!a)return[];const r=JSON.parse(a);return Array.isArray(r)?r.filter(i=>typeof i=="object"&&i!==null&&typeof i.id=="string"&&typeof i.viewedAt=="number").slice(0,uS):[]}catch{return[]}}function e5(t,a,r=Date.now()){try{const i=cS(t).filter(f=>f.id!==a),u=[{id:a,viewedAt:r},...i].slice(0,uS);localStorage.setItem(oS(t),JSON.stringify(u))}catch{}}const JC=new Set([" ","/","-","_",".","\\"]);function nl(t,a){if(!t)return{score:0,indices:[]};if(!a)return null;const r=t.toLowerCase(),i=a.toLowerCase();let u=0,f=0,h=-2,m=!0;const p=[];for(let y=0;y<i.length&&u<r.length;y+=1){const S=i[y]??"";if(S===r[u]){p.push(y);let v=1;y===0?v+=4:m&&(v+=2),h===y-1&&(v+=3),f+=v,h=y,u+=1}m=JC.has(S)}return u<r.length?null:(f-=Math.floor(i.length/20),{score:f,indices:p})}const Cd=20,Eb=[{id:"new",label:"New note",description:"Open the unified create surface (text + voice)",keywords:["new","create","compose","capture","voice","memo"],action:{type:"navigate",to:"/new"}},{id:"graph",label:"Map",description:"Full-vault map view",keywords:["graph","map","visualize"],action:{type:"navigate",to:"/map"}},{id:"today",label:"Recent",description:"Your recent notes, grouped by day",keywords:["today","now","daily","home","recent"],action:{type:"navigate",to:"/"}},{id:"calendar",label:"Calendar",description:"Month grid of note activity",keywords:["calendar","month","date"],action:{type:"navigate",to:"/calendar"}},{id:"tags",label:"Tags",description:"Browse all tags",keywords:["tags"],action:{type:"navigate",to:"/tags"}},{id:"notes",label:"All notes",description:"The full notes browser",keywords:["notes","all","browse","files"],action:{type:"navigate",to:"/notes"}},{id:"pinned",label:"Pinned",description:"Notes tagged as pinned",keywords:["pinned","star","favorites"],action:{type:"navigate",to:"/notes?view=pinned"}},{id:"archived",label:"Archived",description:"Notes tagged as archived",keywords:["archived","archive"],action:{type:"navigate",to:"/notes?view=archived"}},{id:"untagged",label:"Untagged",description:"Notes with no tags — quick-tag inline",keywords:["untagged","unfiled","inbox"],action:{type:"navigate",to:"/notes?view=untagged"}},{id:"orphaned",label:"Orphaned",description:"Notes with no inbound or outbound links",keywords:["orphaned","orphans","isolated","unlinked"],action:{type:"navigate",to:"/notes?view=orphaned"}}];function WC(t,a){let r=null;for(const i of t){const u=nl(a,i);u&&(r===null||u.score>r)&&(r=u.score)}return r}function eO(t,a){const r=PA(t),i=nl(a,r),u=t.path?nl(a,t.path):null;let f=null;i&&(f=i.score+2),u&&(f===null||u.score>f)&&(f=u.score);for(const h of t.tags??[]){const m=nl(a,h);m&&(f===null||m.score>f)&&(f=m.score)}return f}function tO(t){const a=t.query.trim(),r=a.startsWith(">"),i=(r?a.slice(1):a).trim();if(a.length===0){const y=new Map(t.notes.map(x=>[x.id,x])),S=[];for(const x of t.recents){const T=y.get(x.id);if(!T)continue;const j=dh(T);S.push({kind:"note",id:T.id,title:j.text,titleKind:j.kind,path:T.path,score:0})}const v=Eb.map(x=>({kind:"command",id:x.id,label:x.label,description:x.description,action:x.action,score:0}));return[...S,...v].slice(0,Cd)}const u=Eb.flatMap(y=>{const S=WC([y.label,...y.keywords],i);return S===null?[]:[{kind:"command",id:y.id,label:y.label,description:y.description,action:y.action,score:S+(r?1e3:0)}]});if(r)return u.sort((y,S)=>S.score-y.score).slice(0,Cd);const f=t.notes.flatMap(y=>{const S=eO(y,i);if(S===null)return[];const v=dh(y);return[{kind:"note",id:y.id,title:v.text,titleKind:v.kind,path:y.path,score:S}]}),m=[...t.tags.flatMap(y=>{const S=nl(i,y.name);return S?[{kind:"tag",name:y.name,count:y.count,score:S.score}]:[]})].sort((y,S)=>S.score-y.score),p=[...u,...f].sort((y,S)=>S.score-y.score);return[...m,...p].slice(0,Cd)}const nO=150;function aO({onClose:t}){const a=ae(k=>k.activeVaultId),r=Mr(),i=b.useRef(null),u=b.useRef(null),f=b.useId(),h=b.useId(),[m,p]=b.useState(""),[y,S]=b.useState(""),[v,x]=b.useState(0),T=j_(!0),j=__(),_=b.useMemo(()=>a?cS(a):[],[a]);b.useEffect(()=>{const k=setTimeout(()=>S(m),nO);return()=>clearTimeout(k)},[m]);const C=b.useMemo(()=>tO({query:y,notes:T.data??[],tags:j.data??[],recents:_}),[y,T.data,j.data,_]);b.useEffect(()=>{x(0)},[C.length]),b.useEffect(()=>{var k;(k=i.current)==null||k.focus()},[]);const O=b.useCallback(k=>{k.kind==="note"?r(`/n/${encodeURIComponent(k.id)}`):k.kind==="tag"?r(`/tags/${encodeURIComponent(k.name)}`):r(k.action.to),t()},[r,t]),B=b.useCallback(k=>{if(k.key==="Escape"){k.preventDefault(),t();return}if(k.key==="ArrowDown"){k.preventDefault(),x(Y=>Math.min(C.length-1,Y+1));return}if(k.key==="ArrowUp"){k.preventDefault(),x(Y=>Math.max(0,Y-1));return}if(k.key==="Enter"){k.preventDefault();const Y=C[v];Y&&O(Y);return}},[C,v,O,t]);b.useEffect(()=>{var Y,Q;const k=(Y=u.current)==null?void 0:Y.querySelector(`[data-qs-idx="${v}"]`);(Q=k==null?void 0:k.scrollIntoView)==null||Q.call(k,{block:"nearest"})},[v]);const H=T.isPending;return c.jsx("dialog",{open:!0,"aria-labelledby":f,className:"qs-scrim-fade fixed inset-0 z-50 m-0 h-full max-h-full w-full max-w-full bg-[color-mix(in_srgb,var(--color-fg)_32%,transparent)] p-0 backdrop-blur-[3px] lg:flex lg:px-6 lg:pb-8",onMouseDown:k=>{k.target===k.currentTarget&&t()},children:c.jsxs("div",{className:"flex h-full w-full flex-col bg-bg/95 backdrop-blur-md lg:mx-auto lg:h-auto lg:w-full lg:max-w-xl lg:flex-col-reverse lg:self-end lg:bg-transparent lg:backdrop-blur-none",children:[c.jsxs("div",{className:"enter-rise flex items-center gap-2 px-3 pt-[max(0.75rem,env(safe-area-inset-top))] pb-2 lg:p-0",children:[c.jsxs("div",{className:"glass-panel flex min-w-0 flex-1 items-center gap-2.5 rounded-full border border-border px-4 py-2.5 shadow-soft transition-shadow duration-(--dur-quick) ease-out focus-within:shadow-lift lg:px-5 lg:py-3",children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-fg-dim",children:c.jsx(co,{width:18,height:18})}),c.jsx("input",{id:f,ref:i,type:"text",value:m,onChange:k=>p(k.target.value),onKeyDown:B,placeholder:"Search your vault…","aria-label":"Quick switch query","aria-controls":h,"aria-activedescendant":C[v]?`qs-opt-${v}`:void 0,autoComplete:"off",spellCheck:!1,className:"min-w-0 flex-1 bg-transparent text-base text-fg placeholder:text-fg-dim focus:outline-none"}),c.jsxs("span",{"aria-hidden":"true","data-testid":"smart-slot-reserved",className:"hidden shrink-0 select-none items-center gap-1 rounded-full border border-border-light px-2.5 py-1 text-xs text-fg-dim opacity-70 lg:flex",children:[c.jsx(zx,{width:13,height:13}),"Smart"]})]}),c.jsx("button",{type:"button",onClick:t,className:"focus-ring shrink-0 rounded-full px-3 py-2 text-sm text-fg-muted hover:text-accent lg:hidden",children:"Cancel"})]}),c.jsxs("div",{className:"enter-rise glass-panel flex min-h-0 flex-1 flex-col lg:mb-3 lg:max-h-[55vh] lg:flex-none lg:rounded-[var(--radius-2xl)] lg:border lg:border-border lg:shadow-lift",children:[c.jsx("div",{id:h,ref:u,role:"listbox",tabIndex:-1,"aria-label":"Quick switch results","aria-live":"polite",className:"min-h-0 flex-1 overflow-y-auto py-1 lg:max-h-[50vh]",children:H&&C.length===0?c.jsx("div",{className:"px-4 py-3 text-sm text-fg-dim",children:"Loading notes…"}):C.length===0?c.jsx("div",{className:"px-4 py-3 text-sm text-fg-dim",children:m.trim().length===0?"Start typing to search.":"No matches."}):C.map((k,Y)=>c.jsx(sO,{entry:k,index:Y,selected:Y===v,onPick:()=>O(k),onHover:()=>x(Y)},rO(k)))}),c.jsxs("div",{className:"hidden items-center justify-between border-t border-border-light px-4 py-2 text-xs text-fg-dim lg:flex",children:[c.jsxs("span",{children:[c.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"↑↓"})," navigate"," ",c.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"↵"})," open"," ",c.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"esc"})," close"," ",c.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:">"})," commands"]}),c.jsx("span",{className:"tabular-nums",children:C.length>0?`${C.length} result${C.length===1?"":"s"}`:""})]})]})]})})}function rO(t){return t.kind==="note"?`note:${t.id}`:t.kind==="tag"?`tag:${t.name}`:`cmd:${t.id}`}function sO({entry:t,index:a,selected:r,onPick:i,onHover:u}){const f=r?"bg-accent/10 text-fg":"text-fg-muted";return c.jsx("div",{id:`qs-opt-${a}`,role:"option",tabIndex:-1,"aria-selected":r,"data-qs-idx":a,onMouseEnter:u,onMouseDown:h=>{h.preventDefault(),i()},className:`mx-1.5 flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-sm ${f}`,children:t.kind==="note"?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"note"}),c.jsx("span",{className:t.titleKind==="timestamp"?"truncate title-timestamp":"truncate font-medium",children:t.title}),t.path?c.jsx("span",{className:"ml-auto truncate font-mono text-xs text-fg-dim",children:t.path}):null]}):t.kind==="tag"?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"tag"}),c.jsxs("span",{className:"font-mono",children:["#",t.name]}),c.jsx("span",{className:"ml-auto text-xs tabular-nums text-fg-dim",children:t.count})]}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-xs uppercase tracking-wider text-accent",children:"cmd"}),c.jsx("span",{className:"font-medium",children:t.label}),c.jsx("span",{className:"ml-auto text-xs text-fg-dim",children:t.description})]})})}function iO(){const t=tl(f=>f.open),a=tl(f=>f.setOpen),r=tl(f=>f.toggle),i=ae(f=>f.activeVaultId);b.useEffect(()=>{const f=h=>{h.key==="k"&&(h.metaKey||h.ctrlKey)&&!h.altKey&&!h.shiftKey&&(h.preventDefault(),r())};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r]);const u=b.useRef(i);return b.useEffect(()=>{u.current!==i&&(u.current=i,a(!1))},[i,a]),!t||i===null?null:c.jsx(aO,{onClose:()=>a(!1)})}const Tb="parachute.rail-collapsed";function lO(){const[t,a]=b.useState(()=>{try{return localStorage.getItem(Tb)==="1"}catch{return!1}}),r=b.useCallback(()=>{a(i=>{const u=!i;try{localStorage.setItem(Tb,u?"1":"0")}catch{}return u})},[]);return[t,r]}function uO(){const t=ae(h=>h.getActiveVault()),a=Sm(),[r,i]=lO();if(!t)return null;const u=a.filter(h=>h.id!=="foot"),f=a.find(h=>h.id==="foot");return c.jsxs("aside",{"aria-label":"Primary",className:`glass-panel sticky top-0 hidden h-dvh shrink-0 flex-col border-r border-border transition-[width] duration-(--dur-move) ease-out lg:flex ${r?"w-16":"w-60"}`,style:{paddingTop:"env(safe-area-inset-top)"},children:[c.jsxs("div",{className:r?"flex flex-col items-stretch gap-2 p-3":"p-3",children:[c.jsxs("div",{className:r?"":"flex items-start gap-1.5",children:[c.jsx("div",{className:"min-w-0 flex-1",children:c.jsx(Em,{variant:"rail",collapsed:r})}),c.jsx("button",{type:"button",onClick:i,"aria-label":r?"Expand the sidebar":"Collapse the sidebar","aria-expanded":!r,title:r?"Expand":"Collapse",className:`focus-ring grid shrink-0 place-items-center rounded-lg text-fg-dim hover:bg-bg hover:text-fg-muted ${r?"mx-auto mt-2 h-8 w-8":"h-9 w-7"}`,children:c.jsx("span",{"aria-hidden":!0,className:`transition-transform duration-(--dur-move) ease-out ${r?"rotate-180":""}`,children:c.jsx(Lj,{width:16,height:16})})})]}),c.jsx(cO,{collapsed:r})]}),c.jsx("nav",{"aria-label":"Your vault",className:"flex-1 overflow-y-auto px-3 pb-3",children:u.map(h=>c.jsx(oO,{band:h,collapsed:r},h.id))}),c.jsxs("div",{"data-nav-band":"foot",className:"border-t border-border p-3",children:[f==null?void 0:f.items.map(h=>r?c.jsx(Sh,{item:h,collapsed:!0},h.id):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("div",{className:"min-w-0 flex-1",children:c.jsx(Sh,{item:h,collapsed:!1})}),c.jsx(xh,{})]},h.id)),r?c.jsx("div",{className:"mt-1 flex justify-center",children:c.jsx(xh,{})}):null]})]})}function oO({band:t,collapsed:a}){return c.jsxs("div",{"data-nav-band":t.id,children:[t.label&&!a?c.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[c.jsx("span",{children:t.label}),t.sublabel?c.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.label&&a?c.jsx("div",{"aria-hidden":!0,className:"mx-2 mt-3 mb-2 border-t border-border-light"}):null,t.items.map(r=>c.jsx(Sh,{item:r,collapsed:a},r.id))]})}function Sh({item:t,collapsed:a}){const r=Ge(),i=t.match(r);return c.jsxs(_e,{to:t.to,"data-nav-item":t.id,"aria-current":i?"page":void 0,"aria-label":a?t.label:void 0,title:a?t.label:void 0,className:`focus-ring flex items-center rounded-lg font-round text-sm transition-colors duration-(--dur-quick) ease-out ${a?"justify-center px-0 py-2":"gap-3 px-3 py-2"} ${i?"bg-grass-soft font-semibold text-grass-ink":"font-medium text-fg-muted hover:bg-bg hover:text-fg"}`,children:[c.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),a?null:c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})]})}function cO({collapsed:t}){const a=tl(r=>r.setOpen);return t?c.jsx("button",{type:"button",onClick:()=>a(!0),"aria-label":"Search",title:"Search (⌘K)",className:"focus-ring mx-auto grid h-9 w-9 place-items-center rounded-lg border border-border bg-card text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:border-accent/50 hover:text-fg-muted",children:c.jsx(co,{width:16,height:16})}):c.jsxs("button",{type:"button",onClick:()=>a(!0),className:"focus-ring mt-2 flex w-full items-center gap-2.5 rounded-lg border border-border bg-card px-3 py-2 text-left font-round text-sm text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:border-accent/50 hover:text-fg-muted",children:[c.jsx("span",{"aria-hidden":!0,className:"grid h-4 w-4 shrink-0 place-items-center",children:c.jsx(co,{width:16,height:16})}),c.jsx("span",{className:"flex-1",children:"Search…"}),c.jsx("kbd",{className:"shrink-0 rounded border border-border px-1.5 py-0.5 font-round text-[10px] text-fg-dim",children:"⌘K"})]})}function fO(){const t=ae(m=>m.activeVaultId!==null),{pathname:a}=Ge(),[r,i]=b.useState(!1),u=b.useRef(null),f=b.useRef(null),h=b.useId();return b.useEffect(()=>{i(!1)},[a]),b.useEffect(()=>{if(!r)return;const m=y=>{var S;y.key==="Escape"&&(i(!1),(S=f.current)==null||S.focus())},p=y=>{u.current&&y.target instanceof Node&&!u.current.contains(y.target)&&i(!1)};return document.addEventListener("keydown",m),document.addEventListener("pointerdown",p),()=>{document.removeEventListener("keydown",m),document.removeEventListener("pointerdown",p)}},[r]),!t||Z0(a)||a==="/new"?null:c.jsxs("div",{ref:u,className:"fixed top-6 right-6 z-30 hidden lg:block",children:[c.jsx("button",{ref:f,type:"button",onClick:()=>i(m=>!m),"aria-label":r?"Close create menu":"Create","aria-expanded":r,"aria-controls":h,title:r?void 0:"Create",className:"focus-ring grid h-12 w-12 place-items-center rounded-full bg-accent text-(--color-on-accent) shadow-lift transition-transform duration-(--dur-move) ease-out hover:scale-105 hover:bg-accent-hover motion-reduce:hover:scale-100",children:c.jsx("span",{"aria-hidden":"true",className:`transition-transform duration-(--dur-move) ease-out ${r?"rotate-45":""}`,children:c.jsx(Kh,{width:24,height:24,strokeWidth:2})})}),r?c.jsxs("div",{id:h,"aria-label":"Create",className:"mt-3 flex flex-col items-end gap-3",children:[c.jsx(Od,{to:"/new",label:"New note",icon:c.jsx(Oj,{width:18,height:18})}),c.jsx(Od,{to:"/new?voice=1",label:"Voice note",icon:c.jsx(Mj,{width:18,height:18})}),c.jsx(Od,{to:"/import",label:"Import notes",icon:c.jsx(Vx,{width:18,height:18})})]}):null]})}function Od({to:t,label:a,icon:r}){return c.jsxs(_e,{to:t,"data-speed-dial-verb":a,className:"focus-ring group flex items-center gap-3 rounded-full",children:[c.jsx("span",{className:"rounded-full border border-border bg-card px-3.5 py-1.5 text-sm font-medium text-fg shadow-soft transition-colors duration-(--dur-quick) ease-out group-hover:border-accent/50",children:a}),c.jsx("span",{"aria-hidden":"true",className:"grid h-11 w-11 place-items-center rounded-full bg-fg text-bg shadow-soft transition-transform duration-(--dur-move) ease-out group-hover:scale-105 motion-reduce:group-hover:scale-100",children:r})]})}const dO=4e3;function hO(){const t=aa(r=>r.toasts),a=aa(r=>r.dismiss);return b.useEffect(()=>{if(t.length===0)return;const r=t.map(i=>window.setTimeout(()=>a(i.id),i.durationMs??dO));return()=>{for(const i of r)window.clearTimeout(i)}},[t,a]),t.length===0?null:c.jsx("output",{"aria-live":"polite",className:"pointer-events-none fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 flex-col items-center gap-2",children:t.map(r=>c.jsxs("div",{className:`enter-rise pointer-events-auto flex max-w-md items-center gap-3 rounded-lg border px-4 py-2 text-sm shadow-lift backdrop-blur ${r.tone==="error"?"border-(--color-danger-border) bg-(--color-danger-soft) text-(--color-danger)":r.tone==="success"?"border-accent/40 bg-accent/10 text-accent":"border-border bg-card text-fg-muted"}`,children:[c.jsx("span",{children:r.message}),c.jsx("button",{type:"button",onClick:()=>a(r.id),"aria-label":"Dismiss",className:"focus-ring text-fg-dim hover:text-fg",children:"×"})]},r.id))})}function mO(t={}){const{immediate:a=!1,onNeedReload:r,onNeedRefresh:i,onOfflineReady:u,onRegistered:f,onRegisteredSW:h,onRegisterError:m}=t;let p,y;const S=async(x=!0)=>{await y};async function v(){if("serviceWorker"in navigator){if(p=await Qe(async()=>{const{Workbox:x}=await import("./workbox-window.prod.es5-BBnX5xw4.js");return{Workbox:x}},[]).then(({Workbox:x})=>new x("/sw.js",{scope:"/",type:"classic"})).catch(x=>{m==null||m(x)}),!p)return;p.addEventListener("activated",x=>{(x.isUpdate||x.isExternal)&&(r?r():window.location.reload())}),p.addEventListener("installed",x=>{x.isUpdate||u==null||u()}),p.register({immediate:a}).then(x=>{h?h("/sw.js",x):f==null||f(x)}).catch(x=>{m==null||m(x)})}}return y=v(),S}function pO(t={}){const{immediate:a=!0,onNeedReload:r,onNeedRefresh:i,onOfflineReady:u,onRegistered:f,onRegisteredSW:h,onRegisterError:m}=t,[p,y]=b.useState(!1),[S,v]=b.useState(!1),[x]=b.useState(()=>mO({immediate:a,onNeedReload:r,onOfflineReady(){v(!0),u==null||u()},onNeedRefresh(){y(!0),i==null||i()},onRegistered:f,onRegisteredSW:h,onRegisterError:m}));return{needRefresh:[p,y],offlineReady:[S,v],updateServiceWorker:x}}const jb={BASE_URL:"/"};function gO(t,a){const r=t&&t.length>0?t:a;return!r||r===""||r==="/"?"":r.replace(/\/$/,"")}function yO(){const t=typeof import.meta<"u"&&jb?jb:void 0,a=t?t.VITE_BASE_PATH:void 0,r=t?t.BASE_URL:void 0;return gO(a,r)}const vO=yO();function bO(t){return pl()===vO}async function xO(t=typeof navigator>"u"?void 0:navigator,a){if(!t||!("serviceWorker"in t))return 0;const r=t.serviceWorker;if(!r||typeof r.getRegistrations!="function")return 0;const i=pl(),u=await r.getRegistrations();let f=0;for(const h of u)try{const p=new URL(h.scope).pathname.replace(/\/$/,"")||"/";if(p===i||!(/^\/notes$/.test(p)||/^\/surface\/[a-z0-9][a-z0-9_-]*$/.test(p)))continue;await h.unregister(),f+=1,typeof console<"u"&&console.info(`[notes-ui] unregistered stale service worker at scope ${h.scope} (runtime mount is ${i})`)}catch(m){typeof console<"u"&&console.warn(`[notes-ui] failed to inspect/unregister SW: ${String(m)}`)}return f}function SO(){return pO({onRegisteredSW(t,a){if(!a)return;const r=3600*1e3;setInterval(()=>{a.update().catch(()=>{})},r)},onNeedReload(){BE()}}),null}function wO(){return bO()?c.jsx(SO,{}):null}function EO(){const t=ae(u=>u.activeVaultId),a=ae(u=>u.getActiveVault()),r=Rr(u=>t?u.byVault[t]??null:null),i=Dr(u=>t?u.byVault[t]??null:null);return!a||!t?null:r&&!Qs(a.clientId)?c.jsx(TO,{reason:r.reason,vaultIssuer:a.issuer??a.url,vaultScope:a.scope,vaultId:t}):i&&i.state==="down"?c.jsx(jO,{vaultUrl:a.url,vaultId:t}):null}function TO({reason:t,vaultIssuer:a,vaultScope:r,vaultId:i}){const[u,f]=b.useState(!1),[h,m]=b.useState(null),[p,y]=b.useState(!1);async function S(){m(null),y(!1),f(!0);try{const{authorizeUrl:v}=await pm(a,r,void 0,{priorHaltedVaultId:i});window.location.assign(v)}catch(v){v instanceof No?y(!0):m(v instanceof Error?v.message:String(v))}finally{f(!1)}}return c.jsxs("div",{role:"alert","aria-live":"assertive",className:"border-b border-red-500/40 bg-red-500/10 px-4 py-3 text-sm text-red-200 md:px-6",children:[c.jsxs("div",{className:"mx-auto flex max-w-5xl flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[c.jsxs("div",{children:[c.jsx("p",{className:"font-medium text-red-100",children:"Vault session expired"}),c.jsx("p",{className:"text-xs text-red-200/80",children:t}),h?c.jsx("p",{className:"mt-1 text-xs text-red-300",children:h}):null]}),c.jsx("button",{type:"button",onClick:S,disabled:u,className:"self-start rounded-lg bg-red-500/30 px-3 py-1.5 text-xs font-medium text-red-50 hover:bg-red-500/50 disabled:cursor-not-allowed disabled:opacity-60 md:self-auto",children:u?"Starting OAuth…":"Reconnect to vault"})]}),p?c.jsx("div",{className:"mx-auto mt-2 max-w-5xl",children:c.jsx(rS,{})}):null]})}function jO({vaultUrl:t,vaultId:a}){const r=ke(),i=pt(),u=Dr(y=>y.resetToHealthy),[f,h]=b.useState(!1);async function m(){if(r){h(!0);try{await r.vaultInfo(!1),i.invalidateQueries({queryKey:["notes",a]}),i.invalidateQueries({queryKey:["tags",a]}),i.invalidateQueries({queryKey:["vaultInfo",a]}),i.invalidateQueries({queryKey:["note",a]})}catch{}finally{h(!1)}}}const p=AO(t)?"Try `parachute start vault` in a terminal.":null;return c.jsx("div",{role:"alert","aria-live":"polite",className:"border-b border-red-500/30 bg-red-500/5 px-4 py-3 text-sm text-red-200 md:px-6",children:c.jsxs("div",{className:"mx-auto flex max-w-5xl flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[c.jsxs("div",{children:[c.jsx("p",{className:"font-medium text-red-100",children:"Vault not reachable"}),c.jsxs("p",{className:"text-xs text-red-200/80",children:["Notes can't sync until it's back online.",p?` ${p}`:""]})]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",onClick:m,disabled:f||!r,className:"self-start rounded-lg bg-red-500/20 px-3 py-1.5 text-xs font-medium text-red-50 hover:bg-red-500/40 disabled:cursor-not-allowed disabled:opacity-60 md:self-auto",children:f?"Retrying…":"Retry now"}),c.jsx("button",{type:"button",onClick:()=>u(a),className:"self-start rounded-lg px-3 py-1.5 text-xs text-red-200/80 hover:text-red-100 md:self-auto","aria-label":"Dismiss banner",title:"Dismiss",children:"Dismiss"})]})]})})}const NO=/^(10|192\.168|172\.(1[6-9]|2\d|3[0-1]))\./;function AO(t){try{const r=new URL(t).hostname.replace(/^\[/,"").replace(/\]$/,"");return!!(r==="localhost"||r==="127.0.0.1"||r==="::1"||r.endsWith(".local")||NO.test(r))}catch{return!1}}function wh({icon:t,title:a,description:r,action:i,className:u=""}){return c.jsxs("div",{className:`card p-10 text-center ${u}`.trim(),children:[t?c.jsx("div",{className:"mb-3 flex justify-center text-fg-dim","aria-hidden":"true",children:t}):null,c.jsx("p",{className:"text-fg-muted",children:a}),r?c.jsx("p",{className:"mt-1 text-sm text-fg-dim",children:r}):null,i?c.jsx("div",{className:"mt-4 flex justify-center",children:i}):null]})}const _O="parachute:door-descriptor";function fS(){const t=typeof window<"u"&&window.location?window.location.origin:"";return`${_O}:${t}`}let Pt,Eh=null,Th=!1,xo=!1;const lo=new Set,RO=["monthly","quarterly","yearly"];function CO(t){if(!t||typeof t!="object"||Array.isArray(t))return null;const a=t;if(typeof a.available!="boolean"||a.price!==void 0&&typeof a.price!="number"||a.label!==void 0&&typeof a.label!="string")return null;const r={available:a.available};return typeof a.price=="number"&&(r.price=a.price),typeof a.label=="string"&&(r.label=a.label),r}function OO(t){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return;const a=t,r={};let i=!1;for(const u of RO){if(!(u in a))continue;const f=CO(a[u]);f&&(r[u]=f,i=!0)}return i?r:void 0}function MO(t){const a=t,{intervals:r,...i}=a,u=OO(r);return u!==void 0?{...i,intervals:u}:i}function dS(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;const a=t,r=a.auth,i=!!r&&Array.isArray(r.methods)&&r.methods.length>0&&r.methods.every(S=>typeof S=="string")&&typeof r.signin_path=="string"&&r.signin_path.startsWith("/"),u=a.plans===void 0||Array.isArray(a.plans)&&a.plans.every(S=>!!S&&typeof S=="object"),f=u&&Array.isArray(a.plans)?a.plans.map(S=>MO(S)):void 0;if(i&&u)return f?{...a,plans:f}:a;const{auth:h,plans:m,...p}=a,y={...p};return i&&(y.auth=a.auth),u&&f&&(y.plans=f),y}async function DO(t){try{const a=await t("/.well-known/parachute-account");return a.ok?dS(await a.json()):null}catch{return null}}function hS(){try{const t=localStorage.getItem(fS());if(t==null)return;const a=dS(JSON.parse(t));return a===null?void 0:a}catch{return}}function kO(t){try{localStorage.setItem(fS(),JSON.stringify(t))}catch{}}function LO(t){Th||(Th=!0,Eh=DO(t).then(a=>{if(a!==null){const r=JSON.stringify(Pt)!==JSON.stringify(a);if(Pt=a,kO(a),r)for(const i of lo)i(a)}else if(Pt===void 0){Pt=null;for(const r of lo)r(null)}return xo=!0,lo.clear(),Pt??null}).finally(()=>{Eh=null}))}async function mS(t=fetch.bind(globalThis),a){if(Pt===void 0){const r=hS();r!==void 0&&(Pt=r)}return a&&!xo&&lo.add(a),LO(t),Pt!==void 0?Pt:Eh??null}function UO(){if(Pt===void 0){const t=hS();t!==void 0&&(Pt=t)}return Pt??null}function zO(){Pt===null&&xo&&(Th=!1,xo=!1)}function t5(t){return t.length===0?{kind:"first-vault"}:t.length===1&&t[0]?{kind:"welcome-back",vault:t[0]}:{kind:"picker",vaults:t}}async function VO({hasLocalActiveVault:t,fetchImpl:a=fetch.bind(globalThis)}){let r;try{r=await xl(a)}catch{return{kind:"front-door"}}if(!r.signed_in)return{kind:"front-door"};r.email&&ax(r.email),r.password_change_required&&Ft.getState().markGate("force_change_password");try{const i=await Fx(r.csrf,a);sx(i.token,r.email??r.username??null)}catch(i){if(BO(i))return{kind:"signed-in",email:r.email,username:r.username,vaults:[]}}try{const{vaults:i}=await Zx(a);return{kind:"signed-in",email:r.email,username:r.username,vaults:i}}catch(i){return{kind:"net-error",message:i instanceof Error?i.message:"Unknown error"}}}function BO(t){return t instanceof bl?t.status===403&&t.message==="force_change_password"?(Ft.getState().markGate("force_change_password"),!0):t.status===423?(Ft.getState().markGate("admin_locked"),!0):!1:!1}function HO({children:t}){const[a]=b.useState(()=>new IN({defaultOptions:{queries:{retry:(r,i)=>{var u;if(!(i instanceof Error))return r<2;if(i instanceof $a)return!1;if(i instanceof Jn){const f=ae.getState().activeVaultId;return(f?(u=Dr.getState().byVault[f])==null?void 0:u.state:void 0)==="down"?!1:r<1}return r<2},refetchOnWindowFocus:!1,staleTime:1e4}}}));return c.jsx(KN,{client:a,children:t})}const qO=[/^\/api\//,/^\/oauth\/(?!callback)/,/^\/\.well-known\//,/^\/signup/,/^\/login/,/^\/logout/,/^\/auth\//,/^\/console/,/^\/admin/,/^\/account\//,/^\/billing/,/^\/unsubscribe/,/^\/health/,/^\/vault\//,/^\/u\//];function $O(t){return qO.some(a=>a.test(t))}function Ps({size:t=24,className:a}){return c.jsxs("svg",{width:t,height:t,viewBox:"0 0 64 64","aria-hidden":"true",className:a,children:[c.jsx("path",{d:"M8 30 Q32 2 56 30 Q49 37 42 30 Q37 38 32 30 Q27 38 22 30 Q15 37 8 30 Z",fill:"var(--color-accent-light)"}),c.jsx("path",{d:"M8 30 Q32 2 56 30",fill:"none",stroke:"var(--color-accent)",strokeWidth:"1.4"}),c.jsx("line",{x1:"8",y1:"30",x2:"30",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),c.jsx("line",{x1:"22",y1:"30",x2:"30",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),c.jsx("line",{x1:"42",y1:"30",x2:"34",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),c.jsx("line",{x1:"56",y1:"30",x2:"34",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),c.jsx("rect",{x:"26",y:"50",width:"12",height:"10",rx:"2.5",fill:"var(--color-sun)",stroke:"var(--color-sun-ink)",strokeWidth:"1"})]})}function QO({size:t=22}){return c.jsxs(_e,{to:"/",className:"focus-ring inline-flex items-center gap-2 rounded-lg font-round font-bold text-fg hover:text-accent",children:[c.jsx(Ps,{size:t}),c.jsx("span",{children:"Parachute"})]})}const pS="/welcome";function Md({signedIn:t,netError:a,onRetry:r}={}){return t?c.jsx(JO,{email:t.email,username:t.username,vaults:t.vaults}):a?c.jsx(WO,{message:a,onRetry:r}):c.jsx(PO,{})}function Tl({children:t}){return c.jsxs("div",{className:"relative flex min-h-[calc(100dvh-4rem)] flex-col",children:[c.jsx("div",{className:"flex items-center px-6 pt-6 sm:px-10",children:c.jsx(QO,{})}),c.jsx("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-10 text-center",children:c.jsx("div",{className:"mx-auto w-full max-w-md",children:t})})]})}function gS(){return c.jsx("div",{className:"mt-8 border-t border-border pt-6",children:c.jsxs("p",{className:"font-round text-sm text-fg-muted",children:["Self-hosting?"," ",c.jsx(_e,{to:"/add",className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Connect your own vault →"})," ",c.jsx("span",{className:"text-fg-dim",children:"(your notes stay on your server)"})]})})}function IO(t){var r;if(!t)return"neutral";const a=((r=t.auth)==null?void 0:r.methods)??[];return t.auth!=null&&!a.includes("magic_link")?"hub":t.door==="cloud"||a.includes("magic_link")?"cloud":"neutral"}function KO(t){var i;if(!t||t.length===0)return null;let a=null,r=null;for(const u of t){const f=(i=u.intervals)==null?void 0:i.yearly;f!=null&&f.available&&typeof f.price=="number"&&f.price>0&&(a=a===null?f.price:Math.min(a,f.price)),typeof u.price_month=="number"&&u.price_month>0&&(r=r===null?u.price_month:Math.min(r,u.price_month))}return a!==null?`Plans from $${a} a year.`:r!==null?`Plans from $${r} a month.`:null}const GO="Three months";function YO(t){const a=typeof t=="string"?t.trim():"";return`${a&&a.length<=40?a:GO} free, no card.`}function PO(){const[t,a]=b.useState(()=>UO());b.useEffect(()=>{let i=!0;return zO(),mS(void 0,u=>{i&&a(u)}).then(u=>{i&&a(u)}),()=>{i=!1}},[]);const r=IO(t);return r==="hub"&&(t!=null&&t.auth)?c.jsx(ZO,{auth:t.auth,signupPath:t.signup_path}):r==="cloud"?c.jsx(XO,{plans:t==null?void 0:t.plans,trialLengthLabel:t==null?void 0:t.trial_length_label}):c.jsx(FO,{})}function FO(){return c.jsxs(Tl,{children:[c.jsx(Ps,{size:60,className:"mx-auto mb-6 drop-in"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),c.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",c.jsx("span",{className:"accent-word",children:"land."})]}),c.jsx("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:"Sign in to your parachute."}),c.jsx(_e,{to:"/add",className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Sign in →"})]})}function XO({plans:t,trialLengthLabel:a}){const r=Mr(),[i]=Qh(),u=i.get("link")==="expired",[f,h]=b.useState(lE()??""),[m,p]=b.useState(!1),[y,S]=b.useState(null),v=/.+@.+\..+/.test(f.trim()),x=KO(t),T=YO(a);async function j(_){if(_.preventDefault(),!(!v||m)){p(!0),S(null);try{const C=await xl();await iN(f.trim(),C.csrf,pS),ax(f.trim()),r("/check-email")}catch(C){p(!1),S(C instanceof Error?`Couldn't send the link: ${C.message}`:"Couldn't send the link. Please try again.")}}}return c.jsxs(Tl,{children:[c.jsx(Ps,{size:60,className:"mx-auto mb-6 drop-in"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),c.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",c.jsx("span",{className:"accent-word",children:"land."})]}),u?c.jsxs("p",{className:"mx-auto mb-6 max-w-sm rounded-xl border border-sun bg-sun-soft px-4 py-3 text-sm text-sun-ink",children:["That link has ",c.jsx("span",{className:"font-serif italic",children:"expired."})," No harm done — we'll send a fresh one."]}):null,c.jsx("form",{onSubmit:j,className:"mx-auto w-full max-w-sm",children:c.jsxs("div",{className:"composer flex flex-col gap-3 p-4 text-left",children:[c.jsx("label",{htmlFor:"email",className:"eyebrow",children:"Sign in or create your account"}),c.jsx("input",{id:"email",type:"email",inputMode:"email",autoComplete:"email",autoFocus:!0,value:f,onChange:_=>h(_.target.value),placeholder:"you@example.com","aria-label":"Email address",className:"input input-on-bg"}),c.jsx("button",{type:"submit",disabled:!v||m,className:"btn btn-primary btn-lg justify-center rounded-full shadow-soft",children:m?"Sending your link…":"Email me a sign-in link"})]})}),c.jsx("p",{className:"mx-auto mt-3 max-w-sm font-round text-sm text-fg-muted",children:"One link does both — if you're new, it creates your account, and the email will say so. No password."}),c.jsxs("p",{className:"mx-auto mt-3 max-w-sm font-round text-xs text-fg-dim",children:[T,x?` ${x}`:""]}),y?c.jsx("p",{className:"mx-auto mt-3 max-w-sm rounded-lg border border-danger-border bg-danger-soft px-3 py-2 text-sm text-danger",children:y}):null,c.jsx(gS,{})]})}function ZO({auth:t,signupPath:a}){const r=Mr(),[i,u]=b.useState(!1),f=typeof window<"u"?window.location.host:"";async function h(){if(!i){u(!0);try{const p=await I0(window.location.origin)??window.location.origin,{authorizeUrl:y}=await pm(p);window.location.assign(y)}catch{u(!1),r("/add")}}}function m(){const p=encodeURIComponent(px(pS));window.location.assign(`${t.signin_path}?next=${p}`)}return c.jsxs(Tl,{children:[c.jsx(Ps,{size:60,className:"mx-auto mb-6 drop-in"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),c.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",c.jsx("span",{className:"accent-word",children:"land."})]}),c.jsxs("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:["Sign in to ",c.jsx("span",{className:"font-semibold text-fg",children:f||"your parachute"}),"."]}),c.jsx("button",{type:"button",onClick:h,disabled:i,className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:i?"Opening…":"Open your parachute →"}),c.jsx("p",{className:"mx-auto mt-6 max-w-sm font-round text-sm text-fg-muted",children:c.jsx("button",{type:"button",onClick:m,className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Manage this parachute →"})}),a?c.jsxs("p",{className:"mx-auto mt-3 max-w-sm font-round text-sm text-fg-muted",children:["New here?"," ",c.jsx("a",{href:a,className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Create your account →"})]}):c.jsx("p",{className:"mx-auto mt-3 max-w-sm font-round text-xs text-fg-dim",children:"Accounts on this parachute are created by its operator."}),c.jsx(gS,{})]})}function JO({email:t,username:a,vaults:r}){const i=Mr(),[u,f]=b.useState(!1),h=r.length===1?r[0]:null;async function m(){if(!(!h||u)){f(!0);try{await Do(h.name),bm(h.name),i("/")}catch{i("/welcome",{replace:!0})}}}async function p(){try{const y=await xl();await fN(y.csrf)}finally{Oh(),i("/",{replace:!0}),window.location.assign("/")}}return c.jsxs(Tl,{children:[c.jsx(Ps,{size:56,className:"mx-auto mb-6"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Signed in"}),c.jsxs("h1",{className:"hero-title mb-6",style:{fontSize:"clamp(1.8rem, 4vw, 2.4rem)"},children:["You're already signed in as"," ",c.jsx("span",{className:"accent-word",children:t??a??"your account"}),"."]}),c.jsxs("div",{className:"flex flex-col items-center gap-4",children:[h?c.jsx("button",{type:"button",onClick:m,disabled:u,className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:u?`Opening ${h.name}…`:`Open ${h.name} →`}):c.jsx(_e,{to:"/welcome",className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Choose a vault →"}),c.jsx("button",{type:"button",onClick:p,className:"font-round text-sm font-semibold text-fg-dim hover:text-accent",children:"Not you? Sign out"})]})]})}function WO({message:t,onRetry:a}){return c.jsxs(Tl,{children:[c.jsx(Ps,{size:56,className:"mx-auto mb-6"}),c.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Almost there"}),c.jsxs("h1",{className:"hero-title mb-4",style:{fontSize:"clamp(1.8rem, 4vw, 2.4rem)"},children:["You're signed in — we just couldn't fetch your ",c.jsx("span",{className:"accent-word",children:"vaults."})]}),c.jsx("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:t}),c.jsx("button",{type:"button",onClick:()=>a?a():window.location.reload(),className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Try again"})]})}function eM({tags:t,input:a,onInputChange:r,onAdd:i,onRemove:u}){return c.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-sm",children:[c.jsx("span",{className:"shrink-0 text-xs uppercase tracking-wider text-fg-dim",children:"Tags"}),t.map(f=>c.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-full border border-border bg-bg/60 px-2 py-0.5 text-xs text-fg-muted",children:[c.jsx("span",{className:"min-w-0 break-all",children:f}),c.jsx("button",{type:"button",onClick:()=>u(f),"aria-label":`Remove tag ${f}`,className:"text-fg-dim hover:text-red-400",children:"×"})]},f)),c.jsx("input",{type:"text",value:a,onChange:f=>r(f.target.value),onKeyDown:f=>{f.key==="Enter"||f.key===","?(f.preventDefault(),i(a)):f.key==="Backspace"&&a===""&&t.length>0&&u(t[t.length-1])},onBlur:()=>{a.trim()&&i(a)},placeholder:"add tag…",className:"min-w-24 flex-1 rounded-lg border border-transparent bg-transparent px-1 py-0.5 text-xs text-fg focus:border-border focus:outline-none","aria-label":"Add tag"})]})}function So(t){return t.trim().replace(/^#/,"")}function tM({capability:t,className:a="mb-4 text-xs text-fg-dim"}){const r=typeof(t==null?void 0:t.minutes_remaining)=="number";return c.jsx("p",{className:a,"data-testid":"voice-unavailable",children:r?"Voice transcription comes with the Voice plan.":"Voice transcription isn't enabled on this vault."})}const nM=["audio/webm;codecs=opus","audio/mp4","audio/ogg;codecs=opus"],aM=32e3;function n5(t=nM){if(typeof MediaRecorder>"u")return null;for(const a of t)if(MediaRecorder.isTypeSupported(a))return a;return null}function rM(t){return t.startsWith("audio/webm")?"webm":t.startsWith("audio/mp4")?"m4a":t.startsWith("audio/ogg")?"ogg":t.startsWith("audio/wav")?"wav":"bin"}function a5(t){const a=t.now??(()=>Date.now()),r=t.releaseStreamOnStop??!0,i=t.MediaRecorderCtor??MediaRecorder,u=new i(t.stream,{mimeType:t.mimeType,audioBitsPerSecond:aM}),f=[];let h="idle",m=0,p=0;u.ondataavailable=S=>{S.data&&S.data.size>0&&f.push(S.data),t.onData&&t.onData(f.reduce((v,x)=>v+x.size,0))};const y=()=>{if(r)for(const S of t.stream.getTracks())S.stop()};return{get state(){return h},get mimeType(){return t.mimeType},start(){if(h!=="idle")throw new Error(`Cannot start from ${h}`);u.start(t.dataIntervalMs),m=a(),h="recording"},pause(){h==="recording"&&(u.pause(),p+=a()-m,h="paused")},resume(){h==="paused"&&(u.resume(),m=a(),h="recording")},async stop(){if(h==="idle"||h==="stopped")throw new Error(`Cannot stop from ${h}`);h==="recording"&&(p+=a()-m);const S=new Promise(v=>{u.onstop=async()=>{const x=await iM(f);v({data:x,mimeType:t.mimeType,durationMs:p})}});return u.stop(),h="stopped",y(),S},cancel(){if(h==="recording"||h==="paused")try{u.stop()}catch{}h="stopped",f.length=0,y()}}}async function sM(t){const a=t;return typeof a.arrayBuffer=="function"?a.arrayBuffer():new Promise((r,i)=>{const u=new FileReader;u.onload=()=>r(u.result),u.onerror=()=>i(u.error??new Error("FileReader error")),u.readAsArrayBuffer(t)})}async function iM(t){if(t.length===0)return new ArrayBuffer(0);const a=await Promise.all(t.map(f=>sM(f))),r=a.reduce((f,h)=>f+h.byteLength,0),i=new Uint8Array(r);let u=0;for(const f of a)i.set(new Uint8Array(f),u),u+=f.byteLength;return i.buffer}async function r5(){var t;if(typeof navigator>"u"||!((t=navigator.mediaDevices)!=null&&t.getUserMedia)){const a=new Error("Microphone is not available in this browser.");throw a.kind="unavailable",a}try{return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(a){const r=new Error(a instanceof Error?a.message:"Microphone permission denied."),i=a instanceof DOMException?a.name:"";throw r.kind=i==="NotFoundError"||i==="OverconstrainedError"?"no-device":"permission-denied",r}}function s5(t,a=new Date,r){const i=a.toISOString().replace(/[:.]/g,"-").replace(/Z$/,""),u=r&&r>0?`-part${r}`:"";return`memo-${i}${u}.${rM(t)}`}function Nb(t=new Date){const a=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),u=String(t.getHours()).padStart(2,"0"),f=String(t.getMinutes()).padStart(2,"0"),h=String(t.getSeconds()).padStart(2,"0");return`Notes/${a}/${r}-${i}/${u}-${f}-${h}`}const lM=/(?:^|\s)#([a-zA-Z][\w-]*)/g;function uM(t){const a=new Set;for(const r of t.matchAll(lM)){const i=So(r[1]??"");i&&a.add(i)}return[...a]}function oM(t){const a=Array.from(new Set([...t.tags,...uM(t.content)].filter(i=>i.length>0))),r={content:t.content,path:t.path.trim(),metadata:{source:"text"}};return a.length&&(r.tags=a),r}function cM(t,a,r,i,u=600){const f=b.useRef(r);f.current=r;const h=b.useRef(i);h.current=i;const m=b.useMemo(()=>JSON.stringify(r),[r]);b.useEffect(()=>{if(!t||!a)return;if(!i){Gx(t,a);return}const p=window.setTimeout(()=>Id(t,a,f.current),u);return()=>window.clearTimeout(p)},[m,i,t,a,u]),b.useEffect(()=>{if(!t||!a)return;const p=()=>{h.current&&Id(t,a,f.current)},y=()=>{document.visibilityState==="hidden"&&p()};return window.addEventListener("pagehide",p),document.addEventListener("visibilitychange",y),()=>{window.removeEventListener("pagehide",p),document.removeEventListener("visibilitychange",y)}},[t,a])}const fM={tags:[{name:"capture",description:"Notes captured directly by the user (text or voice)."}]};function dM(t,a){const r=t??[],i=a??[];if(r.length!==i.length)return!1;for(let u=0;u<r.length;u++)if(r[u]!==i[u])return!1;return!0}function hM(t,a){if(!a)return{name:t.name,status:"missing",expected:t,actual:null,differences:[]};const r=[];(a.description??"")!==t.description&&r.push("description");const i=t.parent_names??null;return dM(a.parent_names,i)||r.push("parent_names"),{name:t.name,status:r.length===0?"ok":"misaligned",expected:t,actual:a,differences:r}}async function mM(t){const a=await t.listTagsWithSchema(),r=new Map(a.map(h=>[h.name,h])),i=fM.tags.map(h=>hM(h,r.get(h.name))),u=i.filter(h=>h.status==="missing"),f=i.filter(h=>h.status==="misaligned");return{ok:u.length===0&&f.length===0,missing:u,misaligned:f,rows:i}}const Dd=new Set;async function pM(t,a){for(const r of a)await t.updateTag(r.name,{description:r.description,...r.parent_names?{parent_names:r.parent_names}:{}})}async function gM(t,a){if(!Dd.has(t)){Dd.add(t);try{const i=(await mM(a)).missing.map(u=>u.expected);i.length>0&&await pM(a,i)}catch(r){Dd.delete(t),typeof console<"u"&&console.warn(`[schema-ensure] failed to ensure required schema for vault ${t}:`,r)}}}const yS="home-composer-input";function vS({vault:t,focused:a=!1}){var ee;const r=aa(M=>M.push),i=z_(),u=ke(),{roles:f}=wl(t.id),h=H0(),m=((ee=h.capability)==null?void 0:ee.enabled)===!1,p=b.useRef(Nb()),[y]=b.useState(()=>nN(t.id,Xu)),[S,v]=b.useState(()=>y?{...y.body,path:y.body.path||p.current}:{content:"",path:p.current,tags:[]}),[x,T]=b.useState(!1),[j,_]=b.useState(null),[C,O]=b.useState(""),B=b.useRef(y!==null),H=b.useRef(null);b.useEffect(()=>{B.current||(v(M=>{const P=H.current?M.tags.filter(oe=>oe!==H.current):M.tags,ne=P.includes(f.captureText)?P:[...P,f.captureText];return ne===M.tags?M:{...M,tags:ne}}),H.current=f.captureText)},[f.captureText]);const k=!B.current&&(S.tags.length===0||S.tags.length===1&&S.tags[0]===f.captureText),Y=S.content.trim().length>0||!k||S.path.trim().length>0&&S.path!==p.current;cM(t.id,Xu,S,Y);const Q=b.useRef(S);Q.current=S;const G=b.useRef(Y);G.current=Y;const F=b.useCallback(()=>{G.current&&Id(t.id,Xu,Q.current)},[t.id]);b.useEffect(()=>()=>F(),[F]);const Z=b.useRef(null);b.useEffect(()=>{const M=Z.current;M&&(M.style.height="",S.content&&(M.style.height=`${M.scrollHeight}px`))},[S.content]);const le=x||S.content.length>0,de=S.content.trim().length>0&&S.path.trim().length>0&&!i.isPending,ye=M=>{const P=So(M);!P||S.tags.includes(P)||(B.current=!0,v(ne=>({...ne,tags:[...ne.tags,P]})),O(""))},we=M=>{B.current=!0,v(P=>({...P,tags:P.tags.filter(ne=>ne!==M)}))},re=()=>{de&&(u&&gM(t.id,u),_(null),i.mutate(oM({content:S.content,path:S.path,tags:S.tags}),{onSuccess:()=>{var M;Gx(t.id,Xu),p.current=Nb(),B.current=!1,H.current=f.captureText,O(""),v({content:"",path:p.current,tags:[f.captureText]}),(M=Z.current)==null||M.blur(),T(!1),r(`Saved to ${t.name}`,"success")},onError:M=>{_(M instanceof Uo?"Session expired. Reconnect to save.":M instanceof Error?M.message:"Couldn't save — try again.")}}))};return c.jsxs("form",{"aria-label":"Write a note",className:`composer mb-6 px-5 py-4 ${a?"composer-focus":""}`,onSubmit:M=>{M.preventDefault(),re()},onFocus:()=>T(!0),onBlur:M=>{F(),M.currentTarget.contains(M.relatedTarget)||T(!1)},children:[c.jsx("textarea",{id:yS,ref:Z,rows:1,value:S.content,onChange:M=>v(P=>({...P,content:M.target.value})),onKeyDown:M=>{(M.metaKey||M.ctrlKey)&&M.key==="Enter"&&(M.preventDefault(),re())},"aria-label":"What's on your mind?",placeholder:"What's on your mind?",className:"block max-h-[45vh] w-full resize-none overflow-y-auto border-0 bg-transparent text-fg text-lg outline-none [transition:min-height_var(--dur-move)_ease] placeholder:text-fg-dim",style:{minHeight:le?"6.5rem":"1.75rem"}}),le?c.jsx("div",{className:"mt-2",children:c.jsx(eM,{tags:S.tags,input:C,onInputChange:O,onAdd:ye,onRemove:we})}):null,c.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[le?c.jsx(_e,{to:"/new",onClick:F,className:"focus-ring rounded text-fg-dim text-xs hover:text-accent",children:"Open full editor →"}):c.jsxs("span",{className:"font-round text-fg-dim text-xs",children:["Autosaves to ",t.name]}),c.jsxs("div",{className:"flex items-center gap-2",children:[le?c.jsx("button",{type:"submit",disabled:!de,className:"btn btn-primary btn-touch",title:"Save (⌘⏎)",children:i.isPending?"Saving…":`Save to ${t.name}`}):null,m?null:c.jsx(_e,{to:"/new?voice=1",onClick:F,"aria-label":"Record a voice note",className:"focus-ring grid h-9 w-9 shrink-0 place-items-center rounded-full border border-border bg-bg-soft text-base transition-colors duration-(--dur-quick) ease-out hover:border-accent/50 hover:bg-accent/10",children:c.jsx("span",{"aria-hidden":"true",children:"🎙"})})]})]}),m&&le?c.jsx(tM,{capability:h.capability,className:"mt-2 text-xs text-fg-dim"}):null,j?c.jsx("p",{role:"alert",className:"mt-2 text-danger text-xs",children:j}):null]})}function bS(){const t=Sm(),a=Ge(),r=t.find(i=>i.id==="notes");return!r||r.items.length===0?null:c.jsx("nav",{"aria-label":"Lenses",className:"-mx-5 mb-6 flex gap-2 overflow-x-auto px-5 pb-1 md:-mx-8 md:px-8 lg:hidden",children:r.items.map(i=>{const u=i.match(a);return c.jsx(_e,{to:i.to,"data-nav-item":i.id,"aria-current":u?"page":void 0,className:`focus-ring shrink-0 whitespace-nowrap rounded-full border px-3.5 py-1.5 font-round text-sm transition-colors ${u?"border-transparent bg-grass-soft font-semibold text-grass-ink":"border-border bg-card font-medium text-fg-muted hover:text-fg"}`,children:i.label},i.id)})})}const yM={mcp:"MCP",api:"API",cli:"CLI",operator:"operator"};function Ab(t){const a=yM[t];if(a)return a;if(t.startsWith("agent:"))return"agent";if(t.startsWith("surface:")){const r=t.slice(8);return r?r.charAt(0).toUpperCase()+r.slice(1):"surface"}return t}function vM(t){const a=t.createdVia?`via ${Ab(t.createdVia)}`:null,r=t.lastUpdatedVia?`via ${Ab(t.lastUpdatedVia)}`:null;if(!a&&!r)return null;const i=t.createdBy??t.createdVia??null,u=t.lastUpdatedBy??t.lastUpdatedVia??null,f=u!==null&&u!==i,h=f&&a&&r?`created ${a} · updated ${r}`:a??r??"",m=[t.createdBy?`createdBy: ${t.createdBy}`:null,t.createdVia?`createdVia: ${t.createdVia}`:null,t.lastUpdatedBy?`lastUpdatedBy: ${t.lastUpdatedBy}`:null,t.lastUpdatedVia?`lastUpdatedVia: ${t.lastUpdatedVia}`:null].filter(p=>!!p).join(" · ");return{compact:h,created:a,updated:r,differs:f,raw:m}}function bM({note:t,variant:a="compact",className:r}){const i=vM(t);return i?a==="detail"?c.jsxs("div",{className:`space-y-0.5 text-xs text-fg-dim${r?` ${r}`:""}`,title:i.raw,children:[i.created?c.jsxs("p",{children:["created ",i.created]}):null,i.updated&&i.differs?c.jsxs("p",{children:["updated ",i.updated]}):null]}):c.jsx("span",{className:`shrink-0 text-xs text-fg-dim${r?` ${r}`:""}`,title:i.raw,children:i.compact}):null}function xS({note:t,pinnedTag:a,archivedTag:r,trailing:i,footer:u}){const f=dh(t),h=!!t.path&&t.path.replace(/\.md$/i,"")!==f.text,m=t.updatedAt??t.createdAt,p=(t.tags??[]).includes(a),y=(t.tags??[]).includes(r);return c.jsxs("li",{className:y?"opacity-60 italic":void 0,children:[c.jsxs("div",{className:"note-row items-stretch","data-note-id":t.id,children:[c.jsx("span",{"aria-hidden":"true",className:"note-dot"}),c.jsxs(_e,{to:`/n/${encodeURIComponent(t.id)}`,className:"focus-ring block min-h-11 min-w-0 flex-1 md:min-h-0",children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[c.jsxs("span",{className:"flex min-w-0 items-baseline gap-1.5",children:[p?c.jsx("span",{className:"shrink-0 text-accent","aria-label":"pinned",title:"pinned",children:"★"}):null,c.jsx("span",{className:f.kind==="timestamp"?"min-w-0 truncate text-base title-timestamp":"min-w-0 truncate text-base font-medium text-fg",children:f.text})]}),c.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[c.jsx("span",{className:"text-xs tabular-nums text-fg-dim",children:Tm(m)}),c.jsx(bM,{note:t})]})]}),h?c.jsx("p",{className:"mt-0.5 min-w-0 truncate note-id",children:t.path}):null,t.preview?c.jsx("p",{className:"mt-1 truncate text-sm text-fg-muted",children:t.preview}):null,t.tags&&t.tags.length>0?c.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:t.tags.map(S=>c.jsxs("span",{className:"chip chip-tag max-w-full break-all",children:["#",S]},S))}):null]}),i?c.jsx("div",{className:"shrink-0 self-center",children:i}):null]}),u?c.jsx("div",{className:"pl-4",children:u}):null]})}function SS({children:t,"aria-label":a}){return c.jsx("ol",{"aria-label":a,className:"flex flex-col gap-0.5",children:t})}const xM="lens:path-tree-expanded:";function wS(t){return xM+t}function _b(t){try{const a=localStorage.getItem(wS(t));if(!a)return new Set;const r=JSON.parse(a);return Array.isArray(r)?new Set(r.filter(i=>typeof i=="string")):new Set}catch{return new Set}}function SM(t,a){try{localStorage.setItem(wS(t),JSON.stringify([...a].sort()))}catch{}}function wM(t){const[a,r]=b.useState(()=>t?_b(t):new Set);b.useEffect(()=>{r(t?_b(t):new Set)},[t]);const i=b.useCallback(u=>{t&&r(f=>{const h=new Set(f);return h.has(u)?h.delete(u):h.add(u),SM(t,h),h})},[t]);return{expanded:a,toggle:i}}function EM(t,a){return{name:t,fullPath:a,count:0,children:[],childMap:new Map}}function ES(t){const a=t.split("/").filter(r=>r.length>0);return a.length<=1?[]:a.slice(0,-1)}function TM(t){const a=new Map;for(const i of t){if(!i)continue;const u=ES(i);if(u.length===0)continue;let f=a,h="";for(const m of u){h=h?`${h}/${m}`:m;let p=f.get(m);p||(p=EM(m,h),f.set(m,p)),p.count+=1,f=p.childMap}}const r=i=>i.map(u=>({name:u.name,fullPath:u.fullPath,count:u.count,children:r([...u.childMap.values()])})).sort((u,f)=>u.name.localeCompare(f.name));return r([...a.values()])}const jM=5,NM=20;function AM(t){const a=new Set;let r=0;for(const i of t){if(!i)continue;const u=ES(i);if(u.length!==0&&(r+=1,a.add(u[0]),a.size>=jM||r>=NM))return!0}return!1}function _M({paths:t,vaultId:a,currentPrefix:r,onSelect:i}){const u=b.useMemo(()=>TM(t),[t]),{expanded:f,toggle:h}=wM(a),m=b.useMemo(()=>RM(r),[r]);return u.length===0?c.jsxs("aside",{"aria-label":"Path tree",children:[c.jsx("h2",{className:"mb-2 text-xs uppercase tracking-wider text-fg-dim",children:"Folders"}),c.jsx("p",{className:"text-xs text-fg-dim",children:"No folders yet."})]}):c.jsxs("aside",{"aria-label":"Path tree",className:"md:sticky md:top-6 md:self-start",children:[c.jsxs("div",{className:"mb-2 flex items-baseline justify-between",children:[c.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"Folders"}),r?c.jsx("button",{type:"button",onClick:()=>i(""),className:"text-xs text-fg-dim hover:text-accent",children:"Clear"}):null]}),c.jsx("ul",{className:"space-y-0.5",children:u.map(p=>c.jsx(TS,{node:p,depth:0,expanded:f,forcedOpen:m,currentPrefix:r,onToggle:h,onSelect:i},p.fullPath))})]})}function TS({node:t,depth:a,expanded:r,forcedOpen:i,currentPrefix:u,onToggle:f,onSelect:h}){const m=t.children.length>0,p=r.has(t.fullPath)||i.has(t.fullPath),y=u===t.fullPath;return c.jsxs("li",{children:[c.jsxs("div",{className:`flex items-center gap-1 rounded-lg px-1 py-0.5 text-sm ${y?"bg-accent/10 text-accent":"text-fg-muted hover:text-accent"}`,style:{paddingLeft:`${a*.75+.25}rem`},children:[m?c.jsx("button",{type:"button",onClick:()=>f(t.fullPath),"aria-label":`${p?"Collapse":"Expand"} ${t.fullPath}`,"aria-expanded":p,className:"flex h-4 w-4 items-center justify-center text-fg-dim hover:text-accent",children:c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:p?"▾":"▸"})}):c.jsx("span",{"aria-hidden":"true",className:"inline-block h-4 w-4"}),c.jsxs("button",{type:"button",onClick:()=>h(t.fullPath),"aria-current":y?"true":void 0,className:"flex flex-1 items-baseline gap-1.5 truncate text-left",children:[c.jsx("span",{className:"truncate",children:t.name}),c.jsx("span",{className:"text-xs text-fg-dim",children:t.count})]})]}),m&&p?c.jsx("ul",{className:"space-y-0.5",children:t.children.map(S=>c.jsx(TS,{node:S,depth:a+1,expanded:r,forcedOpen:i,currentPrefix:u,onToggle:f,onSelect:h},S.fullPath))}):null]})}function RM(t){const a=new Set;if(!t)return a;const r=t.split("/").filter(u=>u.length>0);let i="";for(const u of r)i=i?`${i}/${u}`:u,a.add(i);return a}function ul(t){return t<10?`0${t}`:String(t)}function qo(t=new Date){return`${t.getFullYear()}-${ul(t.getMonth()+1)}-${ul(t.getDate())}`}function jS(t){if(!t)return null;const a=new Date(t);return Number.isNaN(a.getTime())?null:qo(a)}function wo(t){if(!t||!/^\d{4}-\d{2}-\d{2}$/.test(t))return null;const[a,r,i]=t.split("-").map(Number),u=new Date(a,r-1,i);return Number.isNaN(u.getTime())?null:u}function NS(t,a){const r=wo(t);return r?(r.setDate(r.getDate()+a),`${r.getFullYear()}-${ul(r.getMonth()+1)}-${ul(r.getDate())}`):t}function i5(t=new Date){return`${t.getFullYear()}-${ul(t.getMonth()+1)}`}function l5(t){if(!t||!/^\d{4}-\d{2}$/.test(t))return null;const[a,r]=t.split("-").map(Number);return r<1||r>12?null:{year:a,month:r}}function u5(t,a,r){const i=t*12+(a-1)+r;return{year:Math.floor(i/12),month:i%12+1}}function o5(t,a){const i=new Date(t,a-1,1).getDay(),u=new Date(t,a-1,1-i),f=[];for(let h=0;h<42;h++)f.push(new Date(u.getFullYear(),u.getMonth(),u.getDate()+h));return f}function c5(t,a=new Date){var h;const r=((h=t.match(/^\d{4}-\d{2}-\d{2}/))==null?void 0:h[0])??null,i=wo(r);if(!i)return t;const u=wo(qo(a));if(!u)return t;const f=Math.round((i.getTime()-u.getTime())/864e5);return f===0?"Today":f===-1?"Yesterday":f===1?"Tomorrow":i.toLocaleDateString(void 0,i.getFullYear()===a.getFullYear()?{month:"short",day:"numeric"}:{month:"short",day:"numeric",year:"numeric"})}function CM(t){const a=wo(t);return a?a.toLocaleDateString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"}):t}function f5(t,a){return new Date(t,a-1,1).toLocaleDateString(void 0,{year:"numeric",month:"long"})}function OM(t){const a=new Map;for(const i of t){const u=jS(i.updatedAt??i.createdAt);if(!u)continue;const f=a.get(u);f?f.push(i):a.set(u,[i])}const r=i=>i.updatedAt??i.createdAt;return Array.from(a.entries()).sort(([i],[u])=>i<u?1:i>u?-1:0).map(([i,u])=>({key:i,notes:u.sort((f,h)=>r(f)<r(h)?1:r(f)>r(h)?-1:0)}))}function MM(t){const a=qo();return t===a?"Today":t===NS(a,-1)?"Yesterday":CM(t)}function jm({children:t}){return c.jsxs("h2",{className:"eyebrow mb-2 flex items-center gap-3",children:[c.jsx("span",{className:"shrink-0",children:t}),c.jsx("span",{"aria-hidden":"true",className:"h-px flex-1 bg-border"})]})}function DM({notes:t}){const a=ae(u=>u.getActiveVault()),{roles:r}=wl((a==null?void 0:a.id)??null),i=b.useMemo(()=>OM(t),[t]);return c.jsx("div",{className:"space-y-8",children:i.map(u=>c.jsxs("section",{children:[c.jsx(jm,{children:c.jsx(_e,{to:`/today?date=${u.key}`,className:"hover:text-accent",children:MM(u.key)})}),c.jsx(SS,{children:u.notes.map(f=>c.jsx(xS,{note:f,pinnedTag:r.pinned,archivedTag:r.archived},f.id))})]},u.key))})}const Nm="application/x-parachute-note";function AS(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(pointer: fine)").matches}function kM(t,a){t.setData(Nm,a),t.effectAllowed="move"}function eo(t){return t?Array.from(t.types??[]).includes(Nm):!1}function LM(t){if(!t)return null;const a=t.getData(Nm);return a===""?null:a}function d5(t){const[a]=b.useState(AS),r=b.useRef(!1),i=b.useCallback(h=>{h.dataTransfer&&(kM(h.dataTransfer,t),r.current=!0)},[t]),u=b.useCallback(()=>{window.setTimeout(()=>{r.current=!1},0)},[]),f=b.useCallback(h=>{r.current&&(h.preventDefault(),h.stopPropagation(),r.current=!1)},[]);return a?{canDrag:!0,sourceProps:{draggable:!0,onDragStart:i,onDragEnd:u,onClickCapture:f}}:{canDrag:!1,sourceProps:{}}}function h5(t){const[a,r]=b.useState(!1),i=b.useRef(0),u=b.useCallback(p=>{eo(p.dataTransfer)&&(p.preventDefault(),i.current+=1,r(!0))},[]),f=b.useCallback(p=>{eo(p.dataTransfer)&&(p.preventDefault(),p.dataTransfer&&(p.dataTransfer.dropEffect="move"))},[]),h=b.useCallback(p=>{eo(p.dataTransfer)&&(i.current=Math.max(0,i.current-1),i.current===0&&r(!1))},[]),m=b.useCallback(p=>{if(!eo(p.dataTransfer))return;p.preventDefault(),i.current=0,r(!1);const y=LM(p.dataTransfer);y&&t(y)},[t]);return{isOver:a,targetProps:{onDragEnter:u,onDragOver:f,onDragLeave:h,onDrop:m}}}function m5(){const t=b.useRef(new Map),a=b.useCallback((i,u)=>(t.current.set(i,u),()=>{t.current.get(i)===u&&t.current.delete(i)}),[]),r=b.useCallback((i,u)=>{var f;(f=t.current.get(i))==null||f(u)},[]);return{register:a,dispatch:r}}const UM=10;function Eo(t){return Object.keys(t.fields??{}).length}function zM(t,a){const r=new Map;for(const p of t){const y=p.name.indexOf("/");if(y>0){const S=p.name.slice(0,y),v=r.get(S)??[];v.push(p),r.set(S,v)}}const i=new Set;for(const[p,y]of r)y.length>=2&&i.add(p);const u=new Map,f=[];for(const p of t){const y=p.name.indexOf("/"),S=y>0?p.name.slice(0,y):p.name;if(y>0&&i.has(S)){let x=u.get(S);x||(x={kind:"group",prefix:S,totalCount:0,children:[]},u.set(S,x)),x.children.push({...p,pinned:a.has(p.name)}),x.totalCount+=p.count??0}else if(i.has(p.name)){let x=u.get(p.name);x||(x={kind:"group",prefix:p.name,totalCount:0,children:[]},u.set(p.name,x)),x.selfTag={...p,pinned:a.has(p.name)},x.totalCount+=p.count??0}else f.push({kind:"leaf",name:p.name,label:p.name,count:p.count??0,pinned:a.has(p.name),fields:p.fields})}for(const p of u.values())p.children.sort((y,S)=>y.pinned!==S.pinned?y.pinned?-1:1:(S.count??0)-(y.count??0)||y.name.localeCompare(S.name));const h=[...f,...Array.from(u.values())],m=p=>{var v,x;if(p.kind==="leaf")return{pinned:p.pinned,count:p.count,label:p.label};const y=(((v=p.selfTag)==null?void 0:v.pinned)??!1)||p.children.some(T=>T.pinned),S=Math.max(((x=p.selfTag)==null?void 0:x.count)??0,...p.children.map(T=>T.count??0))||0;return{pinned:y,count:S,label:p.prefix}};return h.sort((p,y)=>{const S=m(p),v=m(y);return S.pinned!==v.pinned?S.pinned?-1:1:v.count-S.count||S.label.localeCompare(v.label)}),h}function Rb(t){var a;return t.kind==="leaf"?t.pinned:(((a=t.selfTag)==null?void 0:a.pinned)??!1)||t.children.some(r=>r.pinned)}function Cb(t,a){return t.kind==="leaf"?a.has(t.name.toLowerCase()):(t.selfTag?a.has(t.selfTag.name.toLowerCase()):!1)||t.children.some(i=>a.has(i.name.toLowerCase()))}function VM(t,a,r){const i=t.filter(p=>Cb(p,a)),u=t.filter(p=>!Cb(p,a)),f=u.filter(Rb),h=u.filter(p=>!Rb(p)),m=Math.max(0,r-i.length);return[...i,...[...f,...h].slice(0,m)]}function BM({tags:t,pinnedTags:a,selected:r,onToggle:i,onClear:u,isLoading:f}){const[h,m]=b.useState(""),[p,y]=b.useState(!1),S=b.useRef(null);b.useEffect(()=>{var Q;AS()&&((Q=S.current)==null||Q.focus())},[]);const v=b.useMemo(()=>new Set(a.map(Q=>Q.toLowerCase())),[a]),x=b.useMemo(()=>new Set(r.map(Q=>Q.toLowerCase())),[r]),T=b.useMemo(()=>zM(t,v),[t,v]),j=b.useMemo(()=>VM(T,x,UM),[T,x]),[_,C]=b.useState(new Set),O=Q=>{C(G=>{const F=new Set(G);return F.has(Q)?F.delete(Q):F.add(Q),F})},B=h.trim().toLowerCase(),H=b.useMemo(()=>B?t.filter(Q=>Q.name.toLowerCase().includes(B)).sort((Q,G)=>(G.count??0)-(Q.count??0)||Q.name.localeCompare(G.name)):[],[t,B]),k=Q=>{if(Q.key!=="Enter")return;const G=H[0];G&&(Q.preventDefault(),i(G.name))},Y=Q=>Q.kind==="leaf"?c.jsx("li",{children:c.jsx(To,{name:Q.name,label:Q.label,count:Q.count,pinned:Q.pinned,active:x.has(Q.name.toLowerCase()),fieldCount:Eo(Q),onToggle:()=>i(Q.name)})},Q.name):c.jsx("li",{children:c.jsx(HM,{group:Q,isOpen:_.has(Q.prefix),onToggleOpen:()=>O(Q.prefix),selectedSet:x,onToggleTag:i})},Q.prefix);return c.jsxs("nav",{"aria-label":"Browse by tag",children:[c.jsxs("div",{className:"mb-2 flex items-baseline justify-between",children:[c.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"Tags"}),r.length>0?c.jsx("button",{type:"button",onClick:u,className:"text-xs text-fg-dim hover:text-accent",children:"Clear"}):null]}),c.jsx("input",{ref:S,type:"search",value:h,onChange:Q=>m(Q.target.value),onKeyDown:k,placeholder:"Filter tags…","aria-label":"Filter tags",className:"input mb-2 w-full text-sm"}),f?c.jsx("p",{className:"text-xs text-fg-dim",children:"Loading…"}):t.length===0?c.jsx("p",{className:"text-xs text-fg-dim",children:"No tags in this vault."}):B?H.length===0?c.jsxs("p",{className:"text-xs text-fg-dim",children:['No tags match "',h,'".']}):c.jsx("ul",{className:"max-h-[60vh] space-y-0.5 overflow-y-auto pr-1","aria-label":"Matching tags",children:H.map(Q=>c.jsx("li",{children:c.jsx(To,{name:Q.name,label:Q.name,count:Q.count??0,pinned:v.has(Q.name.toLowerCase()),active:x.has(Q.name.toLowerCase()),fieldCount:Eo(Q),onToggle:()=>i(Q.name)})},Q.name))}):c.jsxs(c.Fragment,{children:[c.jsx("ul",{className:"space-y-0.5","aria-label":"Shortlist",children:j.map(Y)}),T.length>j.length?c.jsxs("button",{type:"button",onClick:()=>y(Q=>!Q),"aria-expanded":p,className:"mt-1 flex items-center gap-1 rounded-lg px-1 py-1 text-xs text-fg-dim hover:text-accent",children:[c.jsx("span",{"aria-hidden":"true",className:"font-mono",children:p?"▾":"▸"}),"All ",t.length," tags"]}):null,p?c.jsx("ul",{className:"mt-2 max-h-[60vh] space-y-0.5 overflow-y-auto border-t border-border pr-1 pt-2","aria-label":"All tags",children:T.map(Y)}):null]})]})}function To({name:t,label:a,count:r,pinned:i,active:u,fieldCount:f,onToggle:h}){return c.jsxs("button",{type:"button",onClick:h,"aria-pressed":u,title:`#${t}`,className:`flex w-full items-center gap-1.5 rounded-lg px-2 py-1 text-left text-sm ${u?"bg-accent/15 text-accent":"text-fg-muted hover:bg-bg/60 hover:text-accent"}`,children:[i?c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-accent",children:"★"}):null,c.jsxs("span",{className:"flex-1 truncate",children:["#",a]}),f?c.jsxs("span",{className:"shrink-0 text-xs text-fg-dim",title:`${f} schema field${f===1?"":"s"}`,children:["⊞ ",f]}):null,c.jsx("span",{className:"shrink-0 text-xs text-fg-dim",children:r})]})}function HM({group:t,isOpen:a,onToggleOpen:r,selectedSet:i,onToggleTag:u}){var y;const f=t.children.some(S=>i.has(S.name.toLowerCase())),h=t.selfTag?i.has(t.selfTag.name.toLowerCase()):!1,m=a||f||h,p=(((y=t.selfTag)==null?void 0:y.pinned)??!1)||t.children.some(S=>S.pinned);return c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center gap-1 rounded-lg px-1 py-0.5",children:[c.jsx("button",{type:"button",onClick:r,"aria-expanded":m,"aria-label":`${m?"Collapse":"Expand"} ${t.prefix}`,className:"flex h-5 w-5 shrink-0 items-center justify-center text-fg-dim hover:text-accent",children:c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:m?"▾":"▸"})}),t.selfTag?c.jsx(To,{name:t.selfTag.name,label:t.prefix,count:t.totalCount,pinned:t.selfTag.pinned,active:h,fieldCount:Eo(t.selfTag),onToggle:()=>u(t.selfTag.name)}):c.jsxs("button",{type:"button",onClick:r,className:"flex flex-1 items-center gap-1.5 truncate rounded-lg px-2 py-1 text-left text-sm text-fg-muted hover:bg-bg/60 hover:text-accent",children:[p?c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-accent",children:"★"}):null,c.jsxs("span",{className:"flex-1 truncate",children:["#",t.prefix,"/"]}),c.jsx("span",{className:"shrink-0 text-xs text-fg-dim",children:t.totalCount})]})]}),m?c.jsx("ul",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:t.children.map(S=>{const v=S.name.slice(t.prefix.length+1)||S.name;return c.jsx("li",{children:c.jsx(To,{name:S.name,label:v,count:S.count??0,pinned:S.pinned,active:i.has(S.name.toLowerCase()),fieldCount:Eo(S),onToggle:()=>u(S.name)})},S.name)})}):null]})}function _S({className:t=""}){return c.jsx("output",{className:`mb-4 block rounded-md border border-border bg-card px-3 py-1.5 text-xs text-fg-muted ${t}`.trim(),children:"Offline — showing what's saved."})}function to({label:t,onRemove:a}){return c.jsxs("span",{className:"chip chip-tag-active",children:[t,c.jsx("button",{type:"button",onClick:a,"aria-label":`Remove refinement ${t}`,className:"focus-ring ml-1 rounded-full",children:"×"})]})}function jh({className:t="",width:a,height:r}){const i={};return a!==void 0&&(i.width=a),r!==void 0&&(i.height=r),c.jsx("div",{className:`skeleton ${t}`.trim(),style:Object.keys(i).length?i:void 0,"aria-hidden":"true"})}function Ob(t,a){const[r,i]=b.useState(t);return b.useEffect(()=>{const u=setTimeout(()=>i(t),a);return()=>clearTimeout(u)},[t,a]),r}function qM(t){const[a,r]=b.useState(!1),[i,u]=b.useState(t);t!==i&&(u(t),r(!1));const f=b.useCallback(()=>r(!0),[]);return{dismissed:a,dismiss:f}}const $M=["auto","always","never"],ol="auto",QM="lens:path-tree:";function RS(t){return QM+t}function IM(t){return typeof t=="string"&&$M.includes(t)?t:ol}function Mb(t){try{const a=localStorage.getItem(RS(t));if(!a)return ol;const r=JSON.parse(a);return IM(r.mode)}catch{return ol}}function KM(t,a){try{localStorage.setItem(RS(t),JSON.stringify({mode:a}))}catch{}}function GM(t){const[a,r]=b.useState(()=>t?Mb(t):ol);b.useEffect(()=>{r(t?Mb(t):ol)},[t]);const i=b.useCallback(u=>{t&&(KM(t,u),r(u))},[t]);return{mode:a,setMode:i}}const jo="UI/Views/",CS="saved-view";function YM(t){var r,i;const a={};return(r=t.search)!=null&&r.trim()&&(a.search=t.search.trim()),t.tags&&t.tags.length>0&&(a.tags=[...t.tags]),t.tags&&t.tags.length>1&&t.tagMatch&&(a.tagMatch=t.tagMatch),(i=t.pathPrefix)!=null&&i.trim()&&(a.pathPrefix=t.pathPrefix.trim()),t.sort&&(a.sort=t.sort),t.showArchived&&(a.showArchived=!0),{kind:CS,filters:a}}function PM(t){const a=t.metadata;if(!a||a.kind!==CS)return null;const r=a.filters??{},i=FM(t.path)??t.id;return{id:t.id,name:i,filters:{search:typeof r.search=="string"?r.search:void 0,tags:Array.isArray(r.tags)?r.tags.filter(u=>typeof u=="string"):void 0,tagMatch:r.tagMatch==="all"?"all":r.tagMatch==="any"?"any":void 0,pathPrefix:typeof r.pathPrefix=="string"?r.pathPrefix:void 0,sort:r.sort==="asc"?"asc":r.sort==="desc"?"desc":void 0,showArchived:r.showArchived===!0},updatedAt:t.updatedAt}}function FM(t){return!t||!t.startsWith(jo)?null:t.slice(jo.length).replace(/\.md$/i,"")||null}function XM(t){const a=t.trim().replace(/[/\\]/g,"-");return`${jo}${a}`}function Nh(t){var r,i;const a=new URLSearchParams;(r=t.search)!=null&&r.trim()&&a.set("search",t.search.trim());for(const u of t.tags??[])a.append("tag",u);return t.tagMatch&&a.set("tag_match",t.tagMatch),(i=t.pathPrefix)!=null&&i.trim()&&a.set("path_prefix",t.pathPrefix.trim()),t.sort&&a.set("sort",t.sort),t.showArchived&&a.set("show_archived","1"),a}function Db(t){const a=t.getAll("tag"),r=t.get("tag_match"),i=t.get("sort");return{search:t.get("search")??void 0,tags:a.length>0?a:void 0,tagMatch:r==="all"?"all":r==="any"?"any":void 0,pathPrefix:t.get("path_prefix")??void 0,sort:i==="asc"?"asc":i==="desc"?"desc":void 0,showArchived:t.get("show_archived")==="1"}}function ZM(t){var a,r;return!!((a=t.search)!=null&&a.trim()||t.tags&&t.tags.length>0||(r=t.pathPrefix)!=null&&r.trim())}function JM(t,a){t.invalidateQueries({queryKey:["savedViews",a]}),t.invalidateQueries({queryKey:["notes",a]}),t.invalidateQueries({queryKey:["tags",a]}),t.invalidateQueries({queryKey:["vaultInfo",a]})}function WM(t){const a=ke(),r=ae(i=>i.activeVaultId);return lt({queryKey:["savedViews",r,t],enabled:!!a&&!!t,queryFn:async()=>{const i=new URLSearchParams;return i.set("tag",t),i.set("path_prefix",jo),i.set("sort","asc"),(await a.queryNotes(i)).map(f=>PM(f)).filter(f=>f!==null).sort((f,h)=>f.name.localeCompare(h.name))},staleTime:3e4})}function e3(t){const a=ke(),r=ae(u=>u.activeVaultId),i=pt();return xn({mutationFn:async u=>{if(!a)throw new Error("No active vault");return a.createNote({path:XM(u.name),content:u.description??"",tags:[t],metadata:YM(u.filters)})},onSuccess:()=>JM(i,r)})}const t3=["pinned","archived","untagged","orphaned"],OS={recent:{label:"Recent",hint:"what you've touched lately"},all:{label:"All notes",hint:"everything, searchable"},pinned:{label:"Pinned",hint:"starred"},archived:{label:"Archive",hint:"set aside, never deleted"},untagged:{label:"Untagged",hint:"notes without any tags"},orphaned:{label:"Orphaned",hint:"notes with no links"}};function n3(t){return t3.find(a=>a===t)}function Ah({preset:t,lens:a}={}){return a==="recent"?c.jsx(s3,{}):c.jsx(a3,{preset:t})}function MS({name:t}){return c.jsxs("header",{className:"mb-6",children:[c.jsx("h1",{className:"page-title",style:{fontSize:"clamp(2rem, 4vw, 2.6rem)"},children:t}),c.jsx("p",{className:"mt-1.5 text-fg-muted",children:"Everything here is yours. Open format. Export anytime."})]})}function a3({preset:t}){var ei,Ya;const a=ae(se=>se.getActiveVault()),{roles:r}=wl((a==null?void 0:a.id)??null),{pinnedTags:i}=F_((a==null?void 0:a.id)??null),[u,f]=Qh(),h=t??n3(u.get("view")),m=b.useMemo(()=>Db(u),[u]),[p,y]=b.useState(m.search??""),[S,v]=b.useState(m.pathPrefix??""),[x,T]=b.useState(m.tags??[]),[j,_]=b.useState(m.tagMatch??"any"),[C,O]=b.useState(m.sort??"desc"),[B,H]=b.useState(m.showArchived??!1),[k,Y]=b.useState(0),Q=b.useMemo(()=>u.toString(),[u]);b.useEffect(()=>{const se=Db(new URLSearchParams(Q));y(se.search??""),v(se.pathPrefix??""),T(se.tags??[]),_(se.tagMatch??"any"),O(se.sort??"desc"),H(se.showArchived??!1)},[Q]);const G=Ob(p,300),F=Ob(S,300);b.useEffect(()=>{if(h)return;const se={search:G,tags:x,tagMatch:j,pathPrefix:F,sort:C,showArchived:B};Nh(se).toString()!==Q&&f(Nh(se),{replace:!0})},[h,G,F,x,j,C,B]);const Z=h==="pinned"||h==="archived"?h:null,{def:le}=ER(Z,r),de=b.useMemo(()=>{if(!Z)return x;const se=le?P0(le.query):[];return Array.from(new Set([...se,...x]))},[Z,le,x]),ye=Z?"all":j;b.useEffect(()=>{Y(0)},[G,F,de,ye,C,B]);const we=b.useMemo(()=>({...n_,search:G,pathPrefix:F,tags:de,tagMatch:ye,sort:C,offset:k,limit:gr+1,...h==="untagged"?{hasTags:!1}:{},...h==="orphaned"?{hasLinks:!1}:{}}),[G,F,de,ye,C,k,h]),re=T_(we,{live:!1}),ee=R_(),M=WM(r.view),P=e3(r.view),ne=aa(se=>se.push),[oe,me]=b.useState(!1),[E,q]=b.useState(!1);b.useEffect(()=>{if(!E)return;const se=ft=>{ft.key==="Escape"&&q(!1)};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[E]);const{mode:X}=GM((a==null?void 0:a.id)??null),[W,pe]=b.useState(!1),Se=!h&&X!=="never",Oe=Se&&W,ut=A_(Oe),Ye=b.useMemo(()=>(ut.data??[]).map(se=>se.path),[ut.data]),Ka=Oe&&(X==="always"||X==="auto"&&AM(Ye)),ia=b.useMemo(()=>({search:G,tags:x,tagMatch:j,pathPrefix:F,sort:C,showArchived:B}),[G,F,x,j,C,B]),Fs=b.useCallback(async se=>{try{await P.mutateAsync({name:se,filters:ia}),ne(`Saved view "${se}".`,"success"),me(!1)}catch(ft){ne(`Could not save view: ${ft.message}`,"error")}},[P,ia,ne]),Jt=b.useMemo(()=>{if(!re.data)return re.data;let se=re.data.slice(0,gr);if(!h&&!B&&(se=se.filter(ft=>!(ft.tags??[]).includes(r.archived))),!h){const ft=r.pinned;se=[...se].sort((Pa,Io)=>{const Fa=(Pa.tags??[]).includes(ft)?0:1,Tt=(Io.tags??[]).includes(ft)?0:1;return Fa-Tt})}return se},[re.data,h,B,r.archived,r.pinned]);if(!a)return c.jsx(fn,{to:"/",replace:!0});const Sn=OS[h??"all"],Xs=k+1,Zs=k+((Jt==null?void 0:Jt.length)??0),jl=k>0,Js=((ei=re.data)==null?void 0:ei.length)??0,Ga=Js>gr,kr=Ga?null:k+Js,Ws=kr!==null?` of ${kr}`:` of ${k+gr}+`,Nl=ZM(ia),$o=(x.length>0?1:0)+(S.trim()?1:0)+(B?1:0)+(C!=="desc"?1:0),St=!h&&!Nl&&$o===0&&!re.isPending&&(((Ya=re.data)==null?void 0:Ya.length)??0)===0&&k===0,Qo=!St,Al=jl||Ga||((Jt==null?void 0:Jt.length)??0)>0;return c.jsxs("div",{className:"page-surface",children:[c.jsx(MS,{name:a.name}),c.jsx(bS,{}),h?null:c.jsx(vS,{vault:a,focused:!1},a.id),c.jsxs("div",{className:"mb-6",children:[c.jsxs("div",{"data-notes-chrome":!0,className:"flex items-center gap-3",children:[c.jsx("input",{type:"search",placeholder:"Search…",value:p,onChange:se=>y(se.target.value),className:"input min-w-0 flex-1","aria-label":"Search notes"}),Qo?c.jsxs("div",{className:"relative",children:[c.jsxs("button",{type:"button",onClick:()=>q(se=>!se),"aria-expanded":E,"aria-controls":"notes-filters",className:"btn btn-secondary btn-touch shrink-0",children:["Filters",c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:E?"▴":"▾"})]}),E?c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button","aria-hidden":"true",tabIndex:-1,onClick:()=>q(!1),className:"enter-fade fixed inset-0 z-30 cursor-default bg-black/40 sm:bg-transparent"}),c.jsx("section",{id:"notes-filters","aria-label":"Filters",className:"card enter-rise fixed inset-x-0 bottom-0 z-40 max-h-[70dvh] overflow-y-auto rounded-b-none p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] shadow-lift sm:absolute sm:top-full sm:right-0 sm:left-auto sm:bottom-auto sm:mt-1 sm:max-h-[30rem] sm:w-[26rem] sm:rounded-b-[var(--radius-2xl)] sm:pb-4",children:c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{children:[c.jsx("h2",{className:"eyebrow mb-3",children:"Refine"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("button",{type:"button",onClick:()=>O(se=>se==="desc"?"asc":"desc"),className:"focus-ring block text-fg-muted text-sm hover:text-accent","aria-label":"Toggle sort direction",children:["Sort: ",C==="desc"?"newest":"oldest"," first"]}),h?null:c.jsxs("label",{className:"flex items-center gap-1.5 text-fg-muted text-sm hover:text-accent",children:[c.jsx("input",{type:"checkbox",checked:B,onChange:se=>H(se.target.checked)}),"Show archived"]}),c.jsx("input",{type:"text",placeholder:"Title starts with…",value:S,onChange:se=>v(se.target.value),className:"input w-full font-mono","aria-label":"Filter by path prefix"}),c.jsx(p3,{active:h})]})]}),h!=="untagged"?c.jsxs("div",{children:[c.jsx(BM,{tags:ee.data??[],pinnedTags:i,selected:x,onToggle:se=>T(ft=>ft.includes(se)?ft.filter(Pa=>Pa!==se):[...ft,se]),onClear:()=>T([]),isLoading:ee.isPending}),x.length>1?c.jsxs("fieldset",{className:"mt-3 flex items-center gap-3 text-xs",children:[c.jsx("legend",{className:"sr-only",children:"Match mode"}),c.jsx("span",{className:"text-fg-dim",children:"Match"}),c.jsxs("label",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"radio",name:"tag-match",value:"any",checked:j==="any",onChange:()=>_("any")}),"Any"]}),c.jsxs("label",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"radio",name:"tag-match",value:"all",checked:j==="all",onChange:()=>_("all")}),"All"]})]}):null]}):null,Se?c.jsxs("details",{className:"group",open:W,onToggle:se=>pe(se.currentTarget.open),children:[c.jsxs("summary",{className:"eyebrow flex cursor-pointer list-none items-center justify-between rounded-lg px-1 py-1 hover:text-accent",children:[c.jsx("span",{children:"Folders"}),c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs transition-transform group-open:rotate-90",children:"▸"})]}),c.jsx("div",{className:"mt-2",children:Ka?c.jsx(_M,{paths:Ye,vaultId:a.id,currentPrefix:S,onSelect:se=>v(se)}):ut.isLoading?c.jsx("p",{className:"px-1 text-xs text-fg-dim",children:"Loading…"}):c.jsx("p",{className:"px-1 text-xs text-fg-dim",children:"Not enough folder variety to show a tree yet."})})]}):null,h?null:c.jsx(d3,{views:M.data})]})})]}):null]}):null]}),c.jsx(f3,{selectedTags:x,onRemoveTag:se=>T(ft=>ft.filter(Pa=>Pa!==se)),tagMatch:j,onToggleTagMatch:()=>_(se=>se==="all"?"any":"all"),pathPrefix:S,onClearPathPrefix:()=>v(""),showArchived:B,onClearArchived:()=>H(!1),sort:C,onResetSort:()=>O("desc"),showSave:Nl,onSaveView:()=>me(!0)})]}),St?null:c.jsxs(jm,{children:[Sn.label,c.jsxs("span",{className:"font-sans normal-case tracking-normal text-fg-muted",children:[" ","· ",Sn.hint]})]}),re.isPending?c.jsx(g3,{}):re.isError&&!re.data?c.jsx(y3,{error:re.error,retry:()=>re.refetch()}):Jt&&Jt.length>0?c.jsxs(c.Fragment,{children:[re.isError?c.jsx(_S,{}):null,c.jsx(SS,{"aria-label":"Notes",children:Jt.map(se=>c.jsx(xS,{note:se,pinnedTag:r.pinned,archivedTag:r.archived,trailing:h==="untagged"?c.jsx(m3,{noteId:se.id,existing:se.tags??[],suggestions:ee.data??[]}):void 0},se.id))})]}):c.jsx(v3,{filtering:r_(we)||!!h}),Al?c.jsxs("div",{className:"mt-6 flex items-center justify-between text-fg-dim text-sm",children:[c.jsx("span",{children:re.data&&re.data.length>0?`Showing ${Xs}–${Zs}${Ws}`:re.isFetching?"Loading…":""}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",disabled:!jl,onClick:()=>Y(se=>Math.max(0,se-gr)),className:"btn btn-secondary btn-touch",children:"Previous"}),c.jsx("button",{type:"button",disabled:!Ga,onClick:()=>Y(se=>se+gr),className:"btn btn-secondary btn-touch",children:"Next"})]})]}):null,oe?c.jsx(h3,{existing:M.data??[],isSaving:P.isPending,onCancel:()=>me(!1),onSave:Fs}):null]})}const r3=100;function s3(){var k,Y,Q;const t=ae(G=>G.getActiveVault()),a=N_(),{dismissed:r,dismiss:i}=qM((t==null?void 0:t.id)??null),{roles:u}=wl((t==null?void 0:t.id)??null),f=t!==null&&Qs(t.clientId),h=am({enabled:f}),m=((k=f?nm(h.data):null)==null?void 0:k.plan)??null,p=typeof(m==null?void 0:m.trial_days_left)=="number"?m.trial_days_left:null,y=b.useMemo(()=>{if(!a.data)return;const G=NS(qo(),-13),F=Z=>Z.updatedAt??Z.createdAt;return a.data.filter(Z=>!(Z.tags??[]).includes(u.archived)).filter(Z=>(jS(F(Z))??"")>=G).sort((Z,le)=>F(Z)<F(le)?1:F(Z)>F(le)?-1:0).slice(0,r3)},[a.data,u.archived]);if(!t)return c.jsx(fn,{to:"/",replace:!0});const S=a.data!==void 0,v=h0(a.data),x=m0({hasUserNote:v}),T=sA(x),j=!r&&!T,_=x.filter(G=>!G.done),C=x.length-_.length,O=S&&!v&&j?"fresh":"returning",B=!a.isPending&&(((Y=a.data)==null?void 0:Y.length)??0)===0,H=OS.recent;return c.jsxs("div",{className:"page-surface",children:[c.jsx(MS,{name:t.name}),c.jsx(bS,{}),c.jsx(vS,{vault:t,focused:O==="fresh"},t.id),c.jsx(i3,{daysLeft:p}),O==="fresh"?c.jsx(l3,{}):null,j&&_.length>0?c.jsx(u3,{to:Ub[_[0].id].to,label:Ub[_[0].id].label,done:C,total:x.length,onDismiss:i}):null,c.jsxs("section",{"aria-label":"Recent notes",children:[B?null:c.jsxs(jm,{children:[H.label,c.jsxs("span",{className:"font-sans normal-case tracking-normal text-fg-muted",children:[" ","· ",H.hint]})]}),a.isPending?c.jsx(o3,{}):a.isError&&!a.data?c.jsx("p",{className:"rounded-xl border border-border bg-card px-4 py-3 text-sm text-fg-muted",children:"Couldn't load recent notes. They'll appear once you're back online."}):(((Q=a.data)==null?void 0:Q.length)??0)===0?c.jsxs("div",{className:"rounded-xl border border-border bg-card p-8 text-center shadow-soft",children:[c.jsx("p",{className:"mb-1 font-serif text-fg text-lg",children:"A quiet, empty page."}),c.jsx("p",{className:"mb-5 text-fg-muted text-sm",children:"Anything at all can land here — a thought, a list, a memory."}),c.jsx("button",{type:"button",onClick:()=>{var G;return(G=document.getElementById(yS))==null?void 0:G.focus()},className:"inline-flex rounded-full bg-accent px-5 py-2.5 font-round font-semibold text-on-accent text-sm shadow-soft hover:bg-accent-hover",children:"Write the first one"})]}):((y==null?void 0:y.length)??0)===0?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"rounded-xl border border-border bg-card px-4 py-3 text-sm text-fg-muted",children:"Nothing touched in the last two weeks."}),c.jsx(kb,{})]}):c.jsxs(c.Fragment,{children:[a.isError?c.jsx(_S,{}):null,c.jsx(DM,{notes:y??[]}),c.jsx(kb,{})]})]}),c.jsx(c3,{clientId:t.clientId,trialDaysLeft:p})]})}function kb(){return c.jsxs("p",{className:"mt-6 text-fg-dim text-sm",children:["Looking for older notes?"," ",c.jsx(_e,{to:"/notes",className:"text-accent hover:underline",children:"All notes →"})]})}function i3({daysLeft:t}){return t===null||t>7?null:c.jsxs("div",{className:"nudge-sun mb-6",children:[c.jsx("span",{"aria-hidden":"true",children:"✦"}),c.jsx(_e,{to:"/account",className:"min-w-0 flex-1 truncate hover:underline",children:t===0?"Your trial ends today — see plans →":`Your trial ends in ${t} day${t===1?"":"s"} — see plans →`})]})}function l3(){return c.jsxs("nav",{"aria-label":"Quick actions",className:"mb-6 grid gap-3 sm:grid-cols-2",children:[c.jsx(Lb,{to:"/connect",emoji:"⚡",title:"Connect your AI",description:"Let Claude or ChatGPT read and write your vault."}),c.jsx(Lb,{to:"/import",emoji:"↯",title:"Bring your notes over",description:"Import from Obsidian or plain markdown."})]})}function Lb({to:t,emoji:a,title:r,description:i}){return c.jsxs(_e,{to:t,className:"focus-ring tile flex items-start gap-3 p-4",children:[c.jsx("span",{"aria-hidden":"true",className:"text-lg leading-none",children:a}),c.jsxs("span",{className:"min-w-0",children:[c.jsx("span",{className:"block font-medium text-fg",children:r}),c.jsx("span",{className:"mt-0.5 block text-fg-muted text-sm",children:i})]})]})}const Ub={write:{label:"Write your first note",to:"/new"}};function u3({to:t,label:a,done:r,total:i,onDismiss:u}){return c.jsxs("div",{className:"nudge-sun mb-8",children:[c.jsx("span",{"aria-hidden":"true",children:"✦"}),c.jsxs(_e,{to:t,className:"min-w-0 flex-1 truncate hover:underline",children:["Finish setting up — ",a]}),c.jsxs("span",{className:"font-round text-sm opacity-80",children:[r," / ",i]}),c.jsx("button",{type:"button",onClick:u,"aria-label":"Dismiss setup",className:"ml-1 text-sun-ink/70 hover:text-sun-ink",children:"✕"})]})}function o3(){return c.jsx("div",{className:"space-y-3","aria-busy":"true",children:[0,1,2].map(t=>c.jsx(jh,{className:"h-14 rounded-xl"},t))})}function c3({clientId:t,trialDaysLeft:a}){return Qs(t)?c.jsx("div",{className:"mt-10 border-t border-border pt-4 text-sm",children:c.jsx(_e,{to:"/account",className:"text-fg-dim hover:text-accent",children:a!==null?c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"font-medium text-sun-ink",children:["Free trial ·"," ",a===0?"ends today":`${a} day${a===1?"":"s"} left`]})," ","· Manage your account →"]}):"Manage your account →"})}):null}function f3({selectedTags:t,onRemoveTag:a,tagMatch:r,onToggleTagMatch:i,pathPrefix:u,onClearPathPrefix:f,showArchived:h,onClearArchived:m,sort:p,onResetSort:y,showSave:S,onSaveView:v}){const x=u.trim();return!(t.length>0||x.length>0||h||p==="asc")&&!S?null:c.jsxs("div",{"aria-label":"Active filters",className:"mt-3 flex flex-wrap items-center gap-2",children:[t.map(j=>c.jsx(to,{label:`#${j}`,onRemove:()=>a(j)},`tag-${j}`)),t.length>1?c.jsxs("button",{type:"button",onClick:i,"aria-label":`Tag match is currently "${r}" — click to switch`,className:"chip",children:["match ",r,c.jsx("span",{"aria-hidden":"true",className:"ml-1",children:"▾"})]}):null,x?c.jsx(to,{label:`title: ${x}`,onRemove:f}):null,h?c.jsx(to,{label:"archived shown",onRemove:m}):null,p==="asc"?c.jsx(to,{label:"oldest first",onRemove:y}):null,S?c.jsx("button",{type:"button",onClick:v,className:"btn btn-accent-soft btn-sm ml-auto",children:"Save as view…"}):null]})}function d3({views:t}){return!t||t.length===0?null:c.jsxs("details",{className:"group border-t border-border pt-3",children:[c.jsxs("summary",{className:"eyebrow flex cursor-pointer list-none items-center gap-1.5 text-fg-dim hover:text-accent",children:[c.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs transition-transform group-open:rotate-90",children:"▸"}),"Saved filters"]}),c.jsx("ul",{className:"mt-2 space-y-0.5","aria-label":"Saved views",children:t.map(a=>c.jsx("li",{children:c.jsx(_e,{to:`/notes?${Nh(a.filters).toString()}`,className:"block truncate rounded-lg px-2 py-1 text-sm text-fg-muted hover:bg-bg-soft hover:text-accent",children:a.name})},a.id))})]})}function h3({existing:t,isSaving:a,onCancel:r,onSave:i}){const[u,f]=b.useState(""),h=u.trim(),m=t.some(y=>y.name.toLowerCase()===h.toLowerCase()),p=h.length>0&&!m&&!a;return c.jsx("div",{className:"dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Save view",children:c.jsxs("div",{className:"dialog-panel max-w-(--w-narrow)",children:[c.jsx("h3",{className:"mb-3 font-serif text-lg text-fg",children:"Save view"}),c.jsxs("label",{className:"block text-sm",children:[c.jsx("span",{className:"mb-1 block text-fg-muted",children:"Name"}),c.jsx("input",{type:"text",value:u,autoFocus:!0,onChange:y=>f(y.target.value),onKeyDown:y=>{y.key==="Enter"&&p&&i(h),y.key==="Escape"&&r()},placeholder:"e.g. Daily journal","aria-label":"View name",className:"input input-on-bg"})]}),m?c.jsx("p",{className:"mt-2 text-xs text-danger",children:"A view with that name already exists."}):null,c.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[c.jsx("button",{type:"button",onClick:r,className:"btn btn-secondary btn-touch",children:"Cancel"}),c.jsx("button",{type:"button",onClick:()=>p&&i(h),disabled:!p,className:"btn btn-primary btn-touch",children:a?"Saving…":"Save"})]})]})})}function m3({noteId:t,existing:a,suggestions:r}){const[i,u]=b.useState(!1),[f,h]=b.useState(""),m=b.useRef(null),p=b.useRef(null),y=U_(t),S=aa(T=>T.push);b.useEffect(()=>{var _;if(!i)return;(_=p.current)==null||_.focus();const T=C=>{var O;(O=m.current)!=null&&O.contains(C.target)||u(!1)},j=C=>{C.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",T),document.addEventListener("keydown",j),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",j)}},[i]);const v=b.useMemo(()=>{const T=So(f).toLowerCase(),j=new Set(a.map(C=>C.toLowerCase())),_=r.filter(C=>!j.has(C.name.toLowerCase()));return T?_.filter(C=>C.name.toLowerCase().includes(T)).slice(0,8):_.slice(0,8)},[f,r,a]),x=b.useCallback(async T=>{const j=So(T);if(j)try{await y.mutateAsync({tags:{add:[j]}}),S(`Added #${j}`,"success"),h(""),u(!1)}catch(_){S(`Could not add tag: ${_.message}`,"error")}},[y,S]);return i?c.jsxs("div",{ref:m,className:"relative",children:[c.jsx("input",{ref:p,type:"text",value:f,onChange:T=>h(T.target.value),onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),x(f))},placeholder:"tag…","aria-label":"Tag name",disabled:y.isPending,className:"input w-32 px-2 py-1 text-xs"}),v.length>0?c.jsx("ul",{className:"absolute right-0 z-20 mt-1 max-h-48 w-44 overflow-y-auto rounded-xl border border-border bg-card text-xs shadow-lift","aria-label":"Tag suggestions",children:v.map(T=>c.jsx("li",{children:c.jsxs("button",{type:"button",onMouseDown:j=>{j.preventDefault(),x(T.name)},className:"flex w-full items-center justify-between px-2 py-1 text-left text-fg hover:bg-bg/60",children:[c.jsx("span",{className:"truncate",children:T.name}),c.jsx("span",{className:"ml-2 shrink-0 text-fg-dim",children:T.count??0})]})},T.name))}):null]}):c.jsx("button",{type:"button",onClick:()=>u(!0),className:"btn btn-sm border border-border bg-bg/60 text-fg-muted hover:border-accent hover:text-accent","aria-label":"Add tag",children:"+ tag"})}function p3({active:t}){const a=[{view:"untagged",label:"Untagged"},{view:"orphaned",label:"Orphaned"}];return c.jsxs("nav",{"aria-label":"Show only",className:"flex flex-wrap items-center gap-2",children:[c.jsx("span",{className:"text-fg-muted text-sm",children:"Show only:"}),a.map(r=>{const i=r.view===t;return c.jsx(_e,{to:i?"/notes":`/notes?view=${r.view}`,"aria-current":i?"page":void 0,className:`chip focus-ring max-w-full ${i?"chip-tag-active font-medium":"chip-tag"}`,children:r.label},r.view)})]})}function g3(){return c.jsx("ol",{className:"flex flex-col gap-0.5","aria-busy":"true",children:[0,1,2,3,4].map(t=>c.jsxs("li",{className:"rounded-xl px-3 py-3",children:[c.jsx(jh,{className:"h-4 w-1/3"}),c.jsx(jh,{className:"mt-2 h-3 w-2/3"})]},t))})}function y3({error:t,retry:a}){const r=t instanceof Uo;return c.jsx(W0,{title:r?"Session expired":"Could not load notes",message:t.message,retry:r?void 0:a,action:r?c.jsx(_e,{to:"/add",className:"btn btn-primary",children:"Reconnect vault"}):void 0})}function v3({filtering:t}){return t?c.jsx(wh,{title:"No notes match these filters."}):c.jsx(wh,{title:"This vault has no notes yet.",action:c.jsx(_e,{to:"/new",className:"btn btn-primary",children:"Create one"})})}const b3=b.lazy(()=>Qe(()=>import("./Account-DYfzZj5S.js"),__vite__mapDeps([0,1])).then(t=>({default:t.Account}))),x3=b.lazy(()=>Qe(()=>import("./Activity-CKF0o1vW.js"),[]).then(t=>({default:t.Activity}))),S3=b.lazy(()=>Qe(()=>import("./AddVault-DKBqKeyq.js"),__vite__mapDeps([2,3,4,5])).then(t=>({default:t.AddVault}))),w3=b.lazy(()=>Qe(()=>import("./AddVaultChooser-BW2Q-Yue.js"),__vite__mapDeps([6,3,4])).then(t=>({default:t.AddVaultChooser}))),E3=b.lazy(()=>Qe(()=>import("./AddVaultCreate-CtO9yrS5.js"),__vite__mapDeps([7,3,4])).then(t=>({default:t.AddVaultCreate}))),T3=b.lazy(()=>Qe(()=>import("./AddVaultCreate-CtO9yrS5.js"),__vite__mapDeps([7,3,4])).then(t=>({default:t.AddVaultReady}))),j3=b.lazy(()=>Qe(()=>import("./Calendar-DFuh1M3x.js"),[]).then(t=>({default:t.Calendar}))),N3=b.lazy(()=>Qe(()=>import("./ConnectAI-BL20KQ5Y.js"),[]).then(t=>({default:t.ConnectAI}))),A3=b.lazy(()=>Qe(()=>import("./DayView-Dr2pAVmN.js"),__vite__mapDeps([8,4])).then(t=>({default:t.DayView}))),_3=b.lazy(()=>Qe(()=>import("./Export-BynzqvGJ.js"),[]).then(t=>({default:t.Export}))),R3=b.lazy(()=>Qe(()=>import("./Import-6SmwJlgO.js"),__vite__mapDeps([9,10])).then(t=>({default:t.Import}))),C3=b.lazy(()=>Qe(()=>import("./NoteEditor-OPipzN_Z.js"),__vite__mapDeps([11,10,12,13,14,15])).then(t=>({default:t.NoteEditor}))),O3=b.lazy(()=>Qe(()=>import("./NoteNew-Dy1AbHxm.js"),__vite__mapDeps([16,10,12,13,17,18,15])).then(t=>({default:t.NoteNew}))),M3=b.lazy(()=>Qe(()=>import("./NoteView-B0eNsUUX.js"),__vite__mapDeps([19,14,13])).then(t=>({default:t.NoteView}))),D3=b.lazy(()=>Qe(()=>import("./OAuthCallback-D35vvyoO.js"),__vite__mapDeps([20,3,4,5])).then(t=>({default:t.OAuthCallback}))),k3=b.lazy(()=>Qe(()=>import("./Settings-UmrOUQH_.js"),__vite__mapDeps([21,17,18,15])).then(t=>({default:t.Settings}))),L3=b.lazy(()=>Qe(()=>import("./Tags-CTF2n8-H.js"),__vite__mapDeps([22,23])).then(t=>({default:t.Tags}))),U3=b.lazy(()=>Qe(()=>import("./TagPage-B7bGWyY4.js"),__vite__mapDeps([24,25,23])).then(t=>({default:t.TagPage}))),z3=b.lazy(()=>Qe(()=>import("./VaultGraph-BLefh0Zh.js"),[]).then(t=>({default:t.VaultGraph}))),V3=b.lazy(()=>Qe(()=>import("./Vaults-tXitT9QI.js"),__vite__mapDeps([26,1,18])).then(t=>({default:t.Vaults}))),B3=b.lazy(()=>Qe(()=>import("./Welcome-yAs98HfO.js"),__vite__mapDeps([27,3,4,1])).then(t=>({default:t.Welcome}))),H3=b.lazy(()=>Qe(()=>import("./CheckEmail-CIv1Gt1o.js"),__vite__mapDeps([28,3,4])).then(t=>({default:t.CheckEmail}))),q3=b.lazy(()=>Qe(()=>import("./ViewNew-DRZyYhEC.js"),[]).then(t=>({default:t.ViewNew}))),$3=b.lazy(()=>Qe(()=>import("./ViewSurface-DzU1BogH.js"),__vite__mapDeps([25,23])).then(t=>({default:t.ViewSurface})));function Q3(){const t=ae(h=>h.getActiveVault()),[a]=Qh(),[r,i]=b.useState(null),u=b.useRef(!1),f=b.useCallback(()=>{u.current=!0,i(null),mS().catch(()=>{}),VO({hasLocalActiveVault:!1}).then(i).catch(()=>i({kind:"front-door"}))},[]);if(b.useEffect(()=>{t||u.current||f()},[t,f]),a.get("add"))return c.jsx(fn,{to:`/add?${a.toString()}`,replace:!0});if(t)return c.jsx(Ah,{lens:"recent"});if(!r)return c.jsx(I3,{});switch(r.kind){case"home":return c.jsx(Ah,{lens:"recent"});case"signed-in":return c.jsx(Md,{signedIn:{email:r.email,username:r.username,vaults:r.vaults}});case"net-error":return c.jsx(Md,{netError:r.message,onRetry:f});default:return c.jsx(Md,{})}}function I3(){return c.jsx("output",{"aria-live":"polite",className:"mx-auto flex min-h-[50dvh] items-center justify-center text-sm text-fg-dim",children:c.jsx("span",{className:"animate-pulse",children:"Loading…"})})}function K3(){return c.jsx("output",{"aria-live":"polite",className:"mx-auto block max-w-5xl px-6 py-10 text-center text-sm text-fg-dim",children:"Loading…"})}function zb({suffix:t=""}){const{id:a}=NT();return a?$O(window.location.pathname)?c.jsx(fn,{to:"/",replace:!0}):c.jsx(fn,{to:`/n/${encodeURIComponent(a)}${t}`,replace:!0}):c.jsx(fn,{to:"/",replace:!0})}function Vb({to:t}){const a=Ge();return c.jsx(fn,{to:`${t}${a.search}`,replace:!0})}function G3(){return c.jsx("div",{className:"page",children:c.jsx(wh,{title:c.jsx("span",{className:"font-serif text-xl text-fg",children:"Page not found"}),description:"That address doesn't match anything in Parachute. It may be mistyped, or the page may have moved.",action:c.jsx(_e,{to:"/notes",className:"btn btn-primary btn-touch",children:"Back to notes"})})})}function Y3(){const{pathname:t}=Ge();return Z0(t)?null:c.jsx("footer",{className:"mx-auto max-w-5xl px-6 py-10 text-center text-sm text-fg-dim",children:c.jsxs("p",{children:["Part of the"," ",c.jsx("a",{href:"https://parachute.computer",className:"focus-ring text-accent hover:underline",children:"Parachute Computer"})," ","ecosystem. AGPL-3.0."]})})}function P3(){const t=ae(r=>r.activeVaultId),a=ke();return W_(t,a),null}function F3(){const t=Ge(),r=bo(i=>i.on)&&tS(t.pathname);return c.jsxs("div",{className:"app-canvas min-h-dvh overflow-x-hidden text-fg",children:[c.jsx(hO,{}),c.jsx(wO,{}),c.jsx(EO,{}),c.jsx(wj,{}),c.jsx(Ej,{}),c.jsx(PC,{}),c.jsx(iC,{}),c.jsxs("div",{className:"lg:flex",children:[r?null:c.jsx(uO,{}),c.jsxs("div",{className:`flex min-w-0 flex-1 flex-col ${r?"":"pb-16 lg:pb-0"}`,children:[r?null:c.jsx(YC,{}),c.jsx(iO,{}),c.jsx("main",{className:"flex-1","data-focus-safe-area":r?"true":void 0,style:r?{paddingTop:"env(safe-area-inset-top)"}:void 0,children:c.jsx(b.Suspense,{fallback:c.jsx(K3,{}),children:c.jsxs(qT,{children:[c.jsx(je,{path:"/",element:c.jsx(Q3,{})}),c.jsx(je,{path:"/check-email",element:c.jsx(Fe,{children:c.jsx(H3,{})})}),c.jsx(je,{path:"/notes",element:c.jsx(Ah,{})}),c.jsx(je,{path:"/all",element:c.jsx(Vb,{to:"/notes"})}),c.jsx(je,{path:"/pinned",element:c.jsx(fn,{to:"/notes?view=pinned",replace:!0})}),c.jsx(je,{path:"/archived",element:c.jsx(fn,{to:"/notes?view=archived",replace:!0})}),c.jsx(je,{path:"/untagged",element:c.jsx(fn,{to:"/notes?view=untagged",replace:!0})}),c.jsx(je,{path:"/orphaned",element:c.jsx(fn,{to:"/notes?view=orphaned",replace:!0})}),c.jsx(je,{path:"/tags",element:c.jsx(Fe,{children:c.jsx(L3,{})})}),c.jsx(je,{path:"/tags/:name",element:c.jsx(Fe,{children:c.jsx(U3,{})})}),c.jsx(je,{path:"/new",element:c.jsx(Fe,{children:c.jsx(O3,{})})}),c.jsx(je,{path:"/capture",element:c.jsx(fn,{to:"/new",replace:!0})}),c.jsx(je,{path:"/import",element:c.jsx(Fe,{children:c.jsx(R3,{})})}),c.jsx(je,{path:"/export",element:c.jsx(Fe,{children:c.jsx(_3,{})})}),c.jsx(je,{path:"/connect",element:c.jsx(Fe,{children:c.jsx(N3,{})})}),c.jsx(je,{path:"/map",element:c.jsx(Fe,{children:c.jsx(z3,{})})}),c.jsx(je,{path:"/graph",element:c.jsx(Vb,{to:"/map"})}),c.jsx(je,{path:"/today",element:c.jsx(Fe,{children:c.jsx(A3,{})})}),c.jsx(je,{path:"/calendar",element:c.jsx(Fe,{children:c.jsx(j3,{})})}),c.jsx(je,{path:"/activity",element:c.jsx(Fe,{children:c.jsx(x3,{})})}),c.jsx(je,{path:"/views/new",element:c.jsx(Fe,{children:c.jsx(q3,{})})}),c.jsx(je,{path:"/views/:id",element:c.jsx(Fe,{children:c.jsx($3,{})})}),c.jsx(je,{path:"/n/:id",element:c.jsx(Fe,{children:c.jsx(M3,{})})}),c.jsx(je,{path:"/n/:id/edit",element:c.jsx(Fe,{children:c.jsx(C3,{})})}),c.jsx(je,{path:"/:id",element:c.jsx(zb,{})}),c.jsx(je,{path:"/:id/edit",element:c.jsx(zb,{suffix:"/edit"})}),c.jsx(je,{path:"/add",element:c.jsx(Fe,{children:c.jsx(S3,{})})}),c.jsx(je,{path:"/add-vault",element:c.jsx(Fe,{children:c.jsx(w3,{})})}),c.jsx(je,{path:"/add-vault/create",element:c.jsx(Fe,{children:c.jsx(E3,{})})}),c.jsx(je,{path:"/add-vault/ready",element:c.jsx(Fe,{children:c.jsx(T3,{})})}),c.jsx(je,{path:"/welcome",element:c.jsx(Fe,{children:c.jsx(B3,{})})}),c.jsx(je,{path:"/oauth/callback",element:c.jsx(Fe,{children:c.jsx(D3,{})})}),c.jsx(je,{path:"/vaults",element:c.jsx(Fe,{children:c.jsx(V3,{})})}),c.jsx(je,{path:"/account",element:c.jsx(Fe,{children:c.jsx(b3,{})})}),c.jsx(je,{path:"/settings",element:c.jsx(Fe,{children:c.jsx(k3,{})})}),c.jsx(je,{path:"*",element:c.jsx(G3,{})})]})})}),r?null:c.jsx(Y3,{})]})]}),r?null:c.jsx(JR,{}),r?null:c.jsx(ZR,{}),r?null:c.jsx(fO,{}),r?c.jsx(lC,{}):null]})}function X3(){V_(),b.useEffect(()=>{aS(Ss())},[]);const t=ae(a=>{var r;return((r=a.getActiveVault())==null?void 0:r.name)??null});return b.useEffect(()=>{document.title=t?`Parachute — ${t}`:"Parachute"},[t]),c.jsx(rC,{children:c.jsx(HO,{children:c.jsxs(N2,{children:[c.jsx(P3,{}),c.jsx(SC,{}),c.jsx(dj,{basename:pl(),children:c.jsx(FR,{children:c.jsx(F3,{})})})]})})})}var kd={exports:{}},Xi={},Ld={exports:{}},Ud={};/**
35
35
  * @license React
36
36
  * scheduler.production.js
37
37
  *