@openparachute/app 0.22.14-rc.2 → 0.22.14-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/.parachute/info +1 -1
- package/dist/assets/{Account-CoSQwMlJ.js → Account-BATMJZJa.js} +1 -1
- package/dist/assets/{Activity-kaMFa3fK.js → Activity-B5veG9-7.js} +1 -1
- package/dist/assets/{AddVault-BdEbS-at.js → AddVault-RIYjxbdI.js} +1 -1
- package/dist/assets/{AddVaultChooser-DR4cyJeZ.js → AddVaultChooser-CWUDOhZF.js} +1 -1
- package/dist/assets/{AddVaultCreate-DKSKUeG8.js → AddVaultCreate-BE3EYXef.js} +1 -1
- package/dist/assets/{Calendar-_loW0paP.js → Calendar-CN00mtO8.js} +1 -1
- package/dist/assets/{CheckEmail-PBWODeVZ.js → CheckEmail-CPk4SrzN.js} +1 -1
- package/dist/assets/{ConnectAI-DQ_N7ZF3.js → ConnectAI-CSuI0Yoc.js} +1 -1
- package/dist/assets/{DayView-DtlzBMFH.js → DayView-CZZ5Upgs.js} +1 -1
- package/dist/assets/{Export-kSyvEi0u.js → Export-CrAILYQp.js} +1 -1
- package/dist/assets/{Import-3fbKo4w8.js → Import-GVSfg168.js} +1 -1
- package/dist/assets/{NoteEditor-CpulwbX3.js → NoteEditor-h03ldU1x.js} +1 -1
- package/dist/assets/{NoteNew-Cc6a1vru.js → NoteNew-Cb8lPDeH.js} +1 -1
- package/dist/assets/{NoteRenderer-I-fX48a-.js → NoteRenderer-Di0UeCb6.js} +24 -24
- package/dist/assets/{NoteView-BQ3li7s2.js → NoteView-BhyqbuWQ.js} +2 -2
- package/dist/assets/{OAuthCallback-pBSW2lKo.js → OAuthCallback-CuQZENVJ.js} +1 -1
- package/dist/assets/{PinArchiveButtons-Dxqe-PNR.js → PinArchiveButtons-ZVswJ5CT.js} +1 -1
- package/dist/assets/{Settings-CPo-Wt-I.js → Settings-BcVzNKyK.js} +1 -1
- package/dist/assets/{TagPage-BnEENXCy.js → TagPage-De-8_dnv.js} +1 -1
- package/dist/assets/{TagSchemaEditor-B-d3rSjI.js → TagSchemaEditor-BCW9lfYM.js} +1 -1
- package/dist/assets/{Tags-CylsLohS.js → Tags-BVja3Y83.js} +1 -1
- package/dist/assets/{VaultGraph-BUmNoSkm.js → VaultGraph-EAIfK4Pi.js} +2 -2
- package/dist/assets/{Vaults-BLhnLLYV.js → Vaults-siYPRrp1.js} +1 -1
- package/dist/assets/{ViewNew-AysTVG25.js → ViewNew-KjZfga8E.js} +1 -1
- package/dist/assets/{ViewSurface-CIpzYIN8.js → ViewSurface-CCFPmjfV.js} +1 -1
- package/dist/assets/{Welcome-Ch_SVwda.js → Welcome-Cpd4_G3A.js} +1 -1
- package/dist/assets/{WizardShell-C6s4rjvR.js → WizardShell-Db9Lf-7T.js} +1 -1
- package/dist/assets/{attachment-upload-DgPB_hNP.js → attachment-upload-BsqkBXUZ.js} +1 -1
- package/dist/assets/{history-D-PT8sXa.js → history-Cm57tniH.js} +1 -1
- package/dist/assets/{index-DEEhPpPi.js → index-BWCbWA0P.js} +2 -2
- package/dist/assets/{provenance-B3gZ95dW.js → provenance-BHxYmeeX.js} +1 -1
- package/dist/assets/{react-force-graph-2d-QCauZ0zI.js → react-force-graph-2d-CM6lDUCC.js} +1 -1
- package/dist/assets/{transcribe-default-Vo4Gqy9l.js → transcribe-default-ApFs1eQh.js} +1 -1
- package/dist/assets/{useAttachmentUploader-DbHznJZI.js → useAttachmentUploader-Qgpb2mJ9.js} +1 -1
- package/dist/index.html +1 -1
- package/dist/sw.js +1 -1
- package/meta.json +1 -1
- package/package.json +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Account-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Account-BATMJZJa.js","assets/provenance-BHxYmeeX.js","assets/AddVault-RIYjxbdI.js","assets/WizardShell-Db9Lf-7T.js","assets/history-Cm57tniH.js","assets/url-QSQwrjSV.js","assets/AddVaultChooser-CWUDOhZF.js","assets/AddVaultCreate-BE3EYXef.js","assets/DayView-CZZ5Upgs.js","assets/Import-GVSfg168.js","assets/attachment-upload-BsqkBXUZ.js","assets/NoteEditor-h03ldU1x.js","assets/useAttachmentUploader-Qgpb2mJ9.js","assets/NoteRenderer-Di0UeCb6.js","assets/PinArchiveButtons-ZVswJ5CT.js","assets/editor-mode-D9fveTEx.js","assets/NoteNew-Cb8lPDeH.js","assets/transcribe-default-ApFs1eQh.js","assets/types-BaJkUfo6.js","assets/NoteView-BhyqbuWQ.js","assets/OAuthCallback-CuQZENVJ.js","assets/Settings-BcVzNKyK.js","assets/Tags-BVja3Y83.js","assets/TagSchemaEditor-BCW9lfYM.js","assets/TagPage-De-8_dnv.js","assets/ViewSurface-CCFPmjfV.js","assets/Vaults-siYPRrp1.js","assets/Welcome-Cpd4_G3A.js","assets/CheckEmail-CPk4SrzN.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var AE=Object.defineProperty;var Ov=t=>{throw TypeError(t)};var _E=(t,a,r)=>a in t?AE(t,a,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[a]=r;var fe=(t,a,r)=>_E(t,typeof a!="symbol"?a+"":a,r),cd=(t,a,r)=>a.has(t)||Ov("Cannot "+r);var A=(t,a,r)=>(cd(t,a,"read from private field"),r?r.call(t):a.get(t)),ue=(t,a,r)=>a.has(t)?Ov("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(t):a.set(t,r),J=(t,a,r,i)=>(cd(t,a,"write to private field"),i?i.call(t,r):a.set(t,r),r),xe=(t,a,r)=>(cd(t,a,"access private method"),r);var Po=(t,a,r,i)=>({set _(o){J(t,a,o,r)},get _(){return A(t,a,i)}});(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))i(o);new MutationObserver(o=>{for(const c of o)if(c.type==="childList")for(const h of c.addedNodes)h.tagName==="LINK"&&h.rel==="modulepreload"&&i(h)}).observe(document,{childList:!0,subtree:!0});function r(o){const c={};return o.integrity&&(c.integrity=o.integrity),o.referrerPolicy&&(c.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?c.credentials="include":o.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function i(o){if(o.ep)return;o.ep=!0;const c=r(o);fetch(o.href,c)}})();var VD=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function RE(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var fd={exports:{}},Gi={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react-jsx-runtime.production.js
|
|
@@ -31,7 +31,7 @@ Please change the parent <Route path="${M}"> to <Route path="${M==="/"?"*":`${M}
|
|
|
31
31
|
`)}return t}function $u(t){const a=t.split("/");return(a[a.length-1]??t).replace(/\.md$/i,"")}function bb(t,a){return t===a.id?!0:a.path?t===a.path||t===$u(a.path):!1}const C_=/^\/?Notes\/(\d{4})\/(\d{2})-(\d{2})\/(\d{2})-(\d{2})-(\d{2})(?:\.md)?$/i;function M_(t){const a=t.match(C_);if(a){const[,r,i,o,c,h]=a,m=new Date(Number(r),Number(i)-1,Number(o),Number(c),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:$u(t)}}function wu(t){const a=t.displayTitle;if(typeof a=="string"&&a.length>0&&!gm(a)&&!bb(a,t))return{kind:"title",text:a};const r=t.content;if(typeof r=="string"){const i=ym(r);if(i&&!bb(i,t))return{kind:"title",text:i}}return t.path?M_(t.path):{kind:"title",text:t.id}}const xb=120,O_=100,D_=new RegExp(`^(?:${G0.source}|${Y0.source}|${P0.source})$`),k_=/^(?:!\[\[[^\n]+\]\]|!\[[^\n]*\]\([^\n]*\))$/;function X0(t){var r,i;if(((r=t[0])==null?void 0:r.trim())!=="---")return 0;const a=Math.min(t.length,O_);for(let o=1;o<a;o++)if(((i=t[o])==null?void 0:i.trim())==="---")return o+1;return 0}function Z0(t){return t.replace(/^#{1,6}\s*/,"").trim()}function gm(t){const a=t.trim();return a===""||D_.test(a)||k_.test(a)}function ym(t){if(!t)return null;const a=t.split(`
|
|
32
32
|
`);for(let r=X0(a);r<a.length;r++){const i=Z0(a[r]);if(gm(i))continue;const o=Array.from(i);return o.length>xb?o.slice(0,xb).join(""):i}return null}function ak(t){const a=t.split(`
|
|
33
33
|
`),r=X0(a);let i=r;for(;i<a.length&&gm(Z0(a[i]));)i++;if(i>=a.length)return t;let o=i+1;for(;o<a.length&&a[o].trim()==="";)o++;return a.splice(r,o-r),a.join(`
|
|
34
|
-
`)}const J0=512*1024*1024,wb=200;function bh(t){return t.contentEvicted?0:typeof t.byteSize=="number"&&Number.isFinite(t.byteSize)&&t.byteSize>=0?t.byteSize:L_(t)}function L_(t){var r,i,o,c;let a=(((r=t.content)==null?void 0:r.length)??0)+(((i=t.preview)==null?void 0:i.length)??0);return(o=t.links)!=null&&o.length&&(a+=JSON.stringify(t.links).length),(c=t.attachments)!=null&&c.length&&(a+=JSON.stringify(t.attachments).length),a}function U_(t){var a,r;return!!(t.content||(a=t.links)!=null&&a.length||(r=t.attachments)!=null&&r.length)}function z_(t){const a=t.preview??V_(t.content),i=t.displayTitle??ym(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 V_(t){if(!t)return;const a=R_(t).replace(/\s+/g," ").trim();if(a)return a.length>wb?`${a.slice(0,wb).trimEnd()}…`:a}function B_(t,a,r){let i=0;for(const h of t)i+=bh(h);const o=i,c=[];if(i>a)for(const h of t){if(i<=a)break;h.contentEvicted||r(h.id)||U_(h)&&(c.push(h),i-=bh(h))}return{toEvict:c,totalBefore:o,totalAfter:i,freedBytes:o-i}}async function H_(t,a,r=J0){const i=await Hu(t,a),o=await vh(t,a),c=K0(o),h=B_(i,r,c);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(z_(p));return await m.done,{evicted:h.toEvict.length,freedBytes:h.freedBytes,totalBytes:h.totalAfter}}async function rk(t,a){const r=await Hu(t,a);let i=0;for(const o of r)i+=bh(o);return i}function W0(t){return`mirror:${t}`}function ew(){const t=typeof navigator<"u"?navigator.locks:void 0;return t!=null&&t.request?t:void 0}async function q_(t,a,r){const i=ew();return i?i.request(W0(t),{ifAvailable:!0},async o=>o?await r():await a()):r()}const $_=15e3;async function Q_(t,a,r=$_){const i=ew();return i?i.request(W0(t),{signal:AbortSignal.timeout(r)},async()=>await a()):a()}const I_={includeContent:!0,includeLinks:!0,includeAttachments:!0},Sb={includeContent:!1,includeLinks:!1,includeAttachments:!1},K_=6e4,G_=200,Y_=1e3,P_=360*60*1e3,F_=1e3;function X_(t){return t instanceof Error?/cursor_invalid|cursor_query_mismatch/i.test(t.message):!1}class Z_{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??K_,this.pageLimit=a.pageLimit??G_,this.maxDrainPages=a.maxDrainPages??F_,this.sweepEnumLimit=a.sweepEnumLimit??Y_,this.sweepIntervalMs=a.sweepIntervalMs??P_,this.ceilingBytes=a.ceilingBytes??J0,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){return q_(a,r,i)}async drainCursor(a,r){var p,y,x,v,w,T,E,_,R,M;let i=await s_(this.db,r)??"";const o=await xu(this.db,r)===void 0;if(o){const V={phase:"hydrating"};await Ed(this.db,r,V),(y=(p=this.opts).onStateChange)==null||y.call(p,r,V),(v=(x=this.opts).onProgress)==null||v.call(x,r,0)}let c=0,h=0,m=!1;try{let V=!1;for(;;){const k=i;let Y;try{Y=await a.queryNotesCursor(I_,k,this.pageLimit)}catch(F){if(!m&&X_(F)){await B0(this.db,r),i="",m=!0;continue}throw F}const $=Y.items??[];if($.length>0&&(await h_(this.db,r,$),h+=$.length,o&&((T=(w=this.opts).onProgress)==null||T.call(w,r,h))),$.length>0&&Y.nextCursor===void 0)throw new Error(`mirror drain: ${$.length}-row page returned no next_cursor — cursor pagination contract violated (stale surface-client?)`);if(Y.nextCursor!==void 0&&(i=Y.nextCursor,await i_(this.db,r,i)),c+=1,$.length===0){V=!0;break}if(Y.nextCursor===k)break;if(c>=this.maxDrainPages)throw new Error(`mirror drain: exceeded ${this.maxDrainPages} pages without exhausting the cursor`)}V&&await o_(this.db,r,Date.now());const H={phase:"live"};return await Ed(this.db,r,H),(_=(E=this.opts).onStateChange)==null||_.call(E,r,H),{pagesApplied:c,notesApplied:h,reWalked:m}}catch(V){const H=V instanceof Error?V.message:String(V),k={phase:"error",lastError:H};return await Ed(this.db,r,k),(M=(R=this.opts).onStateChange)==null||M.call(R,r,k),{pagesApplied:c,notesApplied:h,reWalked:m,error:H}}}async maybeSweep(a,r){if(r.error||r.skipped)return;const i=await u_(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"),()=>H_(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 o=await vh(this.db,r),c=K0(o),h=await Hu(this.db,r),m=T_(h,i.index,c);await m_(this.db,r,m.toDelete);let p=0,y=0;if(a.getNote){for(const x of m.toBackfill){const v=await a.getNote(x,{includeLinks:!0,includeAttachments:!0});v&&(await yh(this.db,r,v),p+=1)}for(const x of m.toRefetch){const v=await a.getNote(x,{includeLinks:!0,includeAttachments:!0});v&&(await yh(this.db,r,v),y+=1)}}return await this.refreshTags(a,r),await c_(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="",o=0;try{for(;;){const c=i,h=await a.queryNotesCursor(Sb,c,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===c)return{index:r,complete:!1};if(o+=1,o>=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 f_(this.db,r,i)}catch{}}ensureSubscription(a){var c;const r=a.client;if(!r.subscribe||((c=this.subscription)==null?void 0:c.vaultId)===a.vaultId)return;this.teardownSubscription();const i=a.vaultId,o=r.subscribe(Sb,{onSnapshot:()=>{},onUpsert:()=>{},onRemove:h=>this.applyWsRemove(i,h)});this.subscription={vaultId:i,unsubscribe:o}}teardownSubscription(){var a;(a=this.subscription)==null||a.unsubscribe(),this.subscription=null}async applyWsRemove(a,r){try{if(Hs(r)||(await vh(this.db,a)).has(r))return;await q0(this.db,a,r)}catch{}}}const J_="lens-blobs";function W_(){return typeof navigator<"u"&&typeof navigator.storage<"u"&&typeof navigator.storage.getDirectory=="function"}async function jd(){return(await navigator.storage.getDirectory()).getDirectoryHandle(J_,{create:!0})}function sk(){return crypto.randomUUID()}class e2{constructor(){fe(this,"backend","opfs")}async put(a,r,i){const o=await jd(),h=await(await o.getFileHandle(a,{create:!0})).createWritable();await h.write(r),await h.close();const p=await(await o.getFileHandle(`${a}.meta`,{create:!0})).createWritable();await p.write(i),await p.close()}async get(a){try{const r=await jd(),c=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:c,mimeType:h}}catch(r){if(r instanceof DOMException&&r.name==="NotFoundError")return null;throw r}}async delete(a){const r=await jd();for(const i of[a,`${a}.meta`])try{await r.removeEntry(i)}catch(o){if(o instanceof DOMException&&o.name==="NotFoundError")continue;throw o}}}class t2{constructor(a){fe(this,"backend","idb");this.db=a}async put(a,r,i,o){await this.db.put("blobs",{blobId:a,data:r,mimeType:i,vaultId:o,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 n2(t){return W_()?new e2:new t2(t)}const a2=3e4;class r2{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??a2,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,o,c;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 T2({db:this.opts.db,client:a.client,vaultId:a.vaultId,blobStore:this.opts.blobStore,...this.opts.mirror&&{mirror:this.opts.mirror}});return(c=(o=this.opts).onDrain)==null||c.call(o,h),h}finally{this.draining=!1}}}async function s2(){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 i2(){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 l2(){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([i2(),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 tw="lens:sync:lastSyncedAt";function o2(){try{const t=localStorage.getItem(tw);if(!t)return null;const a=Number(t);return Number.isFinite(a)?a:null}catch{return null}}const u2={enabled:!1,state:"off",lastSyncedAt:null,syncNow:async()=>{},clearOffline:async()=>{}},nw=b.createContext({db:null,blobStore:null,engine:null,isOnline:!0,isDraining:!1,lastSyncedAt:null,mirror:u2});function c2(t,a,r,i){return t?a?r==="error"?"error":r==="hydrating"||r===void 0&&i===null?"hydrating":"synced":"offline":"off"}function Wt(){return b.useContext(nw)}function f2({children:t}){const[a,r]=b.useState(null),[i,o]=b.useState(null),[c,h]=b.useState(typeof navigator<"u"?navigator.onLine:!0),[m,p]=b.useState(!1),[y,x]=b.useState(()=>o2()),v=ze(),w=ne(se=>se.activeVaultId),T=pt(),E=b.useMemo(()=>ia(),[]),[_,R]=b.useState(void 0),[M,V]=b.useState(void 0),[H,k]=b.useState(null);b.useEffect(()=>{let se=!1,ee=null;return a_().then(O=>{if(se){O.close();return}ee=O,r(O),o(n2(O)),s2()}).catch(()=>{}),()=>{se=!0,ee==null||ee.close()}},[]),b.useEffect(()=>{if(typeof window>"u")return;const se=()=>h(!0),ee=()=>h(!1);return window.addEventListener("online",se),window.addEventListener("offline",ee),()=>{window.removeEventListener("online",se),window.removeEventListener("offline",ee)}},[]);const Y=b.useRef(v),$=b.useRef(w),F=b.useRef(T);Y.current=v,$.current=w,F.current=T;const G=b.useMemo(()=>!a||!i?null:new r2({db:a,blobStore:i,mirror:b_(a),resolveContext:()=>{const se=Y.current,ee=$.current;return!se||!ee?null:{client:se,vaultId:ee}},onDrainStart:()=>{p(!0)},onDrain:se=>{if(p(!1),se.drained>0){const ee=Date.now();x(ee);try{localStorage.setItem(tw,String(ee))}catch{}const O=$.current;F.current.invalidateQueries({queryKey:["notes",O]}),F.current.invalidateQueries({queryKey:["tags",O]}),F.current.invalidateQueries({queryKey:["vaultInfo",O]})}}}),[a,i]);b.useEffect(()=>{if(G)return G.start(),()=>G.stop()},[G]);const Z=b.useMemo(()=>{if(!a||!E)return null;const se=ee=>ee===$.current;return new Z_({db:a,resolveContext:()=>{const ee=Y.current,O=$.current;return!ee||!O?null:{client:ee,vaultId:O}},onStateChange:(ee,O)=>{se(ee)&&(R(O.phase),O.phase==="live"&&(V(void 0),xu(a,ee).then(P=>{se(ee)&&k(P??null)})))},onProgress:(ee,O)=>{se(ee)&&V({done:O})}})},[a,E]);b.useEffect(()=>{if(Z)return Z.start(),()=>Z.stop()},[Z]),b.useEffect(()=>{if(!a||!E||!w){R(void 0),V(void 0),k(null);return}let se=!0;return V(void 0),Promise.all([l_(a,w),xu(a,w)]).then(([ee,O])=>{se&&(R(ee==null?void 0:ee.phase),k(O??null))}),()=>{se=!1}},[a,E,w]);const le=b.useCallback(async()=>{await(Z==null?void 0:Z.syncOnce())},[Z]),de=b.useCallback(async()=>{!a||!w||(await Q_(w,async()=>{await y_(a,w),await B0(a,w),await d_(a,w)}),R(void 0),V(void 0),k(null),T.invalidateQueries({queryKey:["notes",w]}),T.invalidateQueries({queryKey:["notesForDateViews",w]}),T.invalidateQueries({queryKey:["notesForPathTree",w]}),T.invalidateQueries({queryKey:["tags",w]}))},[a,w,T]),ge=b.useMemo(()=>({enabled:E,state:c2(E,c,_,H),progress:M,lastSyncedAt:H,syncNow:le,clearOffline:de}),[E,c,_,M,H,le,de]),we=b.useMemo(()=>({db:a,blobStore:i,engine:G,isOnline:c,isDraining:m,lastSyncedAt:y,mirror:ge}),[a,i,G,c,m,y,ge]);return u.jsx(nw.Provider,{value:we,children:t})}const Vt={pinned:"pinned",archived:"archived",captureVoice:"capture",captureText:"capture",view:"view"},ik=["pinned","archived","captureVoice","captureText","view"],d2="lens:tag-roles:";function h2(t){return d2+t}function Xi(t,a){if(typeof t!="string")return a;const r=t.trim().replace(/^#/,"");return r.length>0?r:a}function Qu(t){if(!t||typeof t!="object")return{...Vt};const a=t;return{pinned:Xi(a.pinned,Vt.pinned),archived:Xi(a.archived,Vt.archived),captureVoice:Xi(a.captureVoice,Vt.captureVoice),captureText:Xi(a.captureText,Vt.captureText),view:Xi(a.view,Vt.view)}}function m2(t){try{const a=localStorage.getItem(h2(t));return a?Qu(JSON.parse(a)):{...Vt}}catch{return{...Vt}}}const Nr=".parachute/notes/settings",aw=1,la={schemaVersion:aw,tagRoles:{...Vt}};function xh(t){if(!t||typeof t!="object")return{...la,tagRoles:{...Vt}};const a=t,r=typeof a.schemaVersion=="number"?a.schemaVersion:aw,i=Qu(a.tagRoles);return{schemaVersion:r,tagRoles:i}}function vm(t){if(!t||!t.metadata||typeof t.metadata!="object")return{...la,tagRoles:{...Vt}};const a=t.metadata;return xh(a.notes??a.lens)}function ra(t,a){return{schemaVersion:a.schemaVersion??t.schemaVersion,tagRoles:a.tagRoles?Qu({...t.tagRoles,...a.tagRoles}):t.tagRoles}}function p2(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 g2="notes:settings:";function rw(t){return g2+t}function sw(t){return{settings:t??{...la,tagRoles:{...Vt}},serverSettings:t,serverUpdatedAt:null,noteExists:!1,dirtyPatch:null}}function y2(t){try{const a=localStorage.getItem(rw(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?xh(r.serverSettings):null,o=r.dirtyPatch??null,c=i??{...la,tagRoles:{...Vt}};return{settings:o?ra(c,o):xh(r.settings??c),serverSettings:i,serverUpdatedAt:typeof r.serverUpdatedAt=="string"?r.serverUpdatedAt:null,noteExists:r.noteExists===!0,dirtyPatch:o}}catch{return null}}function nu(t,a){try{localStorage.setItem(rw(t),JSON.stringify(a))}catch{}}function v2(t){if(typeof localStorage>"u"||!localStorage.getItem(`lens:tag-roles:${t}`))return null;const r={tagRoles:m2(t)};return{settings:ra(la,r),serverSettings:null,serverUpdatedAt:null,noteExists:!1,dirtyPatch:r}}function b2(t){const a=y2(t);if(a)return a;const r=v2(t);return r||sw(null)}async function Eb(t,a,r,i){if(!a.noteExists){const o=ra(a.serverSettings??la,r);try{const c=await t.createNote({path:Nr,content:"",metadata:{notes:o}},{signal:i});return{server:o,serverUpdatedAt:c.updatedAt??c.createdAt??null,noteExists:!0}}catch(c){if(c instanceof ta||x2(c))return Nd(t,r,i);throw c}}if(a.serverUpdatedAt&&a.serverSettings)try{const o=ra(a.serverSettings,r),c=await t.updateNote(Nr,{metadata:{notes:o},if_updated_at:a.serverUpdatedAt},{signal:i});return{server:o,serverUpdatedAt:c.updatedAt??a.serverUpdatedAt,noteExists:!0}}catch(o){if(o instanceof ta)return Nd(t,r,i);throw o}return Nd(t,r,i)}async function Nd(t,a,r){let i=null;try{i=await t.getNote(Nr)}catch(p){if(!(p instanceof El))throw p;i=null}if(!i){const p=ra(la,a),y=await t.createNote({path:Nr,content:"",metadata:{notes:p}},{signal:r});return{server:p,serverUpdatedAt:y.updatedAt??y.createdAt??null,noteExists:!0}}const o=vm(i),c=ra(o,a),h=i.updatedAt??i.createdAt,m=await t.updateNote(Nr,{metadata:{notes:c},if_updated_at:h},{signal:r});return{server:c,serverUpdatedAt:m.updatedAt??h??null,noteExists:!0}}function x2(t){if(!(t instanceof Error))return!1;const a=t.message.toLowerCase();return a.includes("already exists")||a.includes("duplicate")||a.includes("conflict")}function w2(t){const a=ze(),r=pt(),{db:i}=Wt(),o=b.useMemo(()=>t?b2(t):sw(null),[t]),[c,h]=b.useState(o),[m,p]=b.useState(a?"loading":"offline");b.useEffect(()=>{h(o),p(a?"loading":"offline")},[o,a]);const y=ct({queryKey:["vault-settings",t],enabled:!!t&&!!a,queryFn:async()=>{try{const v=await a.getNote(Nr);return v?{server:vm(v),serverUpdatedAt:v.updatedAt??v.createdAt??null,noteExists:!0}:{server:null,serverUpdatedAt:null,noteExists:!1}}catch(v){if(!(v instanceof El))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(c.dirtyPatch){const T=c.dirtyPatch;(async()=>{try{const E=await Eb(a,{serverSettings:v.server,serverUpdatedAt:v.serverUpdatedAt,noteExists:v.noteExists},T),_={settings:E.server,serverSettings:E.server,serverUpdatedAt:E.serverUpdatedAt,noteExists:!0,dirtyPatch:null};h(_),nu(t,_),p("synced"),r.invalidateQueries({queryKey:["vault-settings",t]})}catch{p("offline")}})();return}const w=v.server?{settings:v.server,serverSettings:v.server,serverUpdatedAt:v.serverUpdatedAt,noteExists:v.noteExists,dirtyPatch:null}:{settings:c.settings,serverSettings:null,serverUpdatedAt:null,noteExists:!1,dirtyPatch:null};h(w),nu(t,w),p("synced")},[t,a,y.data]),b.useEffect(()=>{y.isError&&p("offline")},[y.isError]);const x=b.useCallback(async v=>{if(!t)return;const w=p2(c.dirtyPatch,v),E={settings:ra(c.serverSettings??la,w),serverSettings:c.serverSettings,serverUpdatedAt:c.serverUpdatedAt,noteExists:c.noteExists,dirtyPatch:w};if(h(E),nu(t,E),!a){p("offline");return}const _=i?async()=>(await Tl(i,{kind:"update-settings",notePath:Nr,patch:w,baselineUpdatedAt:c.serverUpdatedAt},{vaultId:t}),null):null;try{const R=await Iu(M=>Eb(a,{serverSettings:c.serverSettings,serverUpdatedAt:c.serverUpdatedAt,noteExists:c.noteExists},v,M),_);if(R){const M={settings:R.server,serverSettings:R.server,serverUpdatedAt:R.serverUpdatedAt,noteExists:!0,dirtyPatch:null};h(M),nu(t,M),p("synced"),r.invalidateQueries({queryKey:["vault-settings",t]})}else p(Zs()?"offline":"queued")}catch(R){R instanceof ta?p("conflict"):p("offline")}},[t,a,i,c,r]);return{settings:c.settings,update:x,status:m}}function Xs(t){const{settings:a,update:r}=w2(t),i=b.useCallback(o=>{if(!t)return;const c=o??{...Vt};r({tagRoles:Qu(c)})},[t,r]);return{roles:a.tagRoles,setRoles:i}}const iw="auth-halted",S2=600*1e3;function E2(t){const a=2**t*1e3;return Math.min(a,S2)}async function Tl(t,a,r){const i={id:crypto.randomUUID(),vaultId:r.vaultId,mutation:a,createdAt:Date.now(),attemptCount:0,nextAttemptAt:0,status:"pending"},o=await t.add("pending",i);return{...i,seq:o}}async function lw(t,a){return a?t.getAllFromIndex("pending","by-vault",a):t.getAll("pending")}async function T2(t){const a=t.now??(()=>Date.now()),r={drained:0,stashed:0,deferred:0,authHalted:!1};for(;;){const i=await j2(t.db,t.vaultId,a());if(!i)break;try{await N2(t,i),await t.db.delete("pending",i.seq),r.drained+=1}catch(o){if(o instanceof qu){await Fs(t.db,iw,{vaultId:t.vaultId,at:a(),message:o.message}),r.authHalted=!0,await Tb(t.db,i,o,a),r.deferred+=1;break}if(o instanceof ta){await t.db.put("pending",{...i,status:"needs-human",lastError:`Conflict: current=${o.currentUpdatedAt??"?"} expected=${o.expectedUpdatedAt??"?"}`,attemptCount:i.attemptCount+1}),r.stashed+=1;continue}if(o instanceof hr){await t.db.put("pending",{...i,attemptCount:i.attemptCount+1,lastError:o.message,nextAttemptAt:a()+5e3}),r.deferred+=1;break}if(o instanceof El){await t.db.delete("pending",i.seq),r.drained+=1;continue}await Tb(t.db,i,o,a),r.deferred+=1;break}}return r}async function j2(t,a,r){let o=await t.transaction("pending","readonly").store.openCursor();for(;o;){const c=o.value;if(c.vaultId===a&&c.status==="pending"&&c.nextAttemptAt<=r)return c;o=await o.continue()}return null}async function Tb(t,a,r,i){const o=a.attemptCount+1;await t.put("pending",{...a,attemptCount:o,nextAttemptAt:i()+E2(o),lastError:r instanceof Error?r.message:String(r)})}class hr extends Error{}async function N2(t,a){var i,o,c;const r=a.mutation;switch(r.kind){case"create-note":{const h=await t.client.createNote(r.payload);await HA(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 ws(t.db,r.targetId,t.vaultId);if(!h)throw new hr(`Awaiting local id ${r.targetId}`);const m=await R2(t.client,h,r.payload,r.baselineUpdatedAt);m&&await((o=t.mirror)==null?void 0:o.upsert(t.vaultId,m));return}case"update-settings":{await C2(t.client,r.notePath,r.patch);return}case"delete-note":{const h=await ws(t.db,r.targetId,t.vaultId);if(!h)throw new hr(`Awaiting local id ${r.targetId}`);await t.client.deleteNote(h),await((c=t.mirror)==null?void 0:c.remove(t.vaultId,h));return}case"upload-attachment":{const h=await t.blobStore.get(r.blobId);if(!h)throw new hr(`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 $A(t.db,r.blobId,y.path,t.vaultId),await t.blobStore.delete(r.blobId);return}case"link-attachment":{const h=await ws(t.db,r.noteId,t.vaultId);if(!h)throw new hr(`Awaiting local id ${r.noteId}`);let m=r.pathRef;if(L0(r.pathRef)&&(m=await qA(t.db,r.pathRef,t.vaultId),!m))throw new hr(`Awaiting blob ${U0(r.pathRef)}`);await t.client.linkAttachment(h,{path:m,mimeType:r.mimeType,...r.transcribe!==void 0?{transcribe:r.transcribe}:{},...r.segment_index!==void 0?{segment_index:r.segment_index}:{}});return}case"delete-attachment":{const h=await ws(t.db,r.noteId,t.vaultId);if(!h)throw new hr(`Awaiting local id ${r.noteId}`);await t.client.deleteAttachment(h,r.attachmentId);return}}}async function A2(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 _2(t,a){await t.delete("pending",a)}const Ad=3,jb=3;async function R2(t,a,r,i){let o=i;for(let c=0;c<=jb;c++){const h=o?{...r,if_updated_at:o}:{...r};try{return await t.updateNote(a,h)}catch(m){if(m instanceof ta&&c<jb){if(m.currentUpdatedAt)o=m.currentUpdatedAt;else{const p=await t.getNote(a);if(!p)throw new El(`Note ${a} disappeared during retry`);o=p.updatedAt??p.createdAt}continue}if(m instanceof ta)return await t.updateNote(a,{...r,force:!0});throw m}}}async function C2(t,a,r){for(let i=0;i<=Ad;i++){let o=null;try{o=await t.getNote(a)}catch(p){if(!(p instanceof El))throw p}if(!o)try{await t.createNote({path:a,content:"",metadata:{notes:ra(la,r)}});return}catch(p){if(p instanceof ta&&i<Ad)continue;throw p}const c=vm(o),h=ra(c,r),m=o.updatedAt??o.createdAt;try{await t.updateNote(a,{metadata:{notes:h},if_updated_at:m});return}catch(p){if(p instanceof ta&&i<Ad)continue;if(p instanceof ta){await t.updateNote(a,{metadata:{notes:h},force:!0});return}throw p}}}async function M2(t,a){const r=await lw(t,a),i=t.transaction("pending","readwrite");for(const o of r)await i.store.delete(o.seq);return await i.done,r.length}let O2=1;const sa=Ka(t=>({toasts:[],push(a,r,i){const o=O2++;return t(c=>({toasts:[...c.toasts,{id:o,message:a,tone:r??"info",durationMs:i==null?void 0:i.durationMs}]})),o},dismiss(a){t(r=>({toasts:r.toasts.filter(i=>i.id!==a)}))},clear(){t({toasts:[]})}})),Su="lens:auth-halt:";function Nb(){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(Su)))continue;const i=localStorage.getItem(r);if(i)try{const o=JSON.parse(i);o!=null&&o.vaultId&&(t[o.vaultId]=o)}catch{}}}catch{}return t}const Ar=Ka(t=>({byVault:Nb(),markHalted(a,r){const i={vaultId:a,reason:r,at:Date.now()};try{localStorage.setItem(Su+a,JSON.stringify(i))}catch{}t(o=>({byVault:{...o.byVault,[a]:i}}))},clearHalt(a){try{localStorage.removeItem(Su+a)}catch{}t(r=>{if(!(a in r.byVault))return r;const{[a]:i,...o}=r.byVault;return{byVault:o}})},reloadFromStorage(){t({byVault:Nb()})}})),D2=Su,k2=Mx;function bm({queryKey:t,params:a,client:r,enabled:i=!0}){const o=pt(),[c,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(!k2(y))return;let x=!0;const v=pT(r,y),w=v.getList();let T=null;const E=()=>{if(!x)return;const R=v.getState();h(R.status==="live"),R.list!==w&&R.list!==T&&(T=R.list,o.setQueryData(t,R.list))},_=v.subscribe(E);return E(),()=>{x=!1,h(!1),_(),v.close()}},[r,m,p,i,o]),{isLive:c}}const mr=50,ow={search:"",tags:[],tagMatch:"any",pathPrefix:"",sort:"desc",limit:mr,offset:0};function L2(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 U2(t){return t.search.trim().length>0||t.tags.length>0||t.pathPrefix.trim().length>0}const z2=6e4;class uw extends Error{constructor(a){super(`This date window reached its ${a.toLocaleString()}-note safety ceiling. Retry after narrowing the window or filters.`),this.name="DateViewOverflowError"}}function xm(t){return t instanceof uw}function V2(t){return xm(t)?!1:z2}const B2=3,au=[1e3,2e3,4e3,8e3,16e3,3e4];function H2(t){return{vaultId:t,state:"healthy",consecutiveFailures:0,lastErrorAt:null,lastErrorReason:null,nextProbeAt:null,backoffIndex:0}}function q2(t){const a=Math.min(t,au.length-1);return au[a]??au[au.length-1]??3e4}const Mr=Ka(t=>({byVault:{},reportSignal(a,r,i){t(o=>{const c=o.byVault[a]??H2(a);if(r==="healthy"){if(!(a in o.byVault))return o;const{[a]:v,...w}=o.byVault;return{byVault:w}}const h=c.consecutiveFailures+1,m=c.backoffIndex+1,p=h>=B2?"down":"retrying",y=Date.now(),x={vaultId:a,state:p,consecutiveFailures:h,lastErrorAt:y,lastErrorReason:i??null,nextProbeAt:y+q2(m),backoffIndex:m};return{byVault:{...o.byVault,[a]:x}}})},resetToHealthy(a){t(r=>{if(!(a in r.byVault))return r;const{[a]:i,...o}=r.byVault;return{byVault:o}})}})),$2="Parachute Notes";async function cw(t,a=fetch.bind(globalThis)){return $E(t,a)}async function Q2(t,a,r=fetch.bind(globalThis)){return QE(t,{clientName:$2,redirectUri:a},r)}const I2="/oauth/callback",K2="vault:read vault:write";function G2(){return yl()}function Y2(t=window.location.origin){return`${t.replace(/\/$/,"")}${G2()}${I2}`}function P2(t){let a;try{a=new URL(Vh(t))}catch{return}const r=a.pathname.match(/^\/vault\/([^/]+)$/);if(r!=null&&r[1])try{return decodeURIComponent(r[1])}catch{return}}async function wm(t,a=K2,r=fetch.bind(globalThis),i={}){const o=Vh(t),c=Y2(),h=await cw(o,r);let m=CN(h.issuer,c);m||(m=(await Q2(h.registration_endpoint,c,r)).client_id,MN(h.issuer,c,m));const p=YE(),y=await PE(p),x=FE(),v={issuerUrl:o,issuer:h.issuer,tokenEndpoint:h.token_endpoint,clientId:m,codeVerifier:p,state:x,redirectUri:c,scope:a,startedAt:new Date().toISOString(),...i.priorHaltedVaultId?{priorHaltedVaultId:i.priorHaltedVaultId}:{},...i.redirect?{redirect:i.redirect}:{}};RN(v);const w=new URL(h.authorization_endpoint);if(w.searchParams.set("response_type","code"),w.searchParams.set("client_id",m),w.searchParams.set("redirect_uri",c),w.searchParams.set("code_challenge",y),w.searchParams.set("code_challenge_method","S256"),w.searchParams.set("state",x),w.searchParams.set("scope",a),i.params)for(const[T,E]of Object.entries(i.params))w.searchParams.has(T)||w.searchParams.set(T,E);if(!w.searchParams.has("vault")){const T=P2(o);T&&w.searchParams.set("vault",T)}return{authorizeUrl:w.toString(),pending:v}}function F2(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 X2(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=F2(r.approve_url);return i?{approveUrl:i}:null}async function lk(t,a,r=fetch.bind(globalThis)){const i=_N();if(!i)throw new Error("No pending OAuth flow. Start the connect flow from the vault page.");if(i.state!==a)throw Wo(),new Error("OAuth state mismatch. The flow was likely interrupted; please try again.");const o=new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:i.codeVerifier,client_id:i.clientId,redirect_uri:i.redirectUri}),c=await r(i.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:o.toString()});if(!c.ok){const m=await c.text();Wo();const p=X2(m);throw p?new ZE(p.approveUrl):new Error(`Token exchange failed (${c.status}): ${m}`)}const h=await c.json();if(!h.access_token)throw Wo(),new Error("Token response missing access_token");return Wo(),{pending:i,token:h}}async function Z2(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 c=await i.text();throw new Ax(i.status,c)}const o=await i.json();if(!o.access_token)throw new Error("Refresh response missing access_token");return o}const _d=new Map;async function J2(t){const a=_d.get(t);if(a)return a;const r=W2(t).finally(()=>{_d.delete(t)});return _d.set(t,r),r}async function W2(t){const a=ne.getState().vaults[t];if(a){const{isHostedVaultRecord:i,remintHostedVault:o}=await Ke(async()=>{const{isHostedVaultRecord:c,remintHostedVault:h}=await Promise.resolve().then(()=>FN);return{isHostedVaultRecord:c,remintHostedVault:h}},[]);if(i(a.clientId)){try{await o(a.name);const c=Vs(t);if(c!=null&&c.accessToken)return Ar.getState().clearHalt(t),c.accessToken}catch{}return null}}const r=Vs(t);if(!(r!=null&&r.refreshToken)||!(a!=null&&a.tokenEndpoint)||!a.clientId)return null;try{const i=await Z2({tokenEndpoint:a.tokenEndpoint,clientId:a.clientId,refreshToken:r.refreshToken}),o=XE(i);return!o.refreshToken&&r.refreshToken&&(o.refreshToken=r.refreshToken),o0(t,o),Ar.getState().clearHalt(t),o.accessToken}catch(i){if(i instanceof Ax&&i.status>=400&&i.status<500){const o=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.`;Ar.getState().markHalted(t,o)}return null}}const Eu=new Map;function eR(t,a){return`${t}\0${a}`}ne.subscribe(t=>{for(const a of[...Eu.keys()]){const r=a.indexOf("\0"),i=a.slice(0,r),o=a.slice(r+1),c=t.vaults[i];(!c||c.url!==o)&&Eu.delete(a)}});function ze(){const t=ne(r=>r.activeVaultId),a=ne(r=>{var o;const i=r.activeVaultId;return i?((o=r.vaults[i])==null?void 0:o.url)??null:null});return b.useMemo(()=>{if(!t||!a)return null;const r=Vs(t);if(!r)return null;const i=eR(t,a),o=Eu.get(i);if(o)return o.setAccessToken(r.accessToken),o;const c=new S_({vaultUrl:a,accessToken:r.accessToken,onAuthError:()=>J2(t),onAuthRevoked:h=>Ar.getState().markHalted(t,`Vault rejected the current session (${h}).`),onReachability:(h,m)=>Mr.getState().reportSignal(t,h,m)});return Eu.set(i,c),c},[t,a])}async function Sm(t,a,r,i){const o=()=>t&&a?I0(t,a,r):Promise.resolve(null);if(t&&a&&Zs()){const c=await o();if(c)return c}try{return await i()}catch(c){if(c instanceof ll){const h=await o();if(h)return h}throw c}}async function tR(t,a,r,i){const o=()=>t&&a&&r?Q0(t,a,r):Promise.resolve(void 0);if(t&&a&&r&&Zs()){const c=await o();if(c)return c}try{return await i()}catch(c){if(c instanceof ll){const h=await o();if(h)return h}throw c}}async function nR(t,a,r){const i=()=>t&&a?H0(t,a):Promise.resolve(void 0);if(t&&a&&Zs()){const o=await i();if(o)return o}try{return await r()}catch(o){if(o instanceof ll){const c=await i();if(c)return c}throw o}}function Em(t,a,r,i){const[o,c]=b.useState(void 0),h=r.toString();return b.useEffect(()=>{if(!i||!t||!a){c(void 0);return}let m=!0;return I0(t,a,new URLSearchParams(h)).then(p=>{m&&p&&c(p)}).catch(()=>{}),()=>{m=!1}},[i,t,a,h]),o}function aR(t,a,r,i){const[o,c]=b.useState(void 0);return b.useEffect(()=>{if(c(void 0),!i||!t||!a||!r)return;let h=!0;return Q0(t,a,r).then(m=>{h&&m&&c(m)}).catch(()=>{}),()=>{h=!1}},[i,t,a,r]),o}function rR(t,a,r){const[i,o]=b.useState(void 0);return b.useEffect(()=>{if(!r||!t||!a){o(void 0);return}let c=!0;return H0(t,a).then(h=>{c&&h&&o(h)}).catch(()=>{}),()=>{c=!1}},[r,t,a]),i}function fw(){const t=ze(),a=ne(r=>r.activeVaultId);return ct({queryKey:["vaultInfo",a],enabled:!!t,queryFn:()=>t.vaultInfo(!0),staleTime:3e4})}function ok(){return dw().capability}function dw(){var m,p,y;const t=ze(),a=ne(x=>x.activeVaultId),r=fw(),i=!!t&&r.isSuccess&&((m=r.data)==null?void 0:m.transcription)===void 0,o=ct({queryKey:["vaultLanding",a],enabled:i,queryFn:()=>t.vaultLanding(),staleTime:5*6e4,retry:!1}),c=r.isSuccess||r.isError,h=!i||o.isSuccess||o.isError;return{capability:((p=r.data)==null?void 0:p.transcription)??((y=o.data)==null?void 0:y.transcription),settled:c&&h}}function hw(t,a){const r=ze(),i=ne(v=>v.activeVaultId),{db:o}=Wt(),c=ia(),h=(a==null?void 0:a.live)??!0,m=b.useMemo(()=>["notes",i,t],[i,t]),p=b.useMemo(()=>{const v=L2(t);return v.set("include_content","false"),v},[t]),{isLive:y}=bm({queryKey:m,params:p,client:r,enabled:h}),x=Em(o,i,p,c);return ct({queryKey:m,enabled:!!r,queryFn:()=>c?Sm(o,i,p,()=>r.queryNotes(p)):r.queryNotes(p),staleTime:y?Number.POSITIVE_INFINITY:1e4,refetchInterval:y?!1:3e4,refetchOnWindowFocus:!y,placeholderData:c?v=>v??x:x0,networkMode:c?"always":"online"})}const Tm=5e3;function sR(t){const a=ze(),r=ne(i=>i.activeVaultId);return ct({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(Tm)),a.queryNotes(i)},staleTime:6e4})}const iR=5e3;function lR({field:t,from:a,to:r,excludeTag:i,limit:o,enabled:c=!0}){const h=ze(),m=ne(E=>E.activeVaultId),{db:p}=Wt(),y=ia(),x=b.useMemo(()=>{const E=new URLSearchParams;return E.set("sort","desc"),E.set(`meta[${t}][gte]`,a),r&&E.set(`meta[${t}][lt]`,r),i&&E.set("exclude_tag",i),E.set("limit",String(o)),E.set("include_content","false"),E},[i,t,a,o,r]),v=x.toString(),w=b.useMemo(()=>["notesForDateViews",m,v],[m,v]),T=Em(p,m,x,y);return ct({queryKey:w,enabled:!!h&&c,queryFn:async()=>{const E=await(y?Sm(p,m,x,()=>h.queryNotes(x)):h.queryNotes(x));if(E.length>=o)throw new uw(o);return E},staleTime:6e4,refetchInterval:E=>V2(E.state.error),refetchOnWindowFocus:E=>!xm(E.state.error),placeholderData:y?E=>E??T:void 0,networkMode:y?"always":"online"})}function oR(t){const a=ze(),r=ne(m=>m.activeVaultId),{db:i}=Wt(),o=ia(),c=b.useMemo(()=>{const m=new URLSearchParams;return m.set("sort","desc"),m.set("limit",String(Tm)),m},[]),h=Em(i,r,c,o&&t);return ct({queryKey:["notesForPathTree",r],enabled:!!a&&t,queryFn:()=>o?Sm(i,r,c,()=>a.queryNotes(c)):a.queryNotes(c),staleTime:6e4,placeholderData:o?m=>m??h:void 0,networkMode:o?"always":"online"})}function uk(){const t=ze(),a=ne(r=>r.activeVaultId);return ct({queryKey:["allNotesWithLinks",a],enabled:!!t,queryFn:()=>{const r=new URLSearchParams;return r.set("include_links","true"),r.set("sort","desc"),r.set("limit",String(Tm)),t.queryNotes(r)},staleTime:6e4})}function uR(){const t=ze(),a=ne(c=>c.activeVaultId),{db:r}=Wt(),i=ia(),o=rR(r,a,i);return ct({queryKey:["tags",a],enabled:!!t,queryFn:()=>i?nR(r,a,()=>t.listTags()):t.listTags(),staleTime:6e4,placeholderData:i?c=>c??o:void 0,networkMode:i?"always":"online"})}function cR(){const t=ze(),a=ne(r=>r.activeVaultId);return ct({queryKey:["tags",a,"with-schema"],enabled:!!t,queryFn:()=>t.listTags({includeSchema:!0}),staleTime:6e4})}function ck(t){const a=ze(),r=ne(i=>i.activeVaultId);return ct({queryKey:["tag",r,t],enabled:!!a&&!!t,queryFn:()=>a.getTag(t),staleTime:3e4})}function fk(){const t=ze(),a=ne(i=>i.activeVaultId),r=pt();return Rn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.updateTag(i.name,i.payload)},onSuccess:(i,o)=>{r.setQueryData(["tag",a,o.name],i),r.invalidateQueries({queryKey:["tags",a]})}})}function fR(t,a){return t&&Hs(t)&&!(a&&!Hs(a.id))?2e3:a&&N_(a)?4e3:!1}function dR(t){const a=ze(),r=ne(m=>m.activeVaultId),{db:i}=Wt(),o=pt(),c=ia(),h=aR(i,r,t,c);return ct({queryKey:["note",r,t],enabled:!!a&&!!t,queryFn:()=>{const m=async()=>{if(t&&Hs(t)){const p=i&&r?await ws(i,t,r):null;if(!p){const y=o.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 c?tR(i,r,t,m):m()},refetchInterval:m=>fR(t,m.state.data),staleTime:1e4,placeholderData:c?h:void 0,networkMode:c?"always":"online"})}const hR=8e3;function Zs(){return typeof navigator<"u"&&navigator.onLine===!1}async function Iu(t,a){if(a&&Zs())return a();const r=new AbortController,i=setTimeout(()=>r.abort(new Error("offline-timeout")),hR);try{return await t(r.signal)}catch(o){if(a)return a();throw o}finally{clearTimeout(i)}}function mR(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 pR(t,a,r){const i=BA();return await Tl(t,{kind:"create-note",localId:i,payload:r},{vaultId:a}),mR(r,i)}async function gR(t,a,r,i,o){const c=o==null?void 0:o.updatedAt;return await Tl(t,{kind:"update-note",targetId:r,payload:i,...c&&{baselineUpdatedAt:c}},{vaultId:a}),{...o??{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 yR(t){const a=ze(),r=ne(c=>c.activeVaultId),{db:i}=Wt(),o=pt();return Rn({mutationFn:async c=>{if(!t)throw new Error("No note id");return Iu(m=>{if(!a)throw new Error("No active vault");return a.updateNote(t,c,{signal:m})},i&&r?()=>{const m=o.getQueryData(["note",r,t]);return gR(i,r,t,c,m)}:null)},onSuccess:c=>{o.setQueryData(["note",r,t],c),o.setQueriesData({queryKey:["viewList",r]},h=>h==null?void 0:h.map(m=>m.id===t?c:m)),o.invalidateQueries({queryKey:["viewList",r]}),o.invalidateQueries({queryKey:["notes",r]}),o.invalidateQueries({queryKey:["notesForDateViews",r]}),o.invalidateQueries({queryKey:["tags",r]}),c!=null&&c.id&&c.id!==t&&o.setQueryData(["note",r,c.id],c),i&&r&&c&&pm(i,r,c)}})}function mw(){const t=ze(),a=ne(o=>o.activeVaultId),{db:r}=Wt(),i=pt();return Rn({mutationFn:async o=>Iu(h=>{if(!t)throw new Error("No active vault");return t.createNote(o,{signal:h})},r&&a?()=>pR(r,a,o):null),onSuccess:o=>{i.setQueryData(["note",a,o.id],o),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&&pm(r,a,o)}})}function dk(){const t=ze();return Rn({mutationFn:async a=>{if(!t)throw new Error("No active vault");return t.uploadStorageFile(a.file,{onProgress:a.onProgress,signal:a.signal})}})}function hk(){const t=ze(),a=ne(i=>i.activeVaultId),r=pt();return Rn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.linkAttachment(i.noteId,{path:i.path,mimeType:i.mimeType})},onSuccess:(i,o)=>{r.invalidateQueries({queryKey:["note",a,o.noteId]})}})}function mk(){const t=ze(),a=ne(o=>o.activeVaultId),r=pt(),i=sa(o=>o.push);return Rn({mutationFn:async o=>{if(!t)throw new Error("No active vault");await t.retryTranscription(o.serverId)},onMutate:async({cacheId:o})=>{const c=["note",a,o];await r.cancelQueries({queryKey:c});const h=r.getQueryData(c);return h&&r.setQueryData(c,A_(h)),{prev:h,key:c}},onError:(o,c,h)=>{h!=null&&h.prev&&h.key&&r.setQueryData(h.key,h.prev),i("Couldn't retry transcription right now.","error")},onSettled:(o,c,{cacheId:h})=>{r.invalidateQueries({queryKey:["note",a,h]})}})}function pk(){const t=ze(),a=ne(o=>o.activeVaultId),{db:r}=Wt(),i=pt();return Rn({mutationFn:async o=>{if(Zs()&&r&&a)return await Tl(r,{kind:"delete-attachment",noteId:o.noteId,attachmentId:o.attachmentId},{vaultId:a}),o;if(!t)throw new Error("No active vault");return await t.deleteAttachment(o.noteId,o.attachmentId),o},onSuccess:o=>{i.invalidateQueries({queryKey:["note",a,o.noteId]})}})}function gk(){const t=ze(),a=ne(i=>i.activeVaultId),r=pt();return Rn({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 yk(){const t=ze(),a=ne(i=>i.activeVaultId),r=pt();return Rn({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 vk(){const t=ze(),a=ne(o=>o.activeVaultId),{db:r}=Wt(),i=pt();return Rn({mutationFn:async o=>Iu(async h=>{if(!t)throw new Error("No active vault");return await t.deleteNote(o,{signal:h}),o},r&&a?async()=>(await Tl(r,{kind:"delete-note",targetId:o},{vaultId:a}),o):null),onSuccess:o=>{i.removeQueries({queryKey:["note",a,o]}),i.invalidateQueries({queryKey:["notes",a]}),i.invalidateQueries({queryKey:["notesForDateViews",a]}),i.invalidateQueries({queryKey:["tags",a]}),i.invalidateQueries({queryKey:["vaultInfo",a]}),i.invalidateQueries({queryKey:["hasUserAuthoredNote",a]}),r&&a&&$0(r,a,o)}})}function vR(){b.useEffect(()=>{if(typeof window>"u")return;function t(a){if(a.key===null){ne.setState({vaults:Fd(),activeVaultId:Xd()}),Ar.getState().reloadFromStorage();return}if(a.key===yu){ne.setState({activeVaultId:Xd()});return}if(a.key===Xh){ne.setState({vaults:Fd()});return}if(a.key.startsWith(D2)){Ar.getState().reloadFromStorage();return}}return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[])}const bk={search:"",tags:[]};function bR(t){const a=new Map;for(const c of t)a.set(c.id,c);const r=new Map,i=new Map;for(const c of t)for(const h of c.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(c=>{var m;const h=c.tags??[];return{id:c.id,path:c.path,title:xR(c),tags:h,topTag:h[0],degree:i.get(c.id)??0,summary:typeof((m=c.metadata)==null?void 0:m.summary)=="string"?c.metadata.summary:void 0}}),edges:[...r.values()]}}function xR(t){return t.path?(t.path.split("/").pop()??t.path).replace(/\.md$/i,""):t.id}function xk(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(o=>t.tags.includes(o)))}function wk(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 Sk(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 wR(t){try{return new URL(t.issuer).origin}catch{return null}}function SR(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 ER(t,a=fetch.bind(globalThis),r){const i=`${t.replace(/\/$/,"")}/.well-known/parachute.json`;let o;try{o=await a(i,{headers:{Accept:"application/json"},signal:r})}catch{return null}if(!o.ok)return null;let c;try{c=await o.json()}catch{return null}if(typeof c!="object"||c===null)return null;const h=c.vaults;return Array.isArray(h)?h.filter(SR):null}const TR=15,jR=2;function NR(t){if(!t||t.length===0)return 0;const a=bR([...t]);let r=0;for(const i of a.nodes)i.degree>0&&r++;return r}function AR(t,a){return t>=jR||a>=TR}function pw(){const t=ne(o=>Object.keys(o.vaults).length),a=ne(o=>o.activeVaultId),r=ct({queryKey:["allNotesWithLinks",a],queryFn:()=>{throw new Error("useMapEarned reads the query cache only")},enabled:!1}),i=b.useMemo(()=>NR(r.data),[r.data]);return AR(t,i)}const _R="lens:pinned-tags:";function gw(t){return _R+t}function wh(t){return t.trim().replace(/^#/,"")}function jm(t){const a=new Set,r=[];for(const i of t){const o=wh(i);if(!o)continue;const c=o.toLowerCase();a.has(c)||(a.add(c),r.push(o))}return r}function Ab(t){try{const a=localStorage.getItem(gw(t));if(!a)return[];const r=JSON.parse(a);return Array.isArray(r)?jm(r.filter(i=>typeof i=="string")):[]}catch{return[]}}function _b(t,a){try{localStorage.setItem(gw(t),JSON.stringify(jm(a)))}catch{}}function RR(t){const[a,r]=b.useState(()=>t?Ab(t):[]);b.useEffect(()=>{r(t?Ab(t):[])},[t]);const i=b.useCallback(h=>{if(!t)return;const m=jm(h);_b(t,m),r(m)},[t]),o=b.useCallback(h=>{if(!t)return;const m=wh(h);m&&r(p=>{const x=p.some(v=>v.toLowerCase()===m.toLowerCase())?p.filter(v=>v.toLowerCase()!==m.toLowerCase()):[...p,m];return _b(t,x),x})},[t]),c=b.useCallback(h=>{const m=wh(h).toLowerCase();return a.some(p=>p.toLowerCase()===m)},[a]);return{pinnedTags:a,setPinnedTags:i,togglePin:o,isPinned:c}}const yw=2500,CR="http://127.0.0.1:1939";async function Rd(t,a=yw,r=fetch.bind(globalThis)){return MR(t,a,r)}async function MR(t,a,r){const i=new AbortController,o=setTimeout(()=>i.abort(),a),c=(h,m)=>r(h,{...m??{},signal:i.signal});try{return await cw(t,c),t}catch{return null}finally{clearTimeout(o)}}async function vw(t,a=yw,r=fetch.bind(globalThis),i=KE()){if(i){const c=await Rd(i,a,r);if(c)return c}const o=await Rd(t,a,r);if(o)return o;if(OR(t)){const c=await Rd(CR,a,r);if(c)return c}return null}function OR(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 Ek(){const t=ne(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}),vw(window.location.origin).then(o=>{i||r(o?{status:"found",origin:o}:{status:"not-found",origin:null})}),()=>{i=!0}},[t]),a}function DR(t,a){const r=Mr(o=>t?o.byVault[t]:void 0),i=pt();b.useEffect(()=>{if(!t||!a||!r||r.state==="healthy"||r.nextProbeAt===null)return;const o=Date.now(),c=Math.max(0,r.nextProbeAt-o);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(()=>{})},c);return()=>{h=!0,clearTimeout(m)}},[t,a,r,i])}function tl(t){if(t.name)return t.name;try{return new URL(t.url).host}catch{return t.url}}function Nm(t){sa.getState().push(`Now in ${t}`,"success")}function kR(t,a={}){const r=ne.getState(),i=r.vaults[t];if(!i)return!1;const o=r.activeVaultId===t;return r.setActiveVault(t),(a.toast??!0)&&!o&&Nm(tl(i)),!0}const Cd=25,Rb=40;async function LR(t){for(let a=0;a<Rb;a++){const r=a*Cd,i=new URLSearchParams;i.set("exclude_tag",M0),i.set("sort","desc"),i.set("limit",String(Cd)),i.set("include_content","false"),r>0&&i.set("offset",String(r));const o=await t.queryNotes(i);if(O0(o))return!0;if(o.length<Cd)return!1}throw new Error(`first-note probe: ${Rb} full pages without ending the set — offset paging appears broken`)}function UR(){const t=ze(),a=ne(r=>r.activeVaultId);return ct({queryKey:["hasUserAuthoredNote",a],enabled:!!t,queryFn:()=>LR(t),staleTime:6e4})}const zR=["list","board","calendar","gallery","table"];function VR(t){return typeof t=="string"&&zR.includes(t)}const Md={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 BR(t){return t.path?$u(t.path):t.id}function Am(t){const a=t.metadata??{},r=VR(a.kind)?a.kind:"list",i=[];let o={};if(typeof a.query=="string"&&a.query.trim().length>0)try{const c=JSON.parse(a.query);c&&typeof c=="object"&&!Array.isArray(c)?o=c:(o=null,i.push(Md))}catch{o=null,i.push(Md)}else a.query!==void 0&&a.query!==null&&typeof a.query!="string"&&(o=null,i.push(Md));return{noteId:t.id,path:t.path,title:BR(t),kind:r,query:o,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:HR(a.fields),problems:i}}function HR(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 qR(t,a){return(t.tags??[]).includes(a)}function $R(t){const a=t.metadata;return(a==null?void 0:a.kind)==="saved-view"}const QR="Views/All notes",IR="Views/Recent",bw="Views/Pinned",xw="Views/Archive",ww=[QR,IR,bw,xw];function KR(t){const a=t==null?void 0:t.toLowerCase();return a!==void 0&&ww.some(r=>r.toLowerCase()===a)}const GR="Views/";function _m(t){const a=t.trim().replace(/[/\\]/g,"-");return`${GR}${a||"Untitled view"}`}function YR(t,a,r){const i=_m(t).toLowerCase(),o=r==null?void 0:r.toLowerCase();return[...ww,...a].some(c=>{const h=c.toLowerCase();return h===i&&h!==o})}const PR={pinned:bw,archived:xw},FR={pinned:"Pinned",archived:"Archive"};function XR(t){return PR[t]}function ZR(t,a){const r=t==="pinned"?a.pinned:a.archived;return{noteId:`builtin:${t}`,title:FR[t],kind:"list",query:{tag:r},problems:[]}}function JR(t,a,r){if(a&&qR(a,r.view)){const i=Am(a);if(i.query!==null)return{def:i,isPackNote:!0}}return{def:ZR(t,r),isPackNote:!1}}function WR(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,"/"),o=i+"=".repeat((4-i.length%4)%4),c=atob(o),h=JSON.parse(c),m=h==null?void 0:h.sub;return typeof m=="string"?m:null}catch{return null}}function Cb(t){if(typeof t=="string"||Array.isArray(t)&&t.every(a=>typeof a=="string"))return t}function eC(t){const a=[],r={};let i;for(const[c,h]of Object.entries(t))switch(c){case"tag":r.tag=Cb(h);break;case"exclude_tags":r.excludeTag=Cb(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 "${c}", which this app can't run yet; results may be broader than intended.`})}let o;try{o=Kd(r)}catch(c){const h=c instanceof Error?c.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;o=Kd(p)}return i&&o.set("search",i),{params:o,problems:a}}function Tk(t){return t.addTags.length>0||t.removeExcludes.length>0||!!t.search||!!t.sort}function jk(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 Nk(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 ol(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(a=>typeof a=="string"):[]}function tC(t,a){if(t===null)return null;const r={...t};if(a.addTags.length>0&&(r.tag=[...ol(t.tag),...a.addTags],r.tag_match="all"),a.removeExcludes.length>0){const i=ol(t.exclude_tags).filter(o=>!a.removeExcludes.includes(o));r.exclude_tags=i}return a.search&&(r.search=a.search),a.sort&&(r.sort=a.sort),r}function Sw(t){return t?ol(t.tag):[]}function nC(t){return Sw(t)[0]}function Ak(t){if(!t)return[];const a=[];for(const r of ol(t.tag))a.push({kind:"tag",value:r,label:`#${r}`});for(const r of ol(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 _k=dR;function Ew(t,a=!0){const r=ze(),i=ne(m=>m.activeVaultId),o=b.useMemo(()=>{const m=new URLSearchParams;return m.set("tag",t),m.set("sort","asc"),m},[t]),c=b.useMemo(()=>["viewList",i,t],[i,t]),{isLive:h}=bm({queryKey:c,params:o,client:r,enabled:a&&!!t});return ct({queryKey:c,enabled:a&&!!r&&!!t,queryFn:()=>r.queryNotes(o),staleTime:h?Number.POSITIVE_INFINITY:3e4,refetchInterval:h?!1:3e4,refetchOnWindowFocus:!h})}function aC(t,a){const r=ze(),i=ne(h=>h.activeVaultId),o=t?XR(t):null,c=ct({queryKey:["defaultViewNote",i,o],queryFn:async()=>(await r.queryNotes({path:o}))[0]??null,enabled:!!r&&!!o,staleTime:3e4,refetchOnWindowFocus:!1});return b.useMemo(()=>t?JR(t,c.data??null,a):{def:null,isPackNote:!1},[t,c.data,a])}function Rk(t,a,r){const i=ze(),o=ne(v=>v.activeVaultId),c=(r==null?void 0:r.live)??!0,h=b.useMemo(()=>t?tC(t.query,a):null,[t,a]),m=b.useMemo(()=>h?eC(h):null,[h]),p=b.useMemo(()=>["viewResults",o,t==null?void 0:t.noteId,(m==null?void 0:m.params.toString())??null],[o,t==null?void 0:t.noteId,m]),{isLive:y}=bm({queryKey:p,params:(m==null?void 0:m.params)??new URLSearchParams,client:m?i:null,enabled:!!m&&c}),x=ct({queryKey:p,enabled:!!i&&!!m,queryFn:()=>i.queryNotes(m.params),staleTime:y?Number.POSITIVE_INFINITY:1e4,refetchInterval:y?!1:3e4,refetchOnWindowFocus:!y,placeholderData:x0});return{data:x.data,isPending:x.isPending,isError:x.isError,error:x.error,refetch:()=>void x.refetch(),problems:(m==null?void 0:m.problems)??[],queryKey:p}}function Ck(){const t=ne(a=>a.activeVaultId);return b.useMemo(()=>{if(!t)return null;const a=Vs(t);return a!=null&&a.accessToken?WR(a.accessToken):null},[t])}function Mk(t,a){return a&&(t!=null&&t.createdBy)&&t.createdBy===a?"update":"fork"}function Tw(t){return t.pathname==="/"||t.pathname==="/today"||t.pathname.startsWith("/n/")}function Rm(t){return new URLSearchParams(t.search).get("view")}function rC(t){if(t.pathname!=="/notes")return!1;const a=Rm(t);return a!=="pinned"&&a!=="archived"}function sC(t){return t.pathname==="/notes"&&Rm(t)==="pinned"}function iC(t){return t.pathname==="/notes"&&Rm(t)==="archived"}function lC(t){return Tw(t)||t.pathname==="/notes"}const jw="/",oC="/notes",Tu="/map";function mn(t){return a=>a.pathname===t}const uC=["/welcome","/check-email","/add","/add-vault","/oauth/callback"];function Nw(t){return uC.some(a=>t===a||t.startsWith(`${a}/`))}const cC={id:"recent",label:"Recent",to:jw,icon:u.jsx(nN,{}),match:Tw},fC={id:"notes",label:"All notes",to:oC,icon:u.jsx(Ph,{}),match:rC},dC={id:"pinned",label:"Pinned",to:"/notes?view=pinned",icon:u.jsx(fN,{}),match:sC},hC={id:"archive",label:"Archive",to:"/notes?view=archived",icon:u.jsx(dN,{}),match:iC},Mb="/views/new",mC={id:"new-view",label:"New view",to:Mb,icon:u.jsx(Fh,{}),match:mn(Mb)},pC={id:"calendar",label:"Calendar",to:"/calendar",icon:u.jsx(e0,{}),match:mn("/calendar")},gC={id:"tags",label:"Tags",to:"/tags",icon:u.jsx(aN,{}),match:mn("/tags")},yC={id:"activity",label:"Activity",to:"/activity",icon:u.jsx(iN,{}),match:mn("/activity")},vC={id:"map",label:"Map",to:Tu,icon:u.jsx(r0,{}),match:mn(Tu)},bC={id:"vaults",label:"Vaults",to:"/vaults",icon:u.jsx(lN,{}),match:mn("/vaults")},xC={id:"connect",label:"Connect AI",to:"/connect",icon:u.jsx(t0,{}),match:mn("/connect")},wC={id:"import",label:"Import notes",to:"/import",icon:u.jsx(n0,{}),match:mn("/import")},SC={id:"export",label:"Export notes",to:"/export",icon:u.jsx(oN,{}),match:mn("/export")},EC={id:"settings",label:"Settings",to:"/settings",icon:u.jsx(sN,{}),match:mn("/settings")},TC={write:{label:"Write a note",to:"/new",icon:u.jsx(jC,{}),match:()=>!1}};function jC(){return u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 place-items-center rounded-full border border-border text-[10px]",children:"✦"})}function NC({daysLeft:t}){return u.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 AC(t){const a=[cC,fC,dC,hC],r=[pC,gC,yC];t.mapEarned&&r.push(vC);const i={id:"account",label:"Account & plan",to:"/account",icon:u.jsx(rN,{}),match:mn("/account"),badge:t.trialDaysLeft!==null?u.jsx(NC,{daysLeft:t.trialDaysLeft}):void 0},o=[{id:"notes",label:"Your notes",items:a},{id:"views",label:"Views",items:[...t.viewItems,mC]},{id:"explore",label:"Explore",items:r},{id:"parachute",label:"Your parachute",items:[i,bC,xC,wC,SC]}];return t.setup&&t.setup.steps.length>0&&o.push({id:"setup",label:"Set up",sublabel:`${t.setup.done} of ${t.setup.total}`,items:t.setup.steps.map(c=>({id:`setup-${c}`,...TC[c]}))}),o.push({id:"foot",items:[EC]}),o}function _C(){var T;const t=ne(E=>E.getActiveVault()),a=pw(),r=UR(),{roles:i}=Xs((t==null?void 0:t.id)??null),o=Ew(i.view),c=t!==null&&Gs(t.clientId),h=lm({enabled:c}),m=((T=c?im(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(o.data)?o.data.filter(E=>!KR(E.path)&&!$R(E)).map(E=>{const _=Am(E),R=`/views/${encodeURIComponent(E.id)}`;return{id:`view-${E.id}`,label:_.title,to:R,icon:u.jsx(EN,{kind:_.kind,hueTag:nC(_.query)}),match:mn(R)}}).sort((E,_)=>E.label.localeCompare(_.label)):[],[o.data]);if(!t)return[];const x=D0({hasUserNote:r.data===!0}),v=x.filter(E=>!E.done),w=r.data===void 0||v.length===0?null:{steps:v.map(E=>E.id),done:x.length-v.length,total:x.length};return AC({mapEarned:a,trialDaysLeft:p,setup:w,viewItems:y})}const Aw=b.createContext(null);function RC({children:t}){const a=_C();return u.jsx(Aw.Provider,{value:a,children:t})}function Ku(){const t=b.useContext(Aw);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 CC=Ka(t=>({shown:!1,setShown(a){t({shown:a})}}));function MC(){const t=ne(o=>o.activeVaultId!==null),a=pw(),r=CC(o=>o.shown),{pathname:i}=Ie();return!t||a||i===Tu||r?null:u.jsx(Ne,{to:Tu,"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 md:right-6 md:bottom-6",children:u.jsx(r0,{width:22,height:22})})}const Es=Ka(t=>({open:!1,setOpen(a){t({open:a})},toggle(){t(a=>({open:!a.open}))}}));function OC(){const t=ne(o=>o.activeVaultId!==null),a=Es(o=>o.setOpen),r=Ie();if(!t)return null;const i=lC(r);return u.jsx("nav",{"aria-label":"Primary",className:"fixed inset-x-0 bottom-0 z-20 border-t border-border bg-bg/95 backdrop-blur md:hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:u.jsxs("ul",{className:"mx-auto flex max-w-(--w-page) items-stretch justify-around px-2",children:[u.jsx(DC,{to:jw,label:"Notes",active:i,icon:u.jsx(Ph,{})}),u.jsx(LC,{}),u.jsx(kC,{label:"Search",icon:u.jsx(rl,{}),onClick:()=>a(!0)})]})})}function DC({to:t,label:a,icon:r,active:i}){return u.jsx("li",{className:"flex-1",children:u.jsxs(Ne,{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:[u.jsx("span",{"aria-hidden":"true",children:r}),u.jsx("span",{children:a})]})})}function kC({label:t,icon:a,onClick:r}){return u.jsx("li",{className:"flex-1",children:u.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:[u.jsx("span",{"aria-hidden":"true",children:a}),u.jsx("span",{children:t})]})})}function LC(){return u.jsx("li",{className:"flex flex-1 items-center justify-center",children:u.jsx(Ne,{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:u.jsx(Fh,{width:26,height:26,strokeWidth:2})})})}function _w({title:t,message:a,retry:r,retryLabel:i="Try again",action:o,className:c=""}){return u.jsxs("div",{className:`rounded-lg border border-(--color-danger-border) bg-(--color-danger-soft) p-6 ${c}`.trim(),children:[u.jsx("p",{className:"mb-2 font-medium text-(--color-danger)",children:t}),a?u.jsx("p",{className:"mb-4 text-sm text-fg-muted",children:a}):null,r||o?u.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r?u.jsx("button",{type:"button",onClick:r,className:"btn btn-secondary btn-touch",children:i}):null,o]}):null]})}class Rw 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 UC({error:t}){return u.jsx("div",{className:"page",children:u.jsx(_w,{title:"Something went wrong",message:u.jsxs(u.Fragment,{children:["This page hit an unexpected error. You can head back to your notes.",u.jsxs("details",{className:"mt-3",children:[u.jsx("summary",{className:"cursor-pointer text-xs text-fg-dim hover:text-fg-muted",children:"Technical detail"}),u.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-xs text-fg-dim",children:t.message})]})]}),action:u.jsx(Ne,{to:"/notes",className:"btn btn-secondary btn-touch",children:"Back to notes"})})})}function Le({children:t,resetKey:a}){const r=Ie();return u.jsx(Rw,{fallback:i=>u.jsx(UC,{error:i}),children:t},a??r.key)}function zC({error:t}){return u.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:[u.jsx("p",{className:"font-serif text-xl text-fg",children:"Something went wrong"}),u.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."}),u.jsxs("details",{className:"w-full text-left",children:[u.jsx("summary",{className:"cursor-pointer text-xs text-fg-dim hover:text-fg-muted",children:"Technical detail"}),u.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-xs text-fg-dim",children:t.message})]}),u.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"btn btn-primary btn-touch",children:"Reload"})]})}function VC({children:t}){return u.jsx(Rw,{fallback:a=>u.jsx(zC,{error:a}),children:t})}const ju=Ka(t=>({on:!1,setOn(a){t({on:a})},toggle(){t(a=>({on:!a.on}))}})),BC=/^\/n\/[^/]+(\/edit)?$/;function Cw(t){return BC.test(t)}function HC(){const t=Ie(),a=ju(i=>i.setOn),r=ju(i=>i.toggle);return b.useEffect(()=>{a(!1)},[t.pathname]),b.useEffect(()=>{const i=o=>{(o.metaKey||o.ctrlKey)&&(o.altKey||o.shiftKey||o.key==="."&&Cw(t.pathname)&&(o.preventDefault(),r()))};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[t.pathname,r]),null}function qC(){const t=ju(a=>a.setOn);return u.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:u.jsx(gN,{width:18,height:18})})}function $C(){const t=sa(o=>o.push),[a,r]=b.useState(!1);return{copied:a,copy:async o=>{try{await navigator.clipboard.writeText(o),r(!0),t("Copied to clipboard.","success"),window.setTimeout(()=>r(!1),2e3)}catch{t("Couldn't copy — select and copy manually.","error")}}}}function QC({value:t,label:a,className:r}){const{copied:i,copy:o}=$C();return u.jsxs("div",{className:`flex items-stretch gap-2 ${r??""}`,children:[u.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}),u.jsx("button",{type:"button",onClick:()=>o(t),className:"btn btn-secondary btn-touch shrink-0","aria-label":`Copy ${a}`,children:i?"Copied":"Copy"})]})}function IC(t=navigator,a=window){var r;return(r=a.matchMedia)!=null&&r.call(a,"(display-mode: standalone)").matches?!0:t.standalone===!0}function KC(t=navigator.userAgent,a=typeof document<"u"&&navigator.maxTouchPoints>1){return/iPad|iPhone|iPod/.test(t)?!0:/Macintosh/.test(t)&&a}let Ss=null,Mw=!1;const Sh=new Set;function Cm(){for(const t of Sh)t()}function GC(t){t.preventDefault(),Ss=t,Cm()}function YC(){Ss=null,Mw=!0,Cm()}let Ob=!1;function PC(){Ob||typeof window>"u"||(Ob=!0,window.addEventListener("beforeinstallprompt",GC),window.addEventListener("appinstalled",YC))}PC();function Db(t){return Sh.add(t),()=>{Sh.delete(t)}}function FC(){const t=b.useSyncExternalStore(Db,()=>Ss,()=>null),a=b.useSyncExternalStore(Db,()=>Mw,()=>!1),[r,i]=b.useState({standalone:!0,ios:!1});b.useEffect(()=>{i({standalone:IC(),ios:KC()})},[]);const c=r.standalone||a?"installed":t!==null||r.ios?"available":"unsupported",h=b.useCallback(async()=>{const m=Ss;if(!m)return"unavailable";try{return await m.prompt(),(await m.userChoice).outcome}catch{return"unavailable"}finally{Ss===m&&(Ss=null,Cm())}},[]);return{state:c,isIOSDevice:r.ios,promptInstall:h}}function Ow(){const{state:t,isIOSDevice:a,promptInstall:r}=FC(),i=ne(m=>{var p;return((p=m.getActiveVault())==null?void 0:p.url)??null}),[o,c]=b.useState(!1);if(t!=="available")return null;const h=async()=>{await r()==="unavailable"&&a&&c(!0)};return u.jsxs(u.Fragment,{children:[u.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"}),o?u.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:[u.jsx("h2",{id:"ios-install-title",className:"mb-3 font-serif text-xl",children:"Add Parachute to your home screen"}),u.jsxs("ol",{className:"mb-5 list-decimal space-y-2 pl-5 text-sm text-fg-muted",children:[u.jsx("li",{children:"Tap the Share icon in Safari's toolbar."}),u.jsxs("li",{children:["Choose ",u.jsx("strong",{className:"text-fg",children:"Add to Home Screen"}),"."]}),u.jsx("li",{children:"Tap Add. Parachute will open standalone from your home screen."})]}),i?u.jsxs("div",{className:"mb-5 rounded-md border border-border bg-bg-soft/60 p-3",children:[u.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:"}),u.jsx(QC,{value:i,label:"vault address"})]}):null,u.jsx("div",{className:"flex justify-end",children:u.jsx("button",{type:"button",onClick:()=>c(!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]})}function Mm(t,a){return t==="notes"&&a==="pinned"}function XC(){const t=ne(o=>o.getActiveVault()),{roles:a}=Xs((t==null?void 0:t.id)??null),r=b.useMemo(()=>({...ow,tags:[a.pinned],sort:"desc",limit:5}),[a.pinned]),i=hw(r,{live:!1});return{vault:t,notes:i.data}}function Om({variant:t,onNavigate:a}){const{vault:r,notes:i}=XC();if(!r||!i||i.length===0)return null;const o=t==="rail"?"focus-ring block min-w-0 truncate rounded-lg px-3 pl-11 py-1 font-round text-xs text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:bg-bg hover:text-fg-muted":"focus-ring flex min-h-11 min-w-0 items-center rounded-lg px-3 pl-11 py-1 font-round text-sm text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:bg-bg hover:text-fg-muted";return u.jsx("ul",{"aria-label":"Pinned notes",className:"min-w-0 space-y-0.5 pb-1",children:i.map(c=>{const h=wu(c);return u.jsx("li",{className:"min-w-0",children:u.jsx(Ne,{to:`/n/${encodeURIComponent(c.id)}`,"data-pinned-note":c.id,onClick:a,className:o,children:t==="rail"?h.text:u.jsx("span",{className:"min-w-0 truncate",children:h.text})})},c.id)})})}const Eh="notes:textSize",_r=["default","larger","largest"];function ZC(t){return t==="default"||t==="larger"||t==="largest"}function Ts(){try{const t=localStorage.getItem(Eh);return ZC(t)?t:"default"}catch{return"default"}}function JC(t){try{t==="default"?localStorage.removeItem(Eh):localStorage.setItem(Eh,t)}catch{}}function Dw(t,a=document.documentElement){t==="default"?a.removeAttribute("data-text-size"):a.setAttribute("data-text-size",t)}function Od(t){return t==="larger"?"Larger":t==="largest"?"Largest":"Default"}function WC(t){const a=_r.indexOf(t);return _r[(a+1)%_r.length]??"default"}function eM(t){const a=_r.indexOf(t),r=_r.length;return _r[(a-1+r)%r]??"default"}const Th="notes:text-size-change";function fu(t){JC(t),Dw(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Th,{detail:t}))}function tM(){return b.useEffect(()=>{const t=a=>{if((a.metaKey||a.ctrlKey)&&!(a.altKey||a.shiftKey)){if(a.key==="="||a.key==="+"){a.preventDefault(),fu(WC(Ts()));return}if(a.key==="-"||a.key==="_"){a.preventDefault(),fu(eM(Ts()));return}if(a.key==="0"){a.preventDefault(),fu("default");return}}};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[]),null}const Dd=8;function kw(){const[t,a]=b.useState(()=>Ts()),[r,i]=b.useState(!1),o=b.useRef(null),c=b.useRef(null),[h,m]=b.useState("down"),[p,y]=b.useState(null),x=b.useCallback(v=>{a(v),fu(v)},[]);return b.useEffect(()=>{const v=T=>{T.key==="notes:textSize"&&a(Ts())},w=T=>{const E=T.detail;a(E||Ts())};return window.addEventListener("storage",v),window.addEventListener(Th,w),()=>{window.removeEventListener("storage",v),window.removeEventListener(Th,w)}},[]),b.useEffect(()=>{if(!r)return;const v=w=>{o.current&&(o.current.contains(w.target)||i(!1))};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[r]),b.useLayoutEffect(()=>{if(!r)return;const v=()=>{const w=o.current,T=c.current;if(!w||!T)return;const E=w.getBoundingClientRect(),_=T.getBoundingClientRect(),R=_.height||T.offsetHeight,M=_.width||T.offsetWidth,V=window.innerHeight-E.bottom;m(V<R+Dd?"up":"down");const H=E.right-M,k=Dd,Y=Math.max(k,window.innerWidth-M-Dd),$=Math.min(Math.max(H,k),Y);y($-E.left)};return v(),window.addEventListener("resize",v),window.addEventListener("scroll",v,!0),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0)}},[r]),u.jsxs("div",{ref:o,className:"relative",children:[u.jsx("button",{type:"button","aria-label":`Text size: ${Od(t)}. Click to change.`,"aria-expanded":r,title:`Text size: ${Od(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:u.jsxs("span",{"aria-hidden":"true",className:"font-serif",children:["A",u.jsx("span",{className:"text-xs",children:"a"})]})}),r?u.jsx("div",{role:"dialog",ref:c,"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:u.jsx("ul",{className:"flex flex-col gap-0.5",children:_r.map(v=>{const w=v===t;return u.jsx("li",{children:u.jsxs("button",{type:"button",onClick:()=>{x(v),i(!1)},"aria-pressed":w,className:`flex w-full items-center justify-between rounded px-2 py-1.5 text-left hover:bg-bg/60 ${w?"text-accent":"text-fg-muted"}`,children:[u.jsx("span",{children:Od(v)}),w?u.jsx("span",{"aria-hidden":"true",className:"text-xs",children:"✓"}):null]})},v)})})}):null]})}const jh="lens:theme",kd=["system","light","dark"];function nM(t){return t==="system"||t==="light"||t==="dark"}function aM(){try{const t=localStorage.getItem(jh);return nM(t)?t:"system"}catch{return"system"}}function rM(t){try{t==="system"?localStorage.removeItem(jh):localStorage.setItem(jh,t)}catch{}}function kb(t,a=document.documentElement){t==="system"?a.removeAttribute("data-theme"):a.setAttribute("data-theme",t)}function sM(t){const a=kd.indexOf(t);return kd[(a+1)%kd.length]}function iM(t){return t==="light"?"Light":t==="dark"?"Dark":"System"}function Nu(){const[t,a]=b.useState("system");b.useEffect(()=>{const o=aM();a(o),kb(o)},[]);const r=()=>{const o=sM(t);a(o),rM(o),kb(o)},i=iM(t);return u.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:u.jsx(lM,{theme:t})})}function lM({theme:t}){return t==="light"?u.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:[u.jsx("circle",{cx:"10",cy:"10",r:"3.5"}),u.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"?u.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"currentColor",children:u.jsx("path",{d:"M15.5 11.8a6 6 0 0 1-7.3-7.3 6 6 0 1 0 7.3 7.3z"})}):u.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"none",stroke:"currentColor",strokeWidth:"1.6",children:[u.jsx("circle",{cx:"10",cy:"10",r:"6"}),u.jsx("path",{d:"M10 4v12",fill:"currentColor",stroke:"none"}),u.jsx("path",{d:"M10 4a6 6 0 0 1 0 12",fill:"currentColor",stroke:"none"})]})}function Lw(){const t=typeof window<"u"&&window.location?window.location.origin:"(unknown origin)";return u.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:[u.jsxs("p",{className:"mb-2 flex items-center gap-2 font-medium text-amber-100",children:[u.jsx("span",{"aria-hidden":!0,children:"⚠"}),"Insecure context — OAuth unavailable"]}),u.jsxs("p",{className:"mb-2 text-xs text-amber-100/90",children:["Your hub URL must be served over HTTPS or accessed at ",u.jsx("code",{children:"http://localhost"}),". This page is at ",u.jsx("code",{className:"font-mono",children:t}),", which the browser treats as insecure for Web Crypto. To connect:"]}),u.jsxs("ul",{className:"ml-4 list-disc space-y-1 text-xs text-amber-100/90",children:[u.jsxs("li",{children:["Use ",u.jsx("code",{children:"http://localhost"})," or ",u.jsx("code",{children:"http://127.0.0.1"})," directly (replace your hub URL with the localhost form), ",u.jsx("strong",{children:"or"})]}),u.jsx("li",{children:"Serve your hub over HTTPS via Tailscale Serve, Cloudflare Tunnel, or a reverse proxy."})]})]})}const oM={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."},uM="Something went wrong. Try again.";function cM(t){return/^[a-z][a-z0-9_]*$/.test(t)}function fM(t,a=uM){if(!(t instanceof Error))return a;const r=t.message.trim();return r?cM(r)?oM[r]??a:r:a}function dr(t){try{return Vh(t)}catch{return t.replace(/\/$/,"")}}function dM(t,a,r,i,o){const c=new Set(r.map(w=>dr(w.url))),h=new Set(t.map(w=>dr(w.url))),m=new Set(t.filter(w=>Gs(w.clientId)).map(w=>w.name)),p=[...t].sort((w,T)=>tl(w).localeCompare(tl(T))).map(w=>({kind:"device",id:w.id,label:tl(w),isActive:w.id===a,hubKnown:c.has(dr(w.url)),vault:w})),y=(o??[]).filter(w=>!(w.url!==void 0&&h.has(dr(w.url)))&&!m.has(w.name)).sort((w,T)=>w.name.localeCompare(T.name)).map(w=>({kind:"account",name:w.name,url:w.url})),x=new Set(y.filter(w=>w.url!==void 0).map(w=>dr(w.url))),v=i===null?[]:r.filter(w=>!h.has(dr(w.url))&&!x.has(dr(w.url))).sort((w,T)=>w.name.localeCompare(T.name)).map(w=>({kind:"hub",name:w.name,url:w.url,hubOrigin:i}));return[...p,...y,...v]}function Ld({label:t,here:a}){const r=(t.trim()[0]??"?").toUpperCase();return u.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 Ud({tone:t,children:a}){return u.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 Lb({layout:t,onAfterAction:a}){const r=ne(j=>j.vaults),i=ne(j=>j.activeVaultId),o=i?r[i]??null:null,[c,h]=b.useState(null),[m,p]=b.useState(!1),[y,x]=b.useState(null),[v,w]=b.useState(null),[T,E]=b.useState(null),[_,R]=b.useState(null),[M,V]=b.useState(!1),H=b.useMemo(()=>o?wR(o):null,[o]),k=lm(),Y=im(k.data),$=Zt(j=>j.identityEpoch),F=ct({queryKey:["account","vaults",$],queryFn:async()=>{try{return(await g0()).vaults}catch{return null}},staleTime:6e4}),G=F.data??null;b.useEffect(()=>{if(!H)return;const j=new AbortController;return p(!0),ER(H,fetch.bind(globalThis),j.signal).then(q=>{j.signal.aborted||(h(q),p(!1))}),()=>{j.abort(),p(!1)}},[H]);const Z=b.useMemo(()=>dM(Object.values(r),i,c??[],H,G),[r,i,c,H,G]),le=Z.filter(j=>j.kind==="device"),de=Z.filter(j=>j.kind==="account"),ge=Z.filter(j=>j.kind==="hub"),we=(Y==null?void 0:Y.plan)??null,se=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,O=b.useCallback(j=>{j.isActive||kR(j.id,{toast:!0}),a()},[a]),P=b.useCallback(async j=>{if(!T){E(j.name),R(null);try{await Vu(j.name),Nm(j.name),a()}catch(q){R(fM(q,"Couldn't open that vault."))}finally{E(null)}}},[T,a]),ae=b.useCallback(async j=>{x(j.name),w(null),V(!1);try{const{authorizeUrl:q}=await wm(j.hubOrigin,void 0,void 0,{params:{vault:j.name}});window.location.assign(q)}catch(q){x(null),q instanceof Mu?V(!0):w(q.message)}},[]),oe=m||F.isPending,ye=u.jsxs(u.Fragment,{children:[le.length>0?u.jsxs("div",{className:"border-b border-border-light",children:[u.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"On this device"}),u.jsx("ul",{className:"pb-2",children:le.map(j=>u.jsx("li",{children:u.jsxs("button",{type:"button",onClick:()=>O(j),className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 text-left hover:bg-bg-soft",children:[u.jsx(Ld,{label:j.label,here:!0}),u.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-fg",children:j.label}),j.isActive?u.jsx("span",{className:"shrink-0 text-2xs font-medium text-grass-ink",children:"✓ current"}):null]})},j.id))})]}):null,de.length>0?u.jsxs("div",{className:"border-b border-border-light",children:[u.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"In your account"}),u.jsx("ul",{className:"pb-2",children:de.map(j=>u.jsx("li",{children:u.jsxs("div",{className:"flex w-full items-center gap-2.5 px-3 py-1.5",children:[u.jsx(Ld,{label:j.name,here:!1}),u.jsx("span",{className:"min-w-0 flex-1 truncate text-fg-muted",children:j.name}),u.jsx("button",{type:"button",onClick:()=>P(j),disabled:T===j.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===j.name?"Opening…":"Open →"})]})},j.name))})]}):null,ge.length>0?u.jsxs("div",{className:"border-b border-border-light",children:[u.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"From your hub"}),u.jsx("ul",{className:"pb-2",children:ge.map(j=>u.jsx("li",{children:u.jsxs("div",{className:"flex w-full items-center gap-2.5 px-3 py-1.5",children:[u.jsx(Ld,{label:j.name,here:!1}),u.jsx("span",{className:"min-w-0 flex-1 truncate text-fg-muted",children:j.name}),u.jsx("button",{type:"button",onClick:()=>ae(j),disabled:y===j.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===j.name?"Connecting…":"Connect"})]})},j.url))})]}):null,M?u.jsx("div",{className:"border-b border-border-light px-3 py-2",children:u.jsx(Lw,{})}):null,v||_?u.jsx("div",{className:"border-b border-border-light px-3 py-2 text-xs text-(--color-danger)",children:v??_}):null,u.jsxs("div",{className:"border-b border-border-light py-2",children:[se&&we?u.jsxs(Ne,{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:[u.jsx(Ud,{tone:"sun",children:"↑"}),u.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"]}),u.jsx("span",{className:"shrink-0 text-sm font-semibold text-accent",children:"Upgrade →"})]}):u.jsxs(Ne,{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:[u.jsx(Ud,{tone:"accent",children:"+"}),u.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-accent",children:"Create a vault"})]}),u.jsxs(Ne,{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:[u.jsx(Ud,{tone:"sky",children:"⌂"}),u.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold",style:{color:"var(--color-sky)"},children:"Connect your own"})]})]}),u.jsxs("div",{className:"px-3 py-2",children:[ee!==null?u.jsxs(Ne,{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,u.jsxs("div",{className:"flex items-center justify-between gap-3",children:[u.jsx(Ne,{to:"/vaults",onClick:a,className:"focus-ring text-xs text-fg-muted hover:text-accent",children:"Manage vaults →"}),oe?u.jsx("span",{className:"text-[10px] text-fg-dim",children:"Looking for more vaults…"}):null]})]})]});return t==="inline"?u.jsx("section",{"aria-label":"Vaults",className:"text-sm",children:ye}):u.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:ye})}function Gu({variant:t="header",onOpenNavSheet:a,onAction:r,collapsed:i=!1}){const o=ne(w=>w.vaults),c=ne(w=>w.activeVaultId),h=c?o[c]??null:null,[m,p]=b.useState(!1),y=b.useRef(null);b.useEffect(()=>{if(!m)return;const w=E=>{y.current&&(y.current.contains(E.target)||p(!1))},T=E=>{E.key==="Escape"&&p(!1)};return document.addEventListener("mousedown",w),document.addEventListener("keydown",T),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",T)}},[m]);const x=b.useCallback(()=>p(!1),[]),v=h?tl(h):"Choose vault";if(t==="sheet")return u.jsx(Lb,{layout:"inline",onAfterAction:r??(()=>{})});if(t==="rail"){const w=(v.trim()[0]??"?").toUpperCase();return u.jsxs("div",{ref:y,className:"relative",children:[u.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:[u.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:w}),i?null:u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"min-w-0 flex-1 truncate font-round font-semibold text-fg",children:v}),u.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-xs text-fg-dim",children:"▾"})]})]}),m?u.jsx(Lb,{layout:"popover",onAfterAction:x}):null]})}return u.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:[u.jsx("span",{"aria-hidden":!0,className:"inline-block h-2 w-2 shrink-0 rounded-full bg-accent"}),u.jsx("span",{className:"min-w-0 truncate",children:v}),u.jsx("span",{"aria-hidden":!0,className:"ml-1 shrink-0 text-xs text-fg-dim",children:"▾"})]})}function hM({open:t,onClose:a,initialFocus:r}){return t?u.jsx(mM,{onClose:a,initialFocus:r}):null}function mM({onClose:t,initialFocus:a}){const r=ne(w=>Object.keys(w.vaults).length>0),i=Ku(),o=Ie(),c=b.useRef(null),h=b.useRef(null),m=b.useRef(null),p=i.filter(w=>w.id!=="foot"),y=i.find(w=>w.id==="foot");b.useEffect(()=>{var E;const w=document.activeElement,T=a==="switcher"?((E=h.current)==null?void 0:E.querySelector("button, a"))??c.current:c.current;return T==null||T.focus(),()=>{var _;return(_=w==null?void 0:w.focus)==null?void 0:_.call(w)}},[a]),b.useEffect(()=>{const w=T=>{if(T.key==="Escape"){t();return}if(T.key!=="Tab"||!c.current)return;const E=Array.from(c.current.querySelectorAll('a[href], button:not([disabled]), input, select, textarea, [tabindex]:not([tabindex="-1"])'));if(E.length===0)return;const _=E[0],R=E[E.length-1],M=document.activeElement;if(!(M instanceof HTMLElement)||!E.includes(M)){T.preventDefault(),(T.shiftKey?R:_).focus();return}T.shiftKey&&document.activeElement===_?(T.preventDefault(),R.focus()):!T.shiftKey&&document.activeElement===R&&(T.preventDefault(),_.focus())};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[t]),b.useEffect(()=>{const w=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=w}},[]);const x=w=>{m.current=c.current&&c.current.scrollTop<=0?w.touches[0].clientY:null},v=w=>{m.current!==null&&w.touches[0].clientY-m.current>64&&(m.current=null,t())};return u.jsxs("div",{className:"fixed inset-0 z-40 md:hidden",children:[u.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"}),u.jsxs("div",{role:"dialog",ref:c,"aria-modal":"true","aria-label":"Menu",tabIndex:-1,onTouchStart:x,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:[u.jsx("div",{"aria-hidden":!0,className:"sticky top-0 z-10 flex justify-center pt-2.5 pb-1.5",children:u.jsx("span",{className:"h-1 w-10 rounded-full bg-border"})}),r?u.jsx("div",{ref:h,"data-nav-band":"switcher",className:"border-b border-border-light",children:u.jsx(Gu,{variant:"sheet",onAction:t})}):null,p.length>0?u.jsx("nav",{"aria-label":"Primary",className:"px-3 pb-1",children:p.map(w=>u.jsx(pM,{band:w},w.id))}):null,u.jsxs("div",{"data-nav-band":"foot",className:"border-t border-border px-3 py-3",children:[y==null?void 0:y.items.map(w=>u.jsx(Uw,{item:w,loc:o},w.id)),u.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 px-3",children:[u.jsx(Ow,{}),u.jsx(kw,{}),u.jsx(Nu,{})]})]})]})]})}function pM({band:t}){const a=Ie();return u.jsxs("div",{"data-nav-band":t.id,children:[t.label?u.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[u.jsx("span",{children:t.label}),t.sublabel?u.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.items.map(r=>u.jsxs(b.Fragment,{children:[u.jsx(Uw,{item:r,loc:a}),Mm(t.id,r.id)?u.jsx(Om,{variant:"touch"}):null]},r.id))]})}function Uw({item:t,loc:a}){const r=t.match(a);return u.jsxs(Ne,{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:[u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),u.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})}const Ub={rows:[],byKind:{},total:0,pendingCount:0,needsHumanCount:0,authHalt:null};function zw(t,a,r=2e3){const[i,o]=b.useState(Ub),c=b.useRef(!1);return b.useEffect(()=>{if(c.current=!1,!t||!a){o(Ub);return}let h=null;const m=async()=>{try{const[p,y]=await Promise.all([lw(t,a),Ps(t,iw)]);if(c.current)return;const x={};let v=0,w=0;for(const E of p){const _=E.mutation.kind;x[_]=(x[_]??0)+1,E.status==="needs-human"?w+=1:v+=1}const T=y&&y.vaultId===a?y:null;o({rows:p,byKind:x,total:p.length,pendingCount:v,needsHumanCount:w,authHalt:T})}catch{}};return m(),h=setInterval(m,r),()=>{c.current=!0,h&&clearInterval(h)}},[t,a,r]),i}const gM=[["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 Dm(t,a=new Date){if(!t)return"";const i=new Date(t).getTime();if(Number.isNaN(i))return"";const o=a.getTime()-i,c=Math.abs(o);for(const[h,m]of gM)if(c>=m){const p=Math.floor(c/m);return o>=0?`${p}${h} ago`:`in ${p}${h}`}return"just now"}const yM={"create-note":"new notes","update-note":"note edits","delete-note":"deletions","upload-attachment":"uploads","link-attachment":"attachment links","delete-attachment":"attachment removals"},vM=.8;function bM({onDismiss:t}){const{db:a,isOnline:r,isDraining:i,lastSyncedAt:o}=Wt(),c=ne(M=>M.activeVaultId),h=sa(M=>M.push),m=zw(a,c),[p,y]=b.useState(null),x=Mr(M=>c?M.byVault[c]??null:null),[,v]=b.useState(0);b.useEffect(()=>{const M=setInterval(()=>v(V=>V+1),15e3);return()=>clearInterval(M)},[]),b.useEffect(()=>{let M=!1;return l2().then(V=>{M||V.supported&&typeof V.usage=="number"&&typeof V.quota=="number"&&y({usage:V.usage,quota:V.quota})}),()=>{M=!0}},[]);const w=(x==null?void 0:x.state)==="down",T=m.authHalt?"Reconnect needed":w?"Vault not reachable":r?i?"Syncing…":m.total>0?"Sync pending":"All caught up":"Offline — changes queued",E=async M=>{a&&(await A2(a,M),h("Retrying…","success"))},_=async(M,V)=>{a&&confirm(`Discard this ${zb(V.mutation)}? It cannot be recovered.`)&&(await _2(a,M),h("Row discarded.","success"))},R=async()=>{if(!a||!c||!confirm(`Clear every pending row for this vault (${m.total} total)? Destructive.`))return;const M=await M2(a,c);h(`Cleared ${M} pending row${M===1?"":"s"}.`,"success")};return u.jsxs("div",{className:"space-y-4",children:[u.jsxs("header",{className:"flex items-baseline justify-between",children:[u.jsx("h3",{className:"font-serif text-base text-fg",children:T}),t?u.jsx("button",{type:"button",onClick:t,"aria-label":"Close sync status",className:"text-xs text-fg-dim hover:text-accent",children:"×"}):null]}),m.authHalt?u.jsxs("div",{className:"rounded-md border border-red-500/30 bg-red-500/5 p-3 text-xs text-red-300",children:[u.jsx("p",{className:"mb-2",children:m.authHalt.message||"Vault rejected the current session."}),u.jsx(Ne,{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?u.jsx("p",{className:"text-xs text-fg-dim",children:"Nothing pending in this vault."}):u.jsxs("section",{children:[u.jsx("h4",{className:"mb-1 text-xs uppercase tracking-wider text-fg-dim",children:"Queue"}),u.jsx("ul",{className:"space-y-0.5 text-xs",children:Object.entries(m.byKind).map(([M,V])=>u.jsxs("li",{className:"flex justify-between",children:[u.jsx("span",{className:"text-fg-muted",children:yM[M]??M}),u.jsx("span",{className:"tabular-nums text-fg-dim",children:V})]},M))})]}),m.needsHumanCount>0?u.jsxs("section",{children:[u.jsx("h4",{className:"mb-1 text-xs uppercase tracking-wider text-fg-dim",children:"Needs your help"}),u.jsx("ul",{className:"space-y-1.5",children:m.rows.filter(M=>M.status==="needs-human").map(M=>u.jsxs("li",{className:"rounded border border-amber-500/30 bg-amber-500/5 p-2 text-xs",children:[u.jsx("p",{className:"font-medium text-amber-200",children:zb(M.mutation)}),M.lastError?u.jsx("p",{className:"mt-0.5 break-words text-amber-100/70",children:M.lastError}):null,u.jsxs("div",{className:"mt-1 flex gap-2",children:[u.jsx("button",{type:"button",onClick:()=>E(M.seq),className:"text-accent hover:underline",children:"Retry"}),u.jsx("button",{type:"button",onClick:()=>_(M.seq,M),className:"text-red-300 hover:underline",children:"Discard"})]})]},M.seq))})]}):null,u.jsx("section",{className:"text-xs text-fg-dim",children:u.jsxs("p",{children:["Last synced:"," ",u.jsx("span",{className:"text-fg-muted",children:o?Dm(new Date(o).toISOString()):"never"})]})}),p?u.jsx(xM,{usage:p.usage,quota:p.quota}):null,m.total>0?u.jsx("div",{className:"flex justify-end border-t border-border pt-3",children:u.jsx("button",{type:"button",onClick:R,className:"text-xs text-red-400 hover:underline",children:"Clear all pending"})}):null]})}function zb(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 xM({usage:t,quota:a}){const r=a>0?t/a:0,i=r>=vM;return u.jsxs("section",{className:"text-xs",children:[u.jsxs("div",{className:"flex justify-between text-fg-dim",children:[u.jsx("span",{children:"Offline cache"}),u.jsx("span",{className:i?"text-amber-300":"text-fg-muted",children:wM(t)})]}),i?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"mt-1 h-1.5 w-full overflow-hidden rounded-full bg-border/40",children:u.jsx("div",{className:"h-full bg-amber-400",style:{width:`${Math.min(100,Math.round(r*100))}%`}})}),u.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 wM(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 SM(t){return t.authHalt?"halted":t.unreachable?"unreachable":t.isOnline?t.isDraining?"syncing":"online":"offline"}function EM(){const{db:t,isOnline:a,isDraining:r}=Wt(),i=ne(w=>w.activeVaultId),o=zw(t,i),c=Mr(w=>i?w.byVault[i]??null:null),[h,m]=b.useState(!1),p=b.useRef(null);b.useEffect(()=>{if(!h)return;const w=T=>{p.current&&(p.current.contains(T.target)||m(!1))};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[h]);const y=SM({isOnline:a,isDraining:r,authHalt:o.authHalt!==null,unreachable:(c==null?void 0:c.state)==="down"}),x=TM(y),v=o.total>0?o.total:null;return u.jsxs("div",{ref:p,className:"relative",children:[u.jsxs("button",{type:"button","aria-label":`Sync status: ${x}${v?`, ${v} pending`:""}`,"aria-expanded":h,onClick:()=>m(w=>!w),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:[u.jsx(jM,{tone:y}),u.jsx("span",{className:"hidden text-xs sm:inline",children:x}),v!==null?u.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?u.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:u.jsx(bM,{onDismiss:()=>m(!1)})}):null]})}function TM(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 jM({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 u.jsx("span",{"aria-hidden":!0,className:`inline-block h-2 w-2 rounded-full ${t==="syncing"?"animate-pulse":""}`,style:{backgroundColor:a}})}const NM="(max-width: 767.98px)";function AM(){const t=Ie(),a=ne(o=>Object.keys(o.vaults).length>0),[r,i]=b.useState(null);return b.useEffect(()=>{i(null)},[t.pathname]),b.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const o=window.matchMedia(NM),c=h=>{h.matches||i(null)};return o.addEventListener("change",c),()=>o.removeEventListener("change",c)},[]),!a&&t.pathname==="/"?null:u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"sticky top-0 z-10 border-b border-border bg-bg/90 backdrop-blur md:hidden",style:{paddingTop:"env(safe-area-inset-top)"},children:u.jsxs("nav",{className:"flex items-center justify-between gap-3 px-4 py-3",children:[a?u.jsx("div",{className:"min-w-0 flex-1",children:u.jsx(Gu,{variant:"header",onOpenNavSheet:()=>i("switcher")})}):u.jsx(Ne,{to:"/",className:"focus-ring min-w-0 shrink truncate font-serif text-lg tracking-tight text-fg hover:text-accent",children:"Parachute"}),u.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a?u.jsx(EM,{}):null,u.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:u.jsx("span",{"aria-hidden":"true",className:"font-mono text-base leading-none",children:"☰"})})]})]})}),u.jsx(hM,{open:r!==null,onClose:()=>i(null),initialFocus:r==="switcher"?"switcher":void 0})]})}function _M(){const{mirror:t}=Wt();return t.state==="hydrating"&&t.progress?u.jsx(RM,{done:t.progress.done}):t.state==="offline"&&t.lastSyncedAt!==null?u.jsxs(Vw,{children:["Offline — showing your saved vault · updated ",CM(t.lastSyncedAt)]}):null}function RM({done:t}){var o;const a=(o=fw().data)==null?void 0:o.stats,r=a==null?void 0:a.totalNotes,i=typeof r=="number"&&r>0?`${t} of ~${r}`:`${t}`;return u.jsxs(Vw,{live:"off",children:["Saving your vault for offline · ",i]})}function Vw({children:t,live:a}){return u.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 CM(t){return Dm(new Date(t).toISOString())}const Vb="nav-drawer-panel",MM="(min-width: 768px) and (max-width: 1023.98px)";function OM(){const t=ne(x=>x.getActiveVault()),a=Ku(),r=Ie(),[i,o]=b.useState(!1),c=b.useCallback(()=>o(!1),[]),h=b.useRef(null),m=b.useRef(null);if(b.useEffect(()=>{if(!i)return;const x=v=>{var T,E;if(v.key!=="Escape"||v.defaultPrevented)return;const w=((T=h.current)==null?void 0:T.contains(document.activeElement))??!1;o(!1),w&&((E=m.current)==null||E.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[i]),b.useEffect(()=>{o(!1)},[r.pathname]),b.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const x=window.matchMedia(MM),v=w=>{w.matches||o(!1)};return x.addEventListener("change",v),()=>x.removeEventListener("change",v)},[]),!t)return null;const p=a.filter(x=>x.id!=="foot"),y=a.find(x=>x.id==="foot");return u.jsx("div",{ref:h,"data-nav-projection":"drawer","data-drawer-open":i?"true":"false",className:`glass-panel sticky top-0 hidden h-dvh shrink-0 flex-col border-r border-border transition-[width] duration-(--dur-move) ease-out md:flex lg:hidden ${i?"w-72":"w-14"}`,style:{paddingTop:"env(safe-area-inset-top)"},children:u.jsxs("nav",{"aria-label":"Vault navigation",id:i?Vb:void 0,className:"flex min-h-0 flex-1 flex-col",children:[u.jsxs("div",{className:`flex shrink-0 items-start justify-center gap-1.5 ${i?"p-1.5":"p-1"}`,children:[i?u.jsx("div",{className:"min-w-0 flex-1",children:u.jsx(Gu,{variant:"rail"})}):null,u.jsx("button",{ref:m,type:"button",onClick:()=>o(x=>!x),"aria-expanded":i,"aria-controls":i?Vb:void 0,"aria-label":i?"Close the navigation drawer":"Open the navigation drawer",title:i?"Close navigation":"Open navigation",className:"focus-ring grid h-11 w-11 shrink-0 place-items-center rounded-lg text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:bg-bg hover:text-fg-muted",children:u.jsx("span",{"aria-hidden":!0,className:`transition-transform duration-(--dur-move) ease-out ${i?"":"rotate-180"}`,children:u.jsx(a0,{width:20,height:20})})})]}),i?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"shrink-0 px-3 pb-3",children:u.jsx(kM,{onDone:c})}),u.jsx("div",{className:"enter-fade min-h-0 flex-1 overflow-y-auto px-3 pb-3",children:p.map(x=>u.jsx(DM,{band:x,onNavigate:c},x.id))}),u.jsxs("div",{"data-nav-band":"foot",className:"enter-fade shrink-0 border-t border-border px-3 pt-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))]",children:[y==null?void 0:y.items.map(x=>u.jsx(Bw,{item:x,loc:r,onNavigate:c},x.id)),u.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 px-3",children:[u.jsx(Ow,{}),u.jsx(kw,{}),u.jsx(Nu,{})]})]})]}):u.jsx("div",{"aria-hidden":!0,className:"mt-1 flex justify-center",children:u.jsx("span",{className:"h-10 w-1 rounded-full bg-border-light"})})]})})}function DM({band:t,onNavigate:a}){const r=Ie();return u.jsxs("div",{"data-nav-band":t.id,children:[t.label?u.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[u.jsx("span",{children:t.label}),t.sublabel?u.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.items.map(i=>u.jsxs(b.Fragment,{children:[u.jsx(Bw,{item:i,loc:r,onNavigate:a}),Mm(t.id,i.id)?u.jsx(Om,{variant:"touch",onNavigate:a}):null]},i.id))]})}function Bw({item:t,loc:a,onNavigate:r}){const i=t.match(a);return u.jsxs(Ne,{to:t.to,"data-nav-item":t.id,onClick:r,"aria-current":i?"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 ${i?"bg-grass-soft font-semibold text-grass-ink":"font-medium text-fg-muted hover:bg-bg hover:text-fg"}`,children:[u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),u.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})}function kM({onDone:t}){const a=Es(r=>r.setOpen);return u.jsxs("button",{type:"button",onClick:()=>{a(!0),t()},className:"focus-ring flex min-h-11 w-full items-center gap-2.5 rounded-lg border border-border bg-card px-3 py-2.5 text-left font-round text-base text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:border-accent/50 hover:text-fg-muted",children:[u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:u.jsx(rl,{width:18,height:18})}),u.jsx("span",{className:"flex-1",children:"Search…"})]})}const Hw=10,LM="lens:recents:";function qw(t){return LM+t}function $w(t){try{const a=localStorage.getItem(qw(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,Hw):[]}catch{return[]}}function Ok(t,a,r=Date.now()){try{const i=$w(t).filter(c=>c.id!==a),o=[{id:a,viewedAt:r},...i].slice(0,Hw);localStorage.setItem(qw(t),JSON.stringify(o))}catch{}}const UM=new Set([" ","/","-","_",".","\\"]);function nl(t,a){if(!t)return{score:0,indices:[]};if(!a)return null;const r=t.toLowerCase(),i=a.toLowerCase();let o=0,c=0,h=-2,m=!0;const p=[];for(let y=0;y<i.length&&o<r.length;y+=1){const x=i[y]??"";if(x===r[o]){p.push(y);let v=1;y===0?v+=4:m&&(v+=2),h===y-1&&(v+=3),c+=v,h=y,o+=1}m=UM.has(x)}return o<r.length?null:(c-=Math.floor(i.length/20),{score:c,indices:p})}const zd=20,Bb=[{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 zM(t,a){let r=null;for(const i of t){const o=nl(a,i);o&&(r===null||o.score>r)&&(r=o.score)}return r}function VM(t,a){const r=__(t),i=nl(a,r),o=t.path?nl(a,t.path):null;let c=null;i&&(c=i.score+2),o&&(c===null||o.score>c)&&(c=o.score);for(const h of t.tags??[]){const m=nl(a,h);m&&(c===null||m.score>c)&&(c=m.score)}return c}function BM(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(w=>[w.id,w])),x=[];for(const w of t.recents){const T=y.get(w.id);if(!T)continue;const E=wu(T);x.push({kind:"note",id:T.id,title:E.text,titleKind:E.kind,path:T.path,score:0})}const v=Bb.map(w=>({kind:"command",id:w.id,label:w.label,description:w.description,action:w.action,score:0}));return[...x,...v].slice(0,zd)}const o=Bb.flatMap(y=>{const x=zM([y.label,...y.keywords],i);return x===null?[]:[{kind:"command",id:y.id,label:y.label,description:y.description,action:y.action,score:x+(r?1e3:0)}]});if(r)return o.sort((y,x)=>x.score-y.score).slice(0,zd);const c=t.notes.flatMap(y=>{const x=VM(y,i);if(x===null)return[];const v=wu(y);return[{kind:"note",id:y.id,title:v.text,titleKind:v.kind,path:y.path,score:x}]}),m=[...t.tags.flatMap(y=>{const x=nl(i,y.name);return x?[{kind:"tag",name:y.name,count:y.count,score:x.score}]:[]})].sort((y,x)=>x.score-y.score),p=[...o,...c].sort((y,x)=>x.score-y.score);return[...m,...p].slice(0,zd)}const HM=150;function qM({onClose:t}){const a=ne(k=>k.activeVaultId),r=Cr(),i=b.useRef(null),o=b.useRef(null),c=b.useId(),h=b.useId(),[m,p]=b.useState(""),[y,x]=b.useState(""),[v,w]=b.useState(0),T=sR(!0),E=uR(),_=b.useMemo(()=>a?$w(a):[],[a]);b.useEffect(()=>{const k=setTimeout(()=>x(m),HM);return()=>clearTimeout(k)},[m]);const R=b.useMemo(()=>BM({query:y,notes:T.data??[],tags:E.data??[],recents:_}),[y,T.data,E.data,_]);b.useEffect(()=>{w(0)},[R.length]),b.useEffect(()=>{var k;(k=i.current)==null||k.focus()},[]);const M=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]),V=b.useCallback(k=>{if(k.key==="Escape"){k.preventDefault(),t();return}if(k.key==="ArrowDown"){k.preventDefault(),w(Y=>Math.min(R.length-1,Y+1));return}if(k.key==="ArrowUp"){k.preventDefault(),w(Y=>Math.max(0,Y-1));return}if(k.key==="Enter"){k.preventDefault();const Y=R[v];Y&&M(Y);return}},[R,v,M,t]);b.useEffect(()=>{var Y,$;const k=(Y=o.current)==null?void 0:Y.querySelector(`[data-qs-idx="${v}"]`);($=k==null?void 0:k.scrollIntoView)==null||$.call(k,{block:"nearest"})},[v]);const H=T.isPending;return u.jsx("dialog",{open:!0,"aria-labelledby":c,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:u.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:[u.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:[u.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:[u.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-fg-dim",children:u.jsx(rl,{width:18,height:18})}),u.jsx("input",{id:c,ref:i,type:"text",value:m,onChange:k=>p(k.target.value),onKeyDown:V,placeholder:"Search your vault…","aria-label":"Quick switch query","aria-controls":h,"aria-activedescendant":R[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"}),u.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:[u.jsx(t0,{width:13,height:13}),"Smart"]})]}),u.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"})]}),u.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:[u.jsx("div",{id:h,ref:o,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&&R.length===0?u.jsx("div",{className:"px-4 py-3 text-sm text-fg-dim",children:"Loading notes…"}):R.length===0?u.jsx("div",{className:"px-4 py-3 text-sm text-fg-dim",children:m.trim().length===0?"Start typing to search.":"No matches."}):R.map((k,Y)=>u.jsx(QM,{entry:k,index:Y,selected:Y===v,onPick:()=>M(k),onHover:()=>w(Y)},$M(k)))}),u.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:[u.jsxs("span",{children:[u.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"↑↓"})," navigate"," ",u.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"↵"})," open"," ",u.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"esc"})," close"," ",u.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:">"})," commands"]}),u.jsx("span",{className:"tabular-nums",children:R.length>0?`${R.length} result${R.length===1?"":"s"}`:""})]})]})]})})}function $M(t){return t.kind==="note"?`note:${t.id}`:t.kind==="tag"?`tag:${t.name}`:`cmd:${t.id}`}function QM({entry:t,index:a,selected:r,onPick:i,onHover:o}){const c=r?"bg-accent/10 text-fg":"text-fg-muted";return u.jsx("div",{id:`qs-opt-${a}`,role:"option",tabIndex:-1,"aria-selected":r,"data-qs-idx":a,onMouseEnter:o,onMouseDown:h=>{h.preventDefault(),i()},className:`mx-1.5 flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-sm ${c}`,children:t.kind==="note"?u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"note"}),u.jsx("span",{className:t.titleKind==="timestamp"?"truncate title-timestamp":"truncate font-medium",children:t.title}),t.path?u.jsx("span",{className:"ml-auto truncate font-mono text-xs text-fg-dim",children:t.path}):null]}):t.kind==="tag"?u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"tag"}),u.jsxs("span",{className:"font-mono",children:["#",t.name]}),u.jsx("span",{className:"ml-auto text-xs tabular-nums text-fg-dim",children:t.count})]}):u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"text-xs uppercase tracking-wider text-accent",children:"cmd"}),u.jsx("span",{className:"font-medium",children:t.label}),u.jsx("span",{className:"ml-auto text-xs text-fg-dim",children:t.description})]})})}function IM(){const t=Es(c=>c.open),a=Es(c=>c.setOpen),r=Es(c=>c.toggle),i=ne(c=>c.activeVaultId);b.useEffect(()=>{const c=h=>{h.key==="k"&&(h.metaKey||h.ctrlKey)&&!h.altKey&&!h.shiftKey&&(h.preventDefault(),r())};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[r]);const o=b.useRef(i);return b.useEffect(()=>{o.current!==i&&(o.current=i,a(!1))},[i,a]),!t||i===null?null:u.jsx(qM,{onClose:()=>a(!1)})}const Hb="parachute.rail-collapsed";function KM(){const[t,a]=b.useState(()=>{try{return localStorage.getItem(Hb)==="1"}catch{return!1}}),r=b.useCallback(()=>{a(i=>{const o=!i;try{localStorage.setItem(Hb,o?"1":"0")}catch{}return o})},[]);return[t,r]}function GM(){const t=ne(h=>h.getActiveVault()),a=Ku(),[r,i]=KM();if(!t)return null;const o=a.filter(h=>h.id!=="foot"),c=a.find(h=>h.id==="foot");return u.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:[u.jsxs("div",{className:r?"flex flex-col items-stretch gap-2 p-3":"p-3",children:[u.jsxs("div",{className:r?"":"flex items-start gap-1.5",children:[u.jsx("div",{className:"min-w-0 flex-1",children:u.jsx(Gu,{variant:"rail",collapsed:r})}),u.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:u.jsx("span",{"aria-hidden":!0,className:`transition-transform duration-(--dur-move) ease-out ${r?"rotate-180":""}`,children:u.jsx(a0,{width:16,height:16})})})]}),u.jsx(PM,{collapsed:r})]}),u.jsx("nav",{"aria-label":"Your vault",className:"flex-1 overflow-y-auto px-3 pb-3",children:o.map(h=>u.jsx(YM,{band:h,collapsed:r},h.id))}),u.jsxs("div",{"data-nav-band":"foot",className:"border-t border-border p-3",children:[c==null?void 0:c.items.map(h=>r?u.jsx(Nh,{item:h,collapsed:!0},h.id):u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("div",{className:"min-w-0 flex-1",children:u.jsx(Nh,{item:h,collapsed:!1})}),u.jsx(Nu,{})]},h.id)),r?u.jsx("div",{className:"mt-1 flex justify-center",children:u.jsx(Nu,{})}):null]})]})}function YM({band:t,collapsed:a}){return u.jsxs("div",{"data-nav-band":t.id,children:[t.label&&!a?u.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[u.jsx("span",{children:t.label}),t.sublabel?u.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.label&&a?u.jsx("div",{"aria-hidden":!0,className:"mx-2 mt-3 mb-2 border-t border-border-light"}):null,t.items.map(r=>u.jsxs(b.Fragment,{children:[u.jsx(Nh,{item:r,collapsed:a}),Mm(t.id,r.id)&&!a?u.jsx(Om,{variant:"rail"}):null]},r.id))]})}function Nh({item:t,collapsed:a}){const r=Ie(),i=t.match(r);return u.jsxs(Ne,{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:[u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),a?null:u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})]})}function PM({collapsed:t}){const a=Es(r=>r.setOpen);return t?u.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:u.jsx(rl,{width:16,height:16})}):u.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:[u.jsx("span",{"aria-hidden":!0,className:"grid h-4 w-4 shrink-0 place-items-center",children:u.jsx(rl,{width:16,height:16})}),u.jsx("span",{className:"flex-1",children:"Search…"}),u.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 FM(){const t=ne(m=>m.activeVaultId!==null),{pathname:a}=Ie(),[r,i]=b.useState(!1),o=b.useRef(null),c=b.useRef(null),h=b.useId();return b.useEffect(()=>{i(!1)},[a]),b.useEffect(()=>{if(!r)return;const m=y=>{var x;y.key==="Escape"&&(i(!1),(x=c.current)==null||x.focus())},p=y=>{o.current&&y.target instanceof Node&&!o.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||Nw(a)||a==="/new"?null:u.jsxs("div",{ref:o,className:"fixed top-6 right-6 z-30 hidden md:block",children:[u.jsx("button",{ref:c,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:u.jsx("span",{"aria-hidden":"true",className:`transition-transform duration-(--dur-move) ease-out ${r?"rotate-45":""}`,children:u.jsx(Fh,{width:24,height:24,strokeWidth:2})})}),r?u.jsxs("div",{id:h,"aria-label":"Create",className:"mt-3 flex flex-col items-end gap-3",children:[u.jsx(Vd,{to:"/new",label:"New note",icon:u.jsx(uN,{width:18,height:18})}),u.jsx(Vd,{to:"/new?voice=1",label:"Voice note",icon:u.jsx(cN,{width:18,height:18})}),u.jsx(Vd,{to:"/import",label:"Import notes",icon:u.jsx(n0,{width:18,height:18})})]}):null]})}function Vd({to:t,label:a,icon:r}){return u.jsxs(Ne,{to:t,"data-speed-dial-verb":a,className:"focus-ring group flex items-center gap-3 rounded-full",children:[u.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}),u.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 XM=4e3;function ZM(){const t=sa(r=>r.toasts),a=sa(r=>r.dismiss);return b.useEffect(()=>{if(t.length===0)return;const r=t.map(i=>window.setTimeout(()=>a(i.id),i.durationMs??XM));return()=>{for(const i of r)window.clearTimeout(i)}},[t,a]),t.length===0?null:u.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=>u.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:[u.jsx("span",{children:r.message}),u.jsx("button",{type:"button",onClick:()=>a(r.id),"aria-label":"Dismiss",className:"focus-ring text-fg-dim hover:text-fg",children:"×"})]},r.id))})}function JM(t={}){const{immediate:a=!1,onNeedReload:r,onNeedRefresh:i,onOfflineReady:o,onRegistered:c,onRegisteredSW:h,onRegisterError:m}=t;let p,y;const x=async(w=!0)=>{await y};async function v(){if("serviceWorker"in navigator){if(p=await Ke(async()=>{const{Workbox:w}=await import("./workbox-window.prod.es5-BBnX5xw4.js");return{Workbox:w}},[]).then(({Workbox:w})=>new w("/sw.js",{scope:"/",type:"classic"})).catch(w=>{m==null||m(w)}),!p)return;p.addEventListener("activated",w=>{(w.isUpdate||w.isExternal)&&(r?r():window.location.reload())}),p.addEventListener("installed",w=>{w.isUpdate||o==null||o()}),p.register({immediate:a}).then(w=>{h?h("/sw.js",w):c==null||c(w)}).catch(w=>{m==null||m(w)})}}return y=v(),x}function WM(t={}){const{immediate:a=!0,onNeedReload:r,onNeedRefresh:i,onOfflineReady:o,onRegistered:c,onRegisteredSW:h,onRegisterError:m}=t,[p,y]=b.useState(!1),[x,v]=b.useState(!1),[w]=b.useState(()=>JM({immediate:a,onNeedReload:r,onOfflineReady(){v(!0),o==null||o()},onNeedRefresh(){y(!0),i==null||i()},onRegistered:c,onRegisteredSW:h,onRegisterError:m}));return{needRefresh:[p,y],offlineReady:[x,v],updateServiceWorker:w}}const qb={BASE_URL:"/"};function eO(t,a){const r=t&&t.length>0?t:a;return!r||r===""||r==="/"?"":r.replace(/\/$/,"")}function tO(){const t=typeof import.meta<"u"&&qb?qb:void 0,a=t?t.VITE_BASE_PATH:void 0,r=t?t.BASE_URL:void 0;return eO(a,r)}const nO=tO();function aO(t){return yl()===nO}async function rO(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=yl(),o=await r.getRegistrations();let c=0;for(const h of o)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(),c+=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 c}function sO(){return WM({onRegisteredSW(t,a){if(!a)return;const r=3600*1e3;setInterval(()=>{a.update().catch(()=>{})},r)},onNeedReload(){yT()}}),null}function iO(){return aO()?u.jsx(sO,{}):null}function lO(){const t=ne(o=>o.activeVaultId),a=ne(o=>o.getActiveVault()),r=Ar(o=>t?o.byVault[t]??null:null),i=Mr(o=>t?o.byVault[t]??null:null);return!a||!t?null:r&&!Gs(a.clientId)?u.jsx(oO,{reason:r.reason,vaultIssuer:a.issuer??a.url,vaultScope:a.scope,vaultId:t}):i&&i.state==="down"?u.jsx(uO,{vaultUrl:a.url,vaultId:t}):null}function oO({reason:t,vaultIssuer:a,vaultScope:r,vaultId:i}){const[o,c]=b.useState(!1),[h,m]=b.useState(null),[p,y]=b.useState(!1);async function x(){m(null),y(!1),c(!0);try{const{authorizeUrl:v}=await wm(a,r,void 0,{priorHaltedVaultId:i});window.location.assign(v)}catch(v){v instanceof Mu?y(!0):m(v instanceof Error?v.message:String(v))}finally{c(!1)}}return u.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:[u.jsxs("div",{className:"mx-auto flex max-w-5xl flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[u.jsxs("div",{children:[u.jsx("p",{className:"font-medium text-red-100",children:"Vault session expired"}),u.jsx("p",{className:"text-xs text-red-200/80",children:t}),h?u.jsx("p",{className:"mt-1 text-xs text-red-300",children:h}):null]}),u.jsx("button",{type:"button",onClick:x,disabled:o,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:o?"Starting OAuth…":"Reconnect to vault"})]}),p?u.jsx("div",{className:"mx-auto mt-2 max-w-5xl",children:u.jsx(Lw,{})}):null]})}function uO({vaultUrl:t,vaultId:a}){const r=ze(),i=pt(),o=Mr(y=>y.resetToHealthy),[c,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=fO(t)?"Try `parachute start vault` in a terminal.":null;return u.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:u.jsxs("div",{className:"mx-auto flex max-w-5xl flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[u.jsxs("div",{children:[u.jsx("p",{className:"font-medium text-red-100",children:"Vault not reachable"}),u.jsxs("p",{className:"text-xs text-red-200/80",children:["Notes can't sync until it's back online.",p?` ${p}`:""]})]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("button",{type:"button",onClick:m,disabled:c||!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:c?"Retrying…":"Retry now"}),u.jsx("button",{type:"button",onClick:()=>o(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 cO=/^(10|192\.168|172\.(1[6-9]|2\d|3[0-1]))\./;function fO(t){try{const r=new URL(t).hostname.replace(/^\[/,"").replace(/\]$/,"");return!!(r==="localhost"||r==="127.0.0.1"||r==="::1"||r.endsWith(".local")||cO.test(r))}catch{return!1}}function Ah({icon:t,title:a,description:r,action:i,className:o=""}){return u.jsxs("div",{className:`card p-10 text-center ${o}`.trim(),children:[t?u.jsx("div",{className:"mb-3 flex justify-center text-fg-dim","aria-hidden":"true",children:t}):null,u.jsx("p",{className:"text-fg-muted",children:a}),r?u.jsx("p",{className:"mt-1 text-sm text-fg-dim",children:r}):null,i?u.jsx("div",{className:"mt-4 flex justify-center",children:i}):null]})}const dO="parachute:door-descriptor";function Qw(){const t=typeof window<"u"&&window.location?window.location.origin:"";return`${dO}:${t}`}let Xt,_h=null,Rh=!1,Au=!1;const du=new Set,hO=["monthly","quarterly","yearly"];function mO(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 pO(t){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return;const a=t,r={};let i=!1;for(const o of hO){if(!(o in a))continue;const c=mO(a[o]);c&&(r[o]=c,i=!0)}return i?r:void 0}function gO(t){const a=t,{intervals:r,...i}=a,o=pO(r);return o!==void 0?{...i,intervals:o}:i}function Iw(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(x=>typeof x=="string")&&typeof r.signin_path=="string"&&r.signin_path.startsWith("/"),o=a.plans===void 0||Array.isArray(a.plans)&&a.plans.every(x=>!!x&&typeof x=="object"),c=o&&Array.isArray(a.plans)?a.plans.map(x=>gO(x)):void 0;if(i&&o)return c?{...a,plans:c}:a;const{auth:h,plans:m,...p}=a,y={...p};return i&&(y.auth=a.auth),o&&c&&(y.plans=c),y}async function yO(t){try{const a=await t("/.well-known/parachute-account");return a.ok?Iw(await a.json()):null}catch{return null}}function Kw(){try{const t=localStorage.getItem(Qw());if(t==null)return;const a=Iw(JSON.parse(t));return a===null?void 0:a}catch{return}}function vO(t){try{localStorage.setItem(Qw(),JSON.stringify(t))}catch{}}function bO(t){Rh||(Rh=!0,_h=yO(t).then(a=>{if(a!==null){const r=JSON.stringify(Xt)!==JSON.stringify(a);if(Xt=a,vO(a),r)for(const i of du)i(a)}else if(Xt===void 0){Xt=null;for(const r of du)r(null)}return Au=!0,du.clear(),Xt??null}).finally(()=>{_h=null}))}async function Gw(t=fetch.bind(globalThis),a){if(Xt===void 0){const r=Kw();r!==void 0&&(Xt=r)}return a&&!Au&&du.add(a),bO(t),Xt!==void 0?Xt:_h??null}function xO(){if(Xt===void 0){const t=Kw();t!==void 0&&(Xt=t)}return Xt??null}function wO(){Xt===null&&Au&&(Rh=!1,Au=!1)}function Dk(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 SO({hasLocalActiveVault:t,fetchImpl:a=fetch.bind(globalThis)}){let r;try{r=await Sl(a)}catch{return{kind:"front-door"}}if(!r.signed_in)return{kind:"front-door"};r.email&&xx(r.email),r.password_change_required&&Zt.getState().markGate("force_change_password");try{const i=await m0(r.csrf,a);Sx(i.token,r.email??r.username??null)}catch(i){if(EO(i))return{kind:"signed-in",email:r.email,username:r.username,vaults:[]}}try{const{vaults:i}=await g0(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 EO(t){return t instanceof wl?t.status===403&&t.message==="force_change_password"?(Zt.getState().markGate("force_change_password"),!0):t.status===423?(Zt.getState().markGate("admin_locked"),!0):!1:!1}function TO(t,a){var r;if(!(a instanceof Error))return t<2;if(xm(a)||a instanceof Qa)return!1;if(a instanceof ea){const i=ne.getState().activeVaultId;return(i?(r=Mr.getState().byVault[i])==null?void 0:r.state:void 0)==="down"?!1:t<1}return t<2}function jO({children:t}){const[a]=b.useState(()=>new wA({defaultOptions:{queries:{retry:TO,refetchOnWindowFocus:!1,staleTime:1e4}}}));return u.jsx(SA,{client:a,children:t})}const NO=[/^\/api\//,/^\/oauth\/(?!callback)/,/^\/\.well-known\//,/^\/signup/,/^\/login/,/^\/logout/,/^\/auth\//,/^\/console/,/^\/admin/,/^\/account\//,/^\/billing/,/^\/unsubscribe/,/^\/health/,/^\/vault\//,/^\/u\//];function AO(t){return NO.some(a=>a.test(t))}function Js({size:t=24,className:a}){return u.jsxs("svg",{width:t,height:t,viewBox:"0 0 64 64","aria-hidden":"true",className:a,children:[u.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)"}),u.jsx("path",{d:"M8 30 Q32 2 56 30",fill:"none",stroke:"var(--color-accent)",strokeWidth:"1.4"}),u.jsx("line",{x1:"8",y1:"30",x2:"30",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),u.jsx("line",{x1:"22",y1:"30",x2:"30",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),u.jsx("line",{x1:"42",y1:"30",x2:"34",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),u.jsx("line",{x1:"56",y1:"30",x2:"34",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),u.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 _O({size:t=22}){return u.jsxs(Ne,{to:"/",className:"focus-ring inline-flex items-center gap-2 rounded-lg font-round font-bold text-fg hover:text-accent",children:[u.jsx(Js,{size:t}),u.jsx("span",{children:"Parachute"})]})}const Yw="/welcome";function Bd({signedIn:t,netError:a,onRetry:r}={}){return t?u.jsx(zO,{email:t.email,username:t.username,vaults:t.vaults}):a?u.jsx(VO,{message:a,onRetry:r}):u.jsx(DO,{})}function jl({children:t}){return u.jsxs("div",{className:"relative flex min-h-[calc(100dvh-4rem)] flex-col",children:[u.jsx("div",{className:"flex items-center px-6 pt-6 sm:px-10",children:u.jsx(_O,{})}),u.jsx("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-10 text-center",children:u.jsx("div",{className:"mx-auto w-full max-w-md",children:t})})]})}function Pw(){return u.jsx("div",{className:"mt-8 border-t border-border pt-6",children:u.jsxs("p",{className:"font-round text-sm text-fg-muted",children:["Self-hosting?"," ",u.jsx(Ne,{to:"/add",className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Connect your own vault →"})," ",u.jsx("span",{className:"text-fg-dim",children:"(your notes stay on your server)"})]})})}function RO(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 CO(t){var i;if(!t||t.length===0)return null;let a=null,r=null;for(const o of t){const c=(i=o.intervals)==null?void 0:i.yearly;c!=null&&c.available&&typeof c.price=="number"&&c.price>0&&(a=a===null?c.price:Math.min(a,c.price)),typeof o.price_month=="number"&&o.price_month>0&&(r=r===null?o.price_month:Math.min(r,o.price_month))}return a!==null?`Plans from $${a} a year.`:r!==null?`Plans from $${r} a month.`:null}const MO="Three months";function OO(t){const a=typeof t=="string"?t.trim():"";return`${a&&a.length<=40?a:MO} free, no card.`}function DO(){const[t,a]=b.useState(()=>xO());b.useEffect(()=>{let i=!0;return wO(),Gw(void 0,o=>{i&&a(o)}).then(o=>{i&&a(o)}),()=>{i=!1}},[]);const r=RO(t);return r==="hub"&&(t!=null&&t.auth)?u.jsx(UO,{auth:t.auth,signupPath:t.signup_path}):r==="cloud"?u.jsx(LO,{plans:t==null?void 0:t.plans,trialLengthLabel:t==null?void 0:t.trial_length_label}):u.jsx(kO,{})}function kO(){return u.jsxs(jl,{children:[u.jsx(Js,{size:60,className:"mx-auto mb-6 drop-in"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),u.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",u.jsx("span",{className:"accent-word",children:"land."})]}),u.jsx("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:"Sign in to your parachute."}),u.jsx(Ne,{to:"/add",className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Sign in →"})]})}function LO({plans:t,trialLengthLabel:a}){const r=Cr(),[i]=Yh(),o=i.get("link")==="expired",[c,h]=b.useState(VE()??""),[m,p]=b.useState(!1),[y,x]=b.useState(null),v=/.+@.+\..+/.test(c.trim()),w=CO(t),T=OO(a);async function E(_){if(_.preventDefault(),!(!v||m)){p(!0),x(null);try{const R=await Sl();await zN(c.trim(),R.csrf,Yw),xx(c.trim()),r("/check-email")}catch(R){p(!1),x(R instanceof Error?`Couldn't send the link: ${R.message}`:"Couldn't send the link. Please try again.")}}}return u.jsxs(jl,{children:[u.jsx(Js,{size:60,className:"mx-auto mb-6 drop-in"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),u.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",u.jsx("span",{className:"accent-word",children:"land."})]}),o?u.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 ",u.jsx("span",{className:"font-serif italic",children:"expired."})," No harm done — we'll send a fresh one."]}):null,u.jsx("form",{onSubmit:E,className:"mx-auto w-full max-w-sm",children:u.jsxs("div",{className:"composer flex flex-col gap-3 p-4 text-left",children:[u.jsx("label",{htmlFor:"email",className:"eyebrow",children:"Sign in or create your account"}),u.jsx("input",{id:"email",type:"email",inputMode:"email",autoComplete:"email",autoFocus:!0,value:c,onChange:_=>h(_.target.value),placeholder:"you@example.com","aria-label":"Email address",className:"input input-on-bg"}),u.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"})]})}),u.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."}),u.jsxs("p",{className:"mx-auto mt-3 max-w-sm font-round text-xs text-fg-dim",children:[T,w?` ${w}`:""]}),y?u.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,u.jsx(Pw,{})]})}function UO({auth:t,signupPath:a}){const r=Cr(),[i,o]=b.useState(!1),c=typeof window<"u"?window.location.host:"";async function h(){if(!i){o(!0);try{const p=await vw(window.location.origin)??window.location.origin,{authorizeUrl:y}=await wm(p);window.location.assign(y)}catch{o(!1),r("/add")}}}function m(){const p=encodeURIComponent(Dx(Yw));window.location.assign(`${t.signin_path}?next=${p}`)}return u.jsxs(jl,{children:[u.jsx(Js,{size:60,className:"mx-auto mb-6 drop-in"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),u.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",u.jsx("span",{className:"accent-word",children:"land."})]}),u.jsxs("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:["Sign in to ",u.jsx("span",{className:"font-semibold text-fg",children:c||"your parachute"}),"."]}),u.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 →"}),u.jsx("p",{className:"mx-auto mt-6 max-w-sm font-round text-sm text-fg-muted",children:u.jsx("button",{type:"button",onClick:m,className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Manage this parachute →"})}),a?u.jsxs("p",{className:"mx-auto mt-3 max-w-sm font-round text-sm text-fg-muted",children:["New here?"," ",u.jsx("a",{href:a,className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Create your account →"})]}):u.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."}),u.jsx(Pw,{})]})}function zO({email:t,username:a,vaults:r}){const i=Cr(),[o,c]=b.useState(!1),h=r.length===1?r[0]:null;async function m(){if(!(!h||o)){c(!0);try{await Vu(h.name),Nm(h.name),i("/")}catch{i("/welcome",{replace:!0})}}}async function p(){try{const y=await Sl();await $N(y.csrf)}finally{Lh(),i("/",{replace:!0}),window.location.assign("/")}}return u.jsxs(jl,{children:[u.jsx(Js,{size:56,className:"mx-auto mb-6"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Signed in"}),u.jsxs("h1",{className:"hero-title mb-6",style:{fontSize:"clamp(1.8rem, 4vw, 2.4rem)"},children:["You're already signed in as"," ",u.jsx("span",{className:"accent-word",children:t??a??"your account"}),"."]}),u.jsxs("div",{className:"flex flex-col items-center gap-4",children:[h?u.jsx("button",{type:"button",onClick:m,disabled:o,className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:o?`Opening ${h.name}…`:`Open ${h.name} →`}):u.jsx(Ne,{to:"/welcome",className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Choose a vault →"}),u.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 VO({message:t,onRetry:a}){return u.jsxs(jl,{children:[u.jsx(Js,{size:56,className:"mx-auto mb-6"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Almost there"}),u.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 ",u.jsx("span",{className:"accent-word",children:"vaults."})]}),u.jsx("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:t}),u.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 BO({tags:t,input:a,onInputChange:r,onAdd:i,onRemove:o}){return u.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-sm",children:[u.jsx("span",{className:"shrink-0 text-xs uppercase tracking-wider text-fg-dim",children:"Tags"}),t.map(c=>u.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:[u.jsx("span",{className:"min-w-0 break-all",children:c}),u.jsx("button",{type:"button",onClick:()=>o(c),"aria-label":`Remove tag ${c}`,className:"text-fg-dim hover:text-red-400",children:"×"})]},c)),u.jsx("input",{type:"text",value:a,onChange:c=>r(c.target.value),onKeyDown:c=>{c.key==="Enter"||c.key===","?(c.preventDefault(),i(a)):c.key==="Backspace"&&a===""&&t.length>0&&o(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 _u(t){return t.trim().replace(/^#/,"")}function HO({capability:t,className:a="mb-4 text-xs text-fg-dim"}){const r=typeof(t==null?void 0:t.minutes_remaining)=="number";return u.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 qO=["audio/webm;codecs=opus","audio/mp4","audio/ogg;codecs=opus"],$O=32e3;function kk(t=qO){if(typeof MediaRecorder>"u")return null;for(const a of t)if(MediaRecorder.isTypeSupported(a))return a;return null}function QO(t){return t.startsWith("audio/webm")?"webm":t.startsWith("audio/mp4")?"m4a":t.startsWith("audio/ogg")?"ogg":t.startsWith("audio/wav")?"wav":"bin"}function Lk(t){const a=t.now??(()=>Date.now()),r=t.releaseStreamOnStop??!0,i=t.MediaRecorderCtor??MediaRecorder,o=new i(t.stream,{mimeType:t.mimeType,audioBitsPerSecond:$O}),c=[];let h="idle",m=0,p=0;o.ondataavailable=x=>{x.data&&x.data.size>0&&c.push(x.data),t.onData&&t.onData(c.reduce((v,w)=>v+w.size,0))};const y=()=>{if(r)for(const x of t.stream.getTracks())x.stop()};return{get state(){return h},get mimeType(){return t.mimeType},start(){if(h!=="idle")throw new Error(`Cannot start from ${h}`);o.start(t.dataIntervalMs),m=a(),h="recording"},pause(){h==="recording"&&(o.pause(),p+=a()-m,h="paused")},resume(){h==="paused"&&(o.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 x=new Promise(v=>{o.onstop=async()=>{const w=await KO(c);v({data:w,mimeType:t.mimeType,durationMs:p})}});return o.stop(),h="stopped",y(),x},cancel(){if(h==="recording"||h==="paused")try{o.stop()}catch{}h="stopped",c.length=0,y()}}}async function IO(t){const a=t;return typeof a.arrayBuffer=="function"?a.arrayBuffer():new Promise((r,i)=>{const o=new FileReader;o.onload=()=>r(o.result),o.onerror=()=>i(o.error??new Error("FileReader error")),o.readAsArrayBuffer(t)})}async function KO(t){if(t.length===0)return new ArrayBuffer(0);const a=await Promise.all(t.map(c=>IO(c))),r=a.reduce((c,h)=>c+h.byteLength,0),i=new Uint8Array(r);let o=0;for(const c of a)i.set(new Uint8Array(c),o),o+=c.byteLength;return i.buffer}async function Uk(){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 zk(t,a=new Date,r){const i=a.toISOString().replace(/[:.]/g,"-").replace(/Z$/,""),o=r&&r>0?`-part${r}`:"";return`memo-${i}${o}.${QO(t)}`}function $b(t=new Date){const a=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),c=String(t.getMinutes()).padStart(2,"0"),h=String(t.getSeconds()).padStart(2,"0");return`Notes/${a}/${r}-${i}/${o}-${c}-${h}`}const GO=/(?:^|\s)#([a-zA-Z][\w-]*)/g;function YO(t){const a=new Set;for(const r of t.matchAll(GO)){const i=_u(r[1]??"");i&&a.add(i)}return[...a]}function PO(t){const a=Array.from(new Set([...t.tags,...YO(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 FO(t,a,r,i,o=600){const c=b.useRef(r);c.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){f0(t,a);return}const p=window.setTimeout(()=>Zd(t,a,c.current),o);return()=>window.clearTimeout(p)},[m,i,t,a,o]),b.useEffect(()=>{if(!t||!a)return;const p=()=>{h.current&&Zd(t,a,c.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 XO={tags:[{name:"capture",description:"Notes captured directly by the user (text or voice)."}]};function ZO(t,a){const r=t??[],i=a??[];if(r.length!==i.length)return!1;for(let o=0;o<r.length;o++)if(r[o]!==i[o])return!1;return!0}function JO(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 ZO(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 WO(t){const a=await t.listTagsWithSchema(),r=new Map(a.map(h=>[h.name,h])),i=XO.tags.map(h=>JO(h,r.get(h.name))),o=i.filter(h=>h.status==="missing"),c=i.filter(h=>h.status==="misaligned");return{ok:o.length===0&&c.length===0,missing:o,misaligned:c,rows:i}}const Hd=new Set;async function e3(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 t3(t,a){if(!Hd.has(t)){Hd.add(t);try{const i=(await WO(a)).missing.map(o=>o.expected);i.length>0&&await e3(a,i)}catch(r){Hd.delete(t),typeof console<"u"&&console.warn(`[schema-ensure] failed to ensure required schema for vault ${t}:`,r)}}}const Fw="home-composer-input";function Xw({vault:t,focused:a=!1}){var ee;const r=sa(O=>O.push),i=mw(),o=ze(),{roles:c}=Xs(t.id),h=dw(),m=((ee=h.capability)==null?void 0:ee.enabled)===!1,p=b.useRef($b()),[y]=b.useState(()=>DN(t.id,eu)),[x,v]=b.useState(()=>y?{...y.body,path:y.body.path||p.current}:{content:"",path:p.current,tags:[]}),[w,T]=b.useState(!1),[E,_]=b.useState(null),[R,M]=b.useState(""),V=b.useRef(y!==null),H=b.useRef(null);b.useEffect(()=>{V.current||(v(O=>{const P=H.current?O.tags.filter(oe=>oe!==H.current):O.tags,ae=P.includes(c.captureText)?P:[...P,c.captureText];return ae===O.tags?O:{...O,tags:ae}}),H.current=c.captureText)},[c.captureText]);const k=!V.current&&(x.tags.length===0||x.tags.length===1&&x.tags[0]===c.captureText),Y=x.content.trim().length>0||!k||x.path.trim().length>0&&x.path!==p.current;FO(t.id,eu,x,Y);const $=b.useRef(x);$.current=x;const F=b.useRef(Y);F.current=Y;const G=b.useCallback(()=>{F.current&&Zd(t.id,eu,$.current)},[t.id]);b.useEffect(()=>()=>G(),[G]);const Z=b.useRef(null);b.useEffect(()=>{const O=Z.current;O&&(O.style.height="",x.content&&(O.style.height=`${O.scrollHeight}px`))},[x.content]);const le=w||x.content.length>0,de=x.content.trim().length>0&&x.path.trim().length>0&&!i.isPending,ge=O=>{const P=_u(O);!P||x.tags.includes(P)||(V.current=!0,v(ae=>({...ae,tags:[...ae.tags,P]})),M(""))},we=O=>{V.current=!0,v(P=>({...P,tags:P.tags.filter(ae=>ae!==O)}))},se=()=>{de&&(o&&t3(t.id,o),_(null),i.mutate(PO({content:x.content,path:x.path,tags:x.tags}),{onSuccess:()=>{var O;f0(t.id,eu),p.current=$b(),V.current=!1,H.current=c.captureText,M(""),v({content:"",path:p.current,tags:[c.captureText]}),(O=Z.current)==null||O.blur(),T(!1),r(`Saved to ${t.name}`,"success")},onError:O=>{_(O instanceof qu?"Session expired. Reconnect to save.":O instanceof Error?O.message:"Couldn't save — try again.")}}))};return u.jsxs("form",{"aria-label":"Write a note",className:`composer mb-6 px-5 py-4 ${a?"composer-focus":""}`,onSubmit:O=>{O.preventDefault(),se()},onFocus:()=>T(!0),onBlur:O=>{G(),O.currentTarget.contains(O.relatedTarget)||T(!1)},children:[u.jsx("textarea",{id:Fw,ref:Z,rows:1,value:x.content,onChange:O=>v(P=>({...P,content:O.target.value})),onKeyDown:O=>{(O.metaKey||O.ctrlKey)&&O.key==="Enter"&&(O.preventDefault(),se())},"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?u.jsx("div",{className:"mt-2",children:u.jsx(BO,{tags:x.tags,input:R,onInputChange:M,onAdd:ge,onRemove:we})}):null,u.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[le?u.jsx(Ne,{to:"/new",onClick:G,className:"focus-ring rounded text-fg-dim text-xs hover:text-accent",children:"Open full editor →"}):u.jsxs("span",{className:"font-round text-fg-dim text-xs",children:["Autosaves to ",t.name]}),u.jsxs("div",{className:"flex items-center gap-2",children:[le?u.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:u.jsx(Ne,{to:"/new?voice=1",onClick:G,"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:u.jsx("span",{"aria-hidden":"true",children:"🎙"})})]})]}),m&&le?u.jsx(HO,{capability:h.capability,className:"mt-2 text-xs text-fg-dim"}):null,E?u.jsx("p",{role:"alert",className:"mt-2 text-danger text-xs",children:E}):null]})}function Zw(){const t=Ku(),a=Ie(),r=t.find(i=>i.id==="notes");return!r||r.items.length===0?null:u.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 o=i.match(a);return u.jsx(Ne,{to:i.to,"data-nav-item":i.id,"aria-current":o?"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 ${o?"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 n3={mcp:"MCP",api:"API",cli:"CLI",operator:"operator"};function Qb(t){const a=n3[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 a3(t){const a=t.createdVia?`via ${Qb(t.createdVia)}`:null,r=t.lastUpdatedVia?`via ${Qb(t.lastUpdatedVia)}`:null;if(!a&&!r)return null;const i=t.createdBy??t.createdVia??null,o=t.lastUpdatedBy??t.lastUpdatedVia??null,c=o!==null&&o!==i,h=c&&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:c,raw:m}}function r3({note:t,variant:a="compact",className:r}){const i=a3(t);return i?a==="detail"?u.jsxs("div",{className:`space-y-0.5 text-xs text-fg-dim${r?` ${r}`:""}`,title:i.raw,children:[i.created?u.jsxs("p",{children:["created ",i.created]}):null,i.updated&&i.differs?u.jsxs("p",{children:["updated ",i.updated]}):null]}):u.jsx("span",{className:`shrink-0 text-xs text-fg-dim${r?` ${r}`:""}`,title:i.raw,children:i.compact}):null}function Jw({note:t,pinnedTag:a,archivedTag:r,trailing:i,footer:o}){const c=wu(t),h=!!t.path&&t.path.replace(/\.md$/i,"")!==c.text,m=t.updatedAt??t.createdAt,p=(t.tags??[]).includes(a),y=(t.tags??[]).includes(r);return u.jsxs("li",{className:y?"opacity-60 italic":void 0,children:[u.jsxs("div",{className:"note-row items-stretch","data-note-id":t.id,children:[u.jsx("span",{"aria-hidden":"true",className:"note-dot"}),u.jsxs(Ne,{to:`/n/${encodeURIComponent(t.id)}`,className:"focus-ring block min-h-11 min-w-0 flex-1 md:min-h-0",children:[u.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[u.jsxs("span",{className:"flex min-w-0 items-baseline gap-1.5",children:[p?u.jsx("span",{className:"shrink-0 text-accent","aria-label":"pinned",title:"pinned",children:"★"}):null,u.jsx("span",{className:c.kind==="timestamp"?"min-w-0 truncate text-base title-timestamp":"min-w-0 truncate text-base font-medium text-fg",children:c.text})]}),u.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[u.jsx("span",{className:"text-xs tabular-nums text-fg-dim",children:Dm(m)}),u.jsx(r3,{note:t})]})]}),h?u.jsx("p",{className:"mt-0.5 min-w-0 truncate note-id",children:t.path}):null,t.preview?u.jsx("p",{className:"mt-1 truncate text-sm text-fg-muted",children:t.preview}):null,t.tags&&t.tags.length>0?u.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:t.tags.map(x=>u.jsxs("span",{className:"chip chip-tag max-w-full break-all",children:["#",x]},x))}):null]}),i?u.jsx("div",{className:"shrink-0 self-center",children:i}):null]}),o?u.jsx("div",{className:"pl-4",children:o}):null]})}function Ww({children:t,"aria-label":a}){return u.jsx("ol",{"aria-label":a,className:"flex flex-col gap-0.5",children:t})}const s3="lens:path-tree-expanded:";function eS(t){return s3+t}function Ib(t){try{const a=localStorage.getItem(eS(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 i3(t,a){try{localStorage.setItem(eS(t),JSON.stringify([...a].sort()))}catch{}}function l3(t){const[a,r]=b.useState(()=>t?Ib(t):new Set);b.useEffect(()=>{r(t?Ib(t):new Set)},[t]);const i=b.useCallback(o=>{t&&r(c=>{const h=new Set(c);return h.has(o)?h.delete(o):h.add(o),i3(t,h),h})},[t]);return{expanded:a,toggle:i}}function o3(t,a){return{name:t,fullPath:a,count:0,children:[],childMap:new Map}}function tS(t){const a=t.split("/").filter(r=>r.length>0);return a.length<=1?[]:a.slice(0,-1)}function u3(t){const a=new Map;for(const i of t){if(!i)continue;const o=tS(i);if(o.length===0)continue;let c=a,h="";for(const m of o){h=h?`${h}/${m}`:m;let p=c.get(m);p||(p=o3(m,h),c.set(m,p)),p.count+=1,c=p.childMap}}const r=i=>i.map(o=>({name:o.name,fullPath:o.fullPath,count:o.count,children:r([...o.childMap.values()])})).sort((o,c)=>o.name.localeCompare(c.name));return r([...a.values()])}const c3=5,f3=20;function d3(t){const a=new Set;let r=0;for(const i of t){if(!i)continue;const o=tS(i);if(o.length!==0&&(r+=1,a.add(o[0]),a.size>=c3||r>=f3))return!0}return!1}function h3({paths:t,vaultId:a,currentPrefix:r,onSelect:i}){const o=b.useMemo(()=>u3(t),[t]),{expanded:c,toggle:h}=l3(a),m=b.useMemo(()=>m3(r),[r]);return o.length===0?u.jsxs("aside",{"aria-label":"Path tree",children:[u.jsx("h2",{className:"mb-2 text-xs uppercase tracking-wider text-fg-dim",children:"Folders"}),u.jsx("p",{className:"text-xs text-fg-dim",children:"No folders yet."})]}):u.jsxs("aside",{"aria-label":"Path tree",className:"md:sticky md:top-6 md:self-start",children:[u.jsxs("div",{className:"mb-2 flex items-baseline justify-between",children:[u.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"Folders"}),r?u.jsx("button",{type:"button",onClick:()=>i(""),className:"text-xs text-fg-dim hover:text-accent",children:"Clear"}):null]}),u.jsx("ul",{className:"space-y-0.5",children:o.map(p=>u.jsx(nS,{node:p,depth:0,expanded:c,forcedOpen:m,currentPrefix:r,onToggle:h,onSelect:i},p.fullPath))})]})}function nS({node:t,depth:a,expanded:r,forcedOpen:i,currentPrefix:o,onToggle:c,onSelect:h}){const m=t.children.length>0,p=r.has(t.fullPath)||i.has(t.fullPath),y=o===t.fullPath;return u.jsxs("li",{children:[u.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?u.jsx("button",{type:"button",onClick:()=>c(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:u.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:p?"▾":"▸"})}):u.jsx("span",{"aria-hidden":"true",className:"inline-block h-4 w-4"}),u.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:[u.jsx("span",{className:"truncate",children:t.name}),u.jsx("span",{className:"text-xs text-fg-dim",children:t.count})]})]}),m&&p?u.jsx("ul",{className:"space-y-0.5",children:t.children.map(x=>u.jsx(nS,{node:x,depth:a+1,expanded:r,forcedOpen:i,currentPrefix:o,onToggle:c,onSelect:h},x.fullPath))}):null]})}function m3(t){const a=new Set;if(!t)return a;const r=t.split("/").filter(o=>o.length>0);let i="";for(const o of r)i=i?`${i}/${o}`:o,a.add(i);return a}function ul(t){return t<10?`0${t}`:String(t)}function Yu(t=new Date){return`${t.getFullYear()}-${ul(t.getMonth()+1)}-${ul(t.getDate())}`}function aS(t){if(!t)return null;const a=new Date(t);return Number.isNaN(a.getTime())?null:Yu(a)}function cl(t){if(!t||!/^\d{4}-\d{2}-\d{2}$/.test(t))return null;const[a,r,i]=t.split("-").map(Number),o=new Date(a,r-1,i);return Number.isNaN(o.getTime())?null:o}function rS(t,a){const r=cl(t);return r?(r.setDate(r.getDate()+a),`${r.getFullYear()}-${ul(r.getMonth()+1)}-${ul(r.getDate())}`):t}function p3(t){var a;return((a=cl(t))==null?void 0:a.toISOString())??null}function Vk(t=new Date){return`${t.getFullYear()}-${ul(t.getMonth()+1)}`}function Bk(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 Hk(t,a,r){const i=t*12+(a-1)+r;return{year:Math.floor(i/12),month:i%12+1}}function qk(t,a){const i=new Date(t,a-1,1).getDay(),o=new Date(t,a-1,1-i),c=[];for(let h=0;h<42;h++)c.push(new Date(o.getFullYear(),o.getMonth(),o.getDate()+h));return c}function $k(t,a=new Date){var h;const r=((h=t.match(/^\d{4}-\d{2}-\d{2}/))==null?void 0:h[0])??null,i=cl(r);if(!i)return t;const o=cl(Yu(a));if(!o)return t;const c=Math.round((i.getTime()-o.getTime())/864e5);return c===0?"Today":c===-1?"Yesterday":c===1?"Tomorrow":i.toLocaleDateString(void 0,i.getFullYear()===a.getFullYear()?{month:"short",day:"numeric"}:{month:"short",day:"numeric",year:"numeric"})}function g3(t){const a=cl(t);return a?a.toLocaleDateString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"}):t}function Qk(t,a){return new Date(t,a-1,1).toLocaleDateString(void 0,{year:"numeric",month:"long"})}function y3(t){const a=new Map;for(const i of t){const o=aS(i.updatedAt??i.createdAt);if(!o)continue;const c=a.get(o);c?c.push(i):a.set(o,[i])}const r=i=>i.updatedAt??i.createdAt;return Array.from(a.entries()).sort(([i],[o])=>i<o?1:i>o?-1:0).map(([i,o])=>({key:i,notes:o.sort((c,h)=>r(c)<r(h)?1:r(c)>r(h)?-1:0)}))}function v3(t){const a=Yu();return t===a?"Today":t===rS(a,-1)?"Yesterday":g3(t)}function km({children:t}){return u.jsxs("h2",{className:"eyebrow mb-2 flex items-center gap-3",children:[u.jsx("span",{className:"shrink-0",children:t}),u.jsx("span",{"aria-hidden":"true",className:"h-px flex-1 bg-border"})]})}function b3({notes:t}){const a=ne(o=>o.getActiveVault()),{roles:r}=Xs((a==null?void 0:a.id)??null),i=b.useMemo(()=>y3(t),[t]);return u.jsx("div",{className:"space-y-8",children:i.map(o=>u.jsxs("section",{children:[u.jsx(km,{children:u.jsx(Ne,{to:`/today?date=${o.key}`,className:"hover:text-accent",children:v3(o.key)})}),u.jsx(Ww,{children:o.notes.map(c=>u.jsx(Jw,{note:c,pinnedTag:r.pinned,archivedTag:r.archived},c.id))})]},o.key))})}const Lm="application/x-parachute-note";function sS(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(pointer: fine)").matches}function x3(t,a){t.setData(Lm,a),t.effectAllowed="move"}function ru(t){return t?Array.from(t.types??[]).includes(Lm):!1}function w3(t){if(!t)return null;const a=t.getData(Lm);return a===""?null:a}function Ik(t){const[a]=b.useState(sS),r=b.useRef(!1),i=b.useCallback(h=>{h.dataTransfer&&(x3(h.dataTransfer,t),r.current=!0)},[t]),o=b.useCallback(()=>{window.setTimeout(()=>{r.current=!1},0)},[]),c=b.useCallback(h=>{r.current&&(h.preventDefault(),h.stopPropagation(),r.current=!1)},[]);return a?{canDrag:!0,sourceProps:{draggable:!0,onDragStart:i,onDragEnd:o,onClickCapture:c}}:{canDrag:!1,sourceProps:{}}}function Kk(t){const[a,r]=b.useState(!1),i=b.useRef(0),o=b.useCallback(p=>{ru(p.dataTransfer)&&(p.preventDefault(),i.current+=1,r(!0))},[]),c=b.useCallback(p=>{ru(p.dataTransfer)&&(p.preventDefault(),p.dataTransfer&&(p.dataTransfer.dropEffect="move"))},[]),h=b.useCallback(p=>{ru(p.dataTransfer)&&(i.current=Math.max(0,i.current-1),i.current===0&&r(!1))},[]),m=b.useCallback(p=>{if(!ru(p.dataTransfer))return;p.preventDefault(),i.current=0,r(!1);const y=w3(p.dataTransfer);y&&t(y)},[t]);return{isOver:a,targetProps:{onDragEnter:o,onDragOver:c,onDragLeave:h,onDrop:m}}}function Gk(){const t=b.useRef(new Map),a=b.useCallback((i,o)=>(t.current.set(i,o),()=>{t.current.get(i)===o&&t.current.delete(i)}),[]),r=b.useCallback((i,o)=>{var c;(c=t.current.get(i))==null||c(o)},[]);return{register:a,dispatch:r}}const S3=10;function Ru(t){return Object.keys(t.fields??{}).length}function E3(t,a){const r=new Map;for(const p of t){const y=p.name.indexOf("/");if(y>0){const x=p.name.slice(0,y),v=r.get(x)??[];v.push(p),r.set(x,v)}}const i=new Set;for(const[p,y]of r)y.length>=2&&i.add(p);const o=new Map,c=[];for(const p of t){const y=p.name.indexOf("/"),x=y>0?p.name.slice(0,y):p.name;if(y>0&&i.has(x)){let w=o.get(x);w||(w={kind:"group",prefix:x,totalCount:0,children:[]},o.set(x,w)),w.children.push({...p,pinned:a.has(p.name)}),w.totalCount+=p.count??0}else if(i.has(p.name)){let w=o.get(p.name);w||(w={kind:"group",prefix:p.name,totalCount:0,children:[]},o.set(p.name,w)),w.selfTag={...p,pinned:a.has(p.name)},w.totalCount+=p.count??0}else c.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 o.values())p.children.sort((y,x)=>y.pinned!==x.pinned?y.pinned?-1:1:(x.count??0)-(y.count??0)||y.name.localeCompare(x.name));const h=[...c,...Array.from(o.values())],m=p=>{var v,w;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),x=Math.max(((w=p.selfTag)==null?void 0:w.count)??0,...p.children.map(T=>T.count??0))||0;return{pinned:y,count:x,label:p.prefix}};return h.sort((p,y)=>{const x=m(p),v=m(y);return x.pinned!==v.pinned?x.pinned?-1:1:v.count-x.count||x.label.localeCompare(v.label)}),h}function Kb(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 Gb(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 T3(t,a,r){const i=t.filter(p=>Gb(p,a)),o=t.filter(p=>!Gb(p,a)),c=o.filter(Kb),h=o.filter(p=>!Kb(p)),m=Math.max(0,r-i.length);return[...i,...[...c,...h].slice(0,m)]}function j3({tags:t,pinnedTags:a,selected:r,onToggle:i,onClear:o,isLoading:c}){const[h,m]=b.useState(""),[p,y]=b.useState(!1),x=b.useRef(null);b.useEffect(()=>{var $;sS()&&(($=x.current)==null||$.focus())},[]);const v=b.useMemo(()=>new Set(a.map($=>$.toLowerCase())),[a]),w=b.useMemo(()=>new Set(r.map($=>$.toLowerCase())),[r]),T=b.useMemo(()=>E3(t,v),[t,v]),E=b.useMemo(()=>T3(T,w,S3),[T,w]),[_,R]=b.useState(new Set),M=$=>{R(F=>{const G=new Set(F);return G.has($)?G.delete($):G.add($),G})},V=h.trim().toLowerCase(),H=b.useMemo(()=>V?t.filter($=>$.name.toLowerCase().includes(V)).sort(($,F)=>(F.count??0)-($.count??0)||$.name.localeCompare(F.name)):[],[t,V]),k=$=>{if($.key!=="Enter")return;const F=H[0];F&&($.preventDefault(),i(F.name))},Y=$=>$.kind==="leaf"?u.jsx("li",{children:u.jsx(Cu,{name:$.name,label:$.label,count:$.count,pinned:$.pinned,active:w.has($.name.toLowerCase()),fieldCount:Ru($),onToggle:()=>i($.name)})},$.name):u.jsx("li",{children:u.jsx(N3,{group:$,isOpen:_.has($.prefix),onToggleOpen:()=>M($.prefix),selectedSet:w,onToggleTag:i})},$.prefix);return u.jsxs("nav",{"aria-label":"Browse by tag",children:[u.jsxs("div",{className:"mb-2 flex items-baseline justify-between",children:[u.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"Tags"}),r.length>0?u.jsx("button",{type:"button",onClick:o,className:"text-xs text-fg-dim hover:text-accent",children:"Clear"}):null]}),u.jsx("input",{ref:x,type:"search",value:h,onChange:$=>m($.target.value),onKeyDown:k,placeholder:"Filter tags…","aria-label":"Filter tags",className:"input mb-2 w-full text-sm"}),c?u.jsx("p",{className:"text-xs text-fg-dim",children:"Loading…"}):t.length===0?u.jsx("p",{className:"text-xs text-fg-dim",children:"No tags in this vault."}):V?H.length===0?u.jsxs("p",{className:"text-xs text-fg-dim",children:['No tags match "',h,'".']}):u.jsx("ul",{className:"max-h-[60vh] space-y-0.5 overflow-y-auto pr-1","aria-label":"Matching tags",children:H.map($=>u.jsx("li",{children:u.jsx(Cu,{name:$.name,label:$.name,count:$.count??0,pinned:v.has($.name.toLowerCase()),active:w.has($.name.toLowerCase()),fieldCount:Ru($),onToggle:()=>i($.name)})},$.name))}):u.jsxs(u.Fragment,{children:[u.jsx("ul",{className:"space-y-0.5","aria-label":"Shortlist",children:E.map(Y)}),T.length>E.length?u.jsxs("button",{type:"button",onClick:()=>y($=>!$),"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:[u.jsx("span",{"aria-hidden":"true",className:"font-mono",children:p?"▾":"▸"}),"All ",t.length," tags"]}):null,p?u.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 Cu({name:t,label:a,count:r,pinned:i,active:o,fieldCount:c,onToggle:h}){return u.jsxs("button",{type:"button",onClick:h,"aria-pressed":o,title:`#${t}`,className:`flex w-full items-center gap-1.5 rounded-lg px-2 py-1 text-left text-sm ${o?"bg-accent/15 text-accent":"text-fg-muted hover:bg-bg/60 hover:text-accent"}`,children:[i?u.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-accent",children:"★"}):null,u.jsxs("span",{className:"flex-1 truncate",children:["#",a]}),c?u.jsxs("span",{className:"shrink-0 text-xs text-fg-dim",title:`${c} schema field${c===1?"":"s"}`,children:["⊞ ",c]}):null,u.jsx("span",{className:"shrink-0 text-xs text-fg-dim",children:r})]})}function N3({group:t,isOpen:a,onToggleOpen:r,selectedSet:i,onToggleTag:o}){var y;const c=t.children.some(x=>i.has(x.name.toLowerCase())),h=t.selfTag?i.has(t.selfTag.name.toLowerCase()):!1,m=a||c||h,p=(((y=t.selfTag)==null?void 0:y.pinned)??!1)||t.children.some(x=>x.pinned);return u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center gap-1 rounded-lg px-1 py-0.5",children:[u.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:u.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:m?"▾":"▸"})}),t.selfTag?u.jsx(Cu,{name:t.selfTag.name,label:t.prefix,count:t.totalCount,pinned:t.selfTag.pinned,active:h,fieldCount:Ru(t.selfTag),onToggle:()=>o(t.selfTag.name)}):u.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?u.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-accent",children:"★"}):null,u.jsxs("span",{className:"flex-1 truncate",children:["#",t.prefix,"/"]}),u.jsx("span",{className:"shrink-0 text-xs text-fg-dim",children:t.totalCount})]})]}),m?u.jsx("ul",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:t.children.map(x=>{const v=x.name.slice(t.prefix.length+1)||x.name;return u.jsx("li",{children:u.jsx(Cu,{name:x.name,label:v,count:x.count??0,pinned:x.pinned,active:i.has(x.name.toLowerCase()),fieldCount:Ru(x),onToggle:()=>o(x.name)})},x.name)})}):null]})}function iS({className:t=""}){return u.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 su({label:t,onRemove:a}){return u.jsxs("span",{className:"chip chip-tag-active",children:[t,u.jsx("button",{type:"button",onClick:a,"aria-label":`Remove refinement ${t}`,className:"focus-ring ml-1 rounded-full",children:"×"})]})}function Ch({className:t="",width:a,height:r}){const i={};return a!==void 0&&(i.width=a),r!==void 0&&(i.height=r),u.jsx("div",{className:`skeleton ${t}`.trim(),style:Object.keys(i).length?i:void 0,"aria-hidden":"true"})}function Yb(t,a){const[r,i]=b.useState(t);return b.useEffect(()=>{const o=setTimeout(()=>i(t),a);return()=>clearTimeout(o)},[t,a]),r}function A3(t){const[a,r]=b.useState(!1),[i,o]=b.useState(t);t!==i&&(o(t),r(!1));const c=b.useCallback(()=>r(!0),[]);return{dismissed:a,dismiss:c}}const _3=["auto","always","never"],fl="auto",R3="lens:path-tree:";function lS(t){return R3+t}function C3(t){return typeof t=="string"&&_3.includes(t)?t:fl}function Pb(t){try{const a=localStorage.getItem(lS(t));if(!a)return fl;const r=JSON.parse(a);return C3(r.mode)}catch{return fl}}function M3(t,a){try{localStorage.setItem(lS(t),JSON.stringify({mode:a}))}catch{}}function O3(t){const[a,r]=b.useState(()=>t?Pb(t):fl);b.useEffect(()=>{r(t?Pb(t):fl)},[t]);const i=b.useCallback(o=>{t&&(M3(t,o),r(o))},[t]);return{mode:a,setMode:i}}function Fb(t){var r,i;const a=new URLSearchParams;(r=t.search)!=null&&r.trim()&&a.set("search",t.search.trim());for(const o of t.tags??[])a.append("tag",o);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 Xb(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 D3(t){var a,r;return!!((a=t.search)!=null&&a.trim()||t.tags&&t.tags.length>0||(r=t.pathPrefix)!=null&&r.trim())}function k3(t,a){var i,o;const r={};return(i=t.search)!=null&&i.trim()&&(r.search=t.search.trim()),t.tags&&t.tags.length>0&&(r.tag=[...t.tags]),t.tags&&t.tags.length>1&&t.tagMatch&&(r.tag_match=t.tagMatch),(o=t.pathPrefix)!=null&&o.trim()&&(r.path_prefix=t.pathPrefix.trim()),t.sort&&(r.sort=t.sort),t.showArchived||(r.exclude_tags=[a]),r}const L3=["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 U3(t){return L3.find(a=>a===t)}function Mh({preset:t,lens:a}={}){return a==="recent"?u.jsx(B3,{}):u.jsx(z3,{preset:t})}function uS({name:t}){return u.jsxs("header",{className:"mb-6",children:[u.jsx("h1",{className:"page-title",style:{fontSize:"clamp(2rem, 4vw, 2.6rem)"},children:t}),u.jsx("p",{className:"mt-1.5 text-fg-muted",children:"Everything here is yours. Open format. Export anytime."})]})}function z3({preset:t}){var Cl,ei;const a=ne(re=>re.getActiveVault()),{roles:r}=Xs((a==null?void 0:a.id)??null),{pinnedTags:i}=RR((a==null?void 0:a.id)??null),[o,c]=Yh(),h=t??U3(o.get("view")),m=b.useMemo(()=>Xb(o),[o]),[p,y]=b.useState(m.search??""),[x,v]=b.useState(m.pathPrefix??""),[w,T]=b.useState(m.tags??[]),[E,_]=b.useState(m.tagMatch??"any"),[R,M]=b.useState(m.sort??"desc"),[V,H]=b.useState(m.showArchived??!1),[k,Y]=b.useState(0),$=b.useMemo(()=>o.toString(),[o]);b.useEffect(()=>{const re=Xb(new URLSearchParams($));y(re.search??""),v(re.pathPrefix??""),T(re.tags??[]),_(re.tagMatch??"any"),M(re.sort??"desc"),H(re.showArchived??!1)},[$]);const F=Yb(p,300),G=Yb(x,300);b.useEffect(()=>{if(h)return;const re={search:F,tags:w,tagMatch:E,pathPrefix:G,sort:R,showArchived:V};Fb(re).toString()!==$&&c(Fb(re),{replace:!0})},[h,F,G,w,E,R,V]);const Z=h==="pinned"||h==="archived"?h:null,{def:le}=aC(Z,r),de=b.useMemo(()=>{if(!Z)return w;const re=le?Sw(le.query):[];return Array.from(new Set([...re,...w]))},[Z,le,w]),ge=Z?"all":E;b.useEffect(()=>{Y(0)},[F,G,de,ge,R,V]);const we=b.useMemo(()=>({...ow,search:F,pathPrefix:G,tags:de,tagMatch:ge,sort:R,offset:k,limit:mr+1,...h==="untagged"?{hasTags:!1}:{},...h==="orphaned"?{hasLinks:!1}:{}}),[F,G,de,ge,R,k,h]),se=hw(we,{live:!1}),ee=cR(),O=Ew(r.view),P=mw(),ae=pt(),oe=sa(re=>re.push),[ye,j]=b.useState(!1),[q,X]=b.useState(!1);b.useEffect(()=>{if(!q)return;const re=at=>{at.key==="Escape"&&X(!1)};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[q]);const{mode:W}=O3((a==null?void 0:a.id)??null),[me,Se]=b.useState(!1),Me=!h&&W!=="never",ft=Me&&me,Ge=oR(ft),oa=b.useMemo(()=>(Ge.data??[]).map(re=>re.path),[Ge.data]),Or=ft&&(W==="always"||W==="auto"&&d3(oa)),Ga=b.useMemo(()=>({search:F,tags:w,tagMatch:E,pathPrefix:G,sort:R,showArchived:V}),[F,G,w,E,R,V]),Nl=b.useCallback(async re=>{try{const at=await P.mutateAsync({content:"",path:_m(re),tags:[r.view],metadata:{kind:"list",query:JSON.stringify(k3(Ga,r.archived))}});ae.setQueriesData({queryKey:["viewList",a==null?void 0:a.id]},Ht=>[...(Ht??[]).filter(gt=>gt.id!==at.id),at]),ae.invalidateQueries({queryKey:["viewList",a==null?void 0:a.id]}),oe(`Saved view "${re}".`,"success"),j(!1)}catch(at){oe(`Could not save view: ${at.message}`,"error")}},[P,Ga,r.view,r.archived,ae,a==null?void 0:a.id,oe]),Cn=b.useMemo(()=>(O.data??[]).map(re=>Am(re).title),[O.data]),Bt=b.useMemo(()=>{if(!se.data)return se.data;let re=se.data.slice(0,mr);if(!h&&!V&&(re=re.filter(at=>!(at.tags??[]).includes(r.archived))),!h){const at=r.pinned;re=[...re].sort((Ht,gt)=>{const wn=(Ht.tags??[]).includes(at)?0:1,jt=(gt.tags??[]).includes(at)?0:1;return wn-jt})}return re},[se.data,h,V,r.archived,r.pinned]);if(!a)return u.jsx(dn,{to:"/",replace:!0});const Dr=oS[h??"all"],Pu=k+1,Al=k+((Bt==null?void 0:Bt.length)??0),kr=k>0,Lr=((Cl=se.data)==null?void 0:Cl.length)??0,Ya=Lr>mr,_l=Ya?null:k+Lr,Fu=_l!==null?` of ${_l}`:` of ${k+mr}+`,St=D3(Ga),Xu=(w.length>0?1:0)+(x.trim()?1:0)+(V?1:0)+(R!=="desc"?1:0),Ws=!h&&!St&&Xu===0&&!se.isPending&&(((ei=se.data)==null?void 0:ei.length)??0)===0&&k===0,Rl=!Ws,Ur=kr||Ya||((Bt==null?void 0:Bt.length)??0)>0;return u.jsxs("div",{className:"page-surface",children:[u.jsx(uS,{name:a.name}),u.jsx(Zw,{}),h?null:u.jsx(Xw,{vault:a,focused:!1},a.id),u.jsxs("div",{className:"mb-6",children:[u.jsxs("div",{"data-notes-chrome":!0,className:"flex items-center gap-3",children:[u.jsx("input",{type:"search",placeholder:"Search…",value:p,onChange:re=>y(re.target.value),className:"input min-w-0 flex-1","aria-label":"Search notes"}),Rl?u.jsxs("div",{className:"relative",children:[u.jsxs("button",{type:"button",onClick:()=>X(re=>!re),"aria-expanded":q,"aria-controls":"notes-filters",className:"btn btn-secondary btn-touch shrink-0",children:["Filters",u.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:q?"▴":"▾"})]}),q?u.jsxs(u.Fragment,{children:[u.jsx("button",{type:"button","aria-hidden":"true",tabIndex:-1,onClick:()=>X(!1),className:"enter-fade fixed inset-0 z-30 cursor-default bg-black/40 sm:bg-transparent"}),u.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:u.jsxs("div",{className:"space-y-5",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"eyebrow mb-3",children:"Refine"}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("button",{type:"button",onClick:()=>M(re=>re==="desc"?"asc":"desc"),className:"focus-ring block text-fg-muted text-sm hover:text-accent","aria-label":"Toggle sort direction",children:["Sort: ",R==="desc"?"newest":"oldest"," first"]}),h?null:u.jsxs("label",{className:"flex items-center gap-1.5 text-fg-muted text-sm hover:text-accent",children:[u.jsx("input",{type:"checkbox",checked:V,onChange:re=>H(re.target.checked)}),"Show archived"]}),u.jsx("input",{type:"text",placeholder:"Title starts with…",value:x,onChange:re=>v(re.target.value),className:"input w-full font-mono","aria-label":"Filter by path prefix"}),u.jsx(P3,{active:h})]})]}),h!=="untagged"?u.jsxs("div",{children:[u.jsx(j3,{tags:ee.data??[],pinnedTags:i,selected:w,onToggle:re=>T(at=>at.includes(re)?at.filter(Ht=>Ht!==re):[...at,re]),onClear:()=>T([]),isLoading:ee.isPending}),w.length>1?u.jsxs("fieldset",{className:"mt-3 flex items-center gap-3 text-xs",children:[u.jsx("legend",{className:"sr-only",children:"Match mode"}),u.jsx("span",{className:"text-fg-dim",children:"Match"}),u.jsxs("label",{className:"flex items-center gap-1.5",children:[u.jsx("input",{type:"radio",name:"tag-match",value:"any",checked:E==="any",onChange:()=>_("any")}),"Any"]}),u.jsxs("label",{className:"flex items-center gap-1.5",children:[u.jsx("input",{type:"radio",name:"tag-match",value:"all",checked:E==="all",onChange:()=>_("all")}),"All"]})]}):null]}):null,Me?u.jsxs("details",{className:"group",open:me,onToggle:re=>Se(re.currentTarget.open),children:[u.jsxs("summary",{className:"eyebrow flex cursor-pointer list-none items-center justify-between rounded-lg px-1 py-1 hover:text-accent",children:[u.jsx("span",{children:"Folders"}),u.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs transition-transform group-open:rotate-90",children:"▸"})]}),u.jsx("div",{className:"mt-2",children:Or?u.jsx(h3,{paths:oa,vaultId:a.id,currentPrefix:x,onSelect:re=>v(re)}):Ge.isLoading?u.jsx("p",{className:"px-1 text-xs text-fg-dim",children:"Loading…"}):u.jsx("p",{className:"px-1 text-xs text-fg-dim",children:"Not enough folder variety to show a tree yet."})})]}):null]})})]}):null]}):null]}),u.jsx(K3,{selectedTags:w,onRemoveTag:re=>T(at=>at.filter(Ht=>Ht!==re)),tagMatch:E,onToggleTagMatch:()=>_(re=>re==="all"?"any":"all"),pathPrefix:x,onClearPathPrefix:()=>v(""),showArchived:V,onClearArchived:()=>H(!1),sort:R,onResetSort:()=>M("desc"),showSave:St,onSaveView:()=>j(!0)})]}),Ws?null:u.jsxs(km,{children:[Dr.label,u.jsxs("span",{className:"font-sans normal-case tracking-normal text-fg-muted",children:[" ","· ",Dr.hint]})]}),se.isPending?u.jsx(F3,{}):se.isError&&!se.data?u.jsx(X3,{error:se.error,retry:()=>se.refetch()}):Bt&&Bt.length>0?u.jsxs(u.Fragment,{children:[se.isError?u.jsx(iS,{}):null,u.jsx(Ww,{"aria-label":"Notes",children:Bt.map(re=>u.jsx(Jw,{note:re,pinnedTag:r.pinned,archivedTag:r.archived,trailing:h==="untagged"?u.jsx(Y3,{noteId:re.id,existing:re.tags??[],suggestions:ee.data??[]}):void 0},re.id))})]}):u.jsx(Z3,{filtering:U2(we)||!!h}),Ur?u.jsxs("div",{className:"mt-6 flex items-center justify-between text-fg-dim text-sm",children:[u.jsx("span",{children:se.data&&se.data.length>0?`Showing ${Pu}–${Al}${Fu}`:se.isFetching?"Loading…":""}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("button",{type:"button",disabled:!kr,onClick:()=>Y(re=>Math.max(0,re-mr)),className:"btn btn-secondary btn-touch",children:"Previous"}),u.jsx("button",{type:"button",disabled:!Ya,onClick:()=>Y(re=>re+mr),className:"btn btn-secondary btn-touch",children:"Next"})]})]}):null,ye?u.jsx(G3,{existingNames:Cn,isSaving:P.isPending,onCancel:()=>j(!1),onSave:Nl}):null]})}const V3=100;function B3(){var Y,$,F;const t=ne(G=>G.getActiveVault()),{dismissed:a,dismiss:r}=A3((t==null?void 0:t.id)??null),{roles:i}=Xs((t==null?void 0:t.id)??null),o=rS(Yu(),-13),c=lR({field:"updated_at",from:p3(o),excludeTag:i.archived,limit:iR}),h=t!==null&&Gs(t.clientId),m=lm({enabled:h}),p=((Y=h?im(m.data):null)==null?void 0:Y.plan)??null,y=typeof(p==null?void 0:p.trial_days_left)=="number"?p.trial_days_left:null,x=b.useMemo(()=>{if(!c.data)return;const G=Z=>Z.updatedAt??Z.createdAt;return c.data.filter(Z=>!(Z.tags??[]).includes(i.archived)).filter(Z=>(aS(G(Z))??"")>=o).sort((Z,le)=>G(Z)<G(le)?1:G(Z)>G(le)?-1:0).slice(0,V3)},[o,c.data,i.archived]);if(!t)return u.jsx(dn,{to:"/",replace:!0});const v=c.data!==void 0,w=O0(c.data),T=D0({hasUserNote:w}),E=UA(T),_=!a&&!E,R=T.filter(G=>!G.done),M=T.length-R.length,V=v&&!w&&_?"fresh":"returning",H=!c.isPending&&((($=c.data)==null?void 0:$.length)??0)===0,k=oS.recent;return u.jsxs("div",{className:"page-surface",children:[u.jsx(uS,{name:t.name}),u.jsx(Zw,{}),u.jsx(Xw,{vault:t,focused:V==="fresh"},t.id),u.jsx(H3,{daysLeft:y}),V==="fresh"?u.jsx(q3,{}):null,_&&R.length>0?u.jsx($3,{to:Wb[R[0].id].to,label:Wb[R[0].id].label,done:M,total:T.length,onDismiss:r}):null,u.jsxs("section",{"aria-label":"Recent notes",children:[H?null:u.jsxs(km,{children:[k.label,u.jsxs("span",{className:"font-sans normal-case tracking-normal text-fg-muted",children:[" ","· ",k.hint]})]}),c.isPending?u.jsx(Q3,{}):c.isError&&!c.data?u.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."}):(((F=c.data)==null?void 0:F.length)??0)===0?u.jsxs("div",{className:"rounded-xl border border-border bg-card p-8 text-center shadow-soft",children:[u.jsx("p",{className:"mb-1 font-serif text-fg text-lg",children:"A quiet, empty page."}),u.jsx("p",{className:"mb-5 text-fg-muted text-sm",children:"Anything at all can land here — a thought, a list, a memory."}),u.jsx("button",{type:"button",onClick:()=>{var G;return(G=document.getElementById(Fw))==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"})]}):((x==null?void 0:x.length)??0)===0?u.jsxs(u.Fragment,{children:[u.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."}),u.jsx(Zb,{})]}):u.jsxs(u.Fragment,{children:[c.isError?u.jsx(iS,{}):null,u.jsx(b3,{notes:x??[]}),u.jsx(Zb,{})]})]}),u.jsx(I3,{clientId:t.clientId,trialDaysLeft:y})]})}function Zb(){return u.jsxs("p",{className:"mt-6 text-fg-dim text-sm",children:["Looking for older notes?"," ",u.jsx(Ne,{to:"/notes",className:"text-accent hover:underline",children:"All notes →"})]})}function H3({daysLeft:t}){return t===null||t>7?null:u.jsxs("div",{className:"nudge-sun mb-6",children:[u.jsx("span",{"aria-hidden":"true",children:"✦"}),u.jsx(Ne,{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 q3(){return u.jsxs("nav",{"aria-label":"Quick actions",className:"mb-6 grid gap-3 sm:grid-cols-2",children:[u.jsx(Jb,{to:"/connect",emoji:"⚡",title:"Connect your AI",description:"Let Claude or ChatGPT read and write your vault."}),u.jsx(Jb,{to:"/import",emoji:"↯",title:"Bring your notes over",description:"Import from Obsidian or plain markdown."})]})}function Jb({to:t,emoji:a,title:r,description:i}){return u.jsxs(Ne,{to:t,className:"focus-ring tile flex items-start gap-3 p-4",children:[u.jsx("span",{"aria-hidden":"true",className:"text-lg leading-none",children:a}),u.jsxs("span",{className:"min-w-0",children:[u.jsx("span",{className:"block font-medium text-fg",children:r}),u.jsx("span",{className:"mt-0.5 block text-fg-muted text-sm",children:i})]})]})}const Wb={write:{label:"Write your first note",to:"/new"}};function $3({to:t,label:a,done:r,total:i,onDismiss:o}){return u.jsxs("div",{className:"nudge-sun mb-8",children:[u.jsx("span",{"aria-hidden":"true",children:"✦"}),u.jsxs(Ne,{to:t,className:"min-w-0 flex-1 truncate hover:underline",children:["Finish setting up — ",a]}),u.jsxs("span",{className:"font-round text-sm opacity-80",children:[r," / ",i]}),u.jsx("button",{type:"button",onClick:o,"aria-label":"Dismiss setup",className:"ml-1 text-sun-ink/70 hover:text-sun-ink",children:"✕"})]})}function Q3(){return u.jsx("div",{className:"space-y-3","aria-busy":"true",children:[0,1,2].map(t=>u.jsx(Ch,{className:"h-14 rounded-xl"},t))})}function I3({clientId:t,trialDaysLeft:a}){return Gs(t)?u.jsx("div",{className:"mt-10 border-t border-border pt-4 text-sm",children:u.jsx(Ne,{to:"/account",className:"text-fg-dim hover:text-accent",children:a!==null?u.jsxs(u.Fragment,{children:[u.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 K3({selectedTags:t,onRemoveTag:a,tagMatch:r,onToggleTagMatch:i,pathPrefix:o,onClearPathPrefix:c,showArchived:h,onClearArchived:m,sort:p,onResetSort:y,showSave:x,onSaveView:v}){const w=o.trim();return!(t.length>0||w.length>0||h||p==="asc")&&!x?null:u.jsxs("div",{"aria-label":"Active filters",className:"mt-3 flex flex-wrap items-center gap-2",children:[t.map(E=>u.jsx(su,{label:`#${E}`,onRemove:()=>a(E)},`tag-${E}`)),t.length>1?u.jsxs("button",{type:"button",onClick:i,"aria-label":`Tag match is currently "${r}" — click to switch`,className:"chip",children:["match ",r,u.jsx("span",{"aria-hidden":"true",className:"ml-1",children:"▾"})]}):null,w?u.jsx(su,{label:`title: ${w}`,onRemove:c}):null,h?u.jsx(su,{label:"archived shown",onRemove:m}):null,p==="asc"?u.jsx(su,{label:"oldest first",onRemove:y}):null,x?u.jsx("button",{type:"button",onClick:v,className:"btn btn-accent-soft btn-sm ml-auto",children:"Save as view…"}):null]})}function G3({existingNames:t,isSaving:a,onCancel:r,onSave:i}){const[o,c]=b.useState(""),h=o.trim(),m=YR(h,t.map(_m)),p=h.length>0&&!m&&!a;return u.jsx("div",{className:"dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Save view",children:u.jsxs("div",{className:"dialog-panel max-w-(--w-narrow)",children:[u.jsx("h3",{className:"mb-3 font-serif text-lg text-fg",children:"Save view"}),u.jsxs("label",{className:"block text-sm",children:[u.jsx("span",{className:"mb-1 block text-fg-muted",children:"Name"}),u.jsx("input",{type:"text",value:o,autoFocus:!0,onChange:y=>c(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?u.jsx("p",{className:"mt-2 text-xs text-danger",children:"A view with that name already exists."}):null,u.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[u.jsx("button",{type:"button",onClick:r,className:"btn btn-secondary btn-touch",children:"Cancel"}),u.jsx("button",{type:"button",onClick:()=>p&&i(h),disabled:!p,className:"btn btn-primary btn-touch",children:a?"Saving…":"Save"})]})]})})}function Y3({noteId:t,existing:a,suggestions:r}){const[i,o]=b.useState(!1),[c,h]=b.useState(""),m=b.useRef(null),p=b.useRef(null),y=yR(t),x=sa(T=>T.push);b.useEffect(()=>{var _;if(!i)return;(_=p.current)==null||_.focus();const T=R=>{var M;(M=m.current)!=null&&M.contains(R.target)||o(!1)},E=R=>{R.key==="Escape"&&o(!1)};return document.addEventListener("mousedown",T),document.addEventListener("keydown",E),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",E)}},[i]);const v=b.useMemo(()=>{const T=_u(c).toLowerCase(),E=new Set(a.map(R=>R.toLowerCase())),_=r.filter(R=>!E.has(R.name.toLowerCase()));return T?_.filter(R=>R.name.toLowerCase().includes(T)).slice(0,8):_.slice(0,8)},[c,r,a]),w=b.useCallback(async T=>{const E=_u(T);if(E)try{await y.mutateAsync({tags:{add:[E]}}),x(`Added #${E}`,"success"),h(""),o(!1)}catch(_){x(`Could not add tag: ${_.message}`,"error")}},[y,x]);return i?u.jsxs("div",{ref:m,className:"relative",children:[u.jsx("input",{ref:p,type:"text",value:c,onChange:T=>h(T.target.value),onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),w(c))},placeholder:"tag…","aria-label":"Tag name",disabled:y.isPending,className:"input w-32 px-2 py-1 text-xs"}),v.length>0?u.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=>u.jsx("li",{children:u.jsxs("button",{type:"button",onMouseDown:E=>{E.preventDefault(),w(T.name)},className:"flex w-full items-center justify-between px-2 py-1 text-left text-fg hover:bg-bg/60",children:[u.jsx("span",{className:"truncate",children:T.name}),u.jsx("span",{className:"ml-2 shrink-0 text-fg-dim",children:T.count??0})]})},T.name))}):null]}):u.jsx("button",{type:"button",onClick:()=>o(!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 u.jsxs("nav",{"aria-label":"Show only",className:"flex flex-wrap items-center gap-2",children:[u.jsx("span",{className:"text-fg-muted text-sm",children:"Show only:"}),a.map(r=>{const i=r.view===t;return u.jsx(Ne,{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 F3(){return u.jsx("ol",{className:"flex flex-col gap-0.5","aria-busy":"true",children:[0,1,2,3,4].map(t=>u.jsxs("li",{className:"rounded-xl px-3 py-3",children:[u.jsx(Ch,{className:"h-4 w-1/3"}),u.jsx(Ch,{className:"mt-2 h-3 w-2/3"})]},t))})}function X3({error:t,retry:a}){const r=t instanceof qu;return u.jsx(_w,{title:r?"Session expired":"Could not load notes",message:t.message,retry:r?void 0:a,action:r?u.jsx(Ne,{to:"/add",className:"btn btn-primary",children:"Reconnect vault"}):void 0})}function Z3({filtering:t}){return t?u.jsx(Ah,{title:"No notes match these filters."}):u.jsx(Ah,{title:"This vault has no notes yet.",action:u.jsx(Ne,{to:"/new",className:"btn btn-primary",children:"Create one"})})}const J3=b.lazy(()=>Ke(()=>import("./Account-CoSQwMlJ.js"),__vite__mapDeps([0,1])).then(t=>({default:t.Account}))),W3=b.lazy(()=>Ke(()=>import("./Activity-kaMFa3fK.js"),[]).then(t=>({default:t.Activity}))),eD=b.lazy(()=>Ke(()=>import("./AddVault-BdEbS-at.js"),__vite__mapDeps([2,3,4,5])).then(t=>({default:t.AddVault}))),tD=b.lazy(()=>Ke(()=>import("./AddVaultChooser-DR4cyJeZ.js"),__vite__mapDeps([6,3,4])).then(t=>({default:t.AddVaultChooser}))),nD=b.lazy(()=>Ke(()=>import("./AddVaultCreate-DKSKUeG8.js"),__vite__mapDeps([7,3,4])).then(t=>({default:t.AddVaultCreate}))),aD=b.lazy(()=>Ke(()=>import("./AddVaultCreate-DKSKUeG8.js"),__vite__mapDeps([7,3,4])).then(t=>({default:t.AddVaultReady}))),rD=b.lazy(()=>Ke(()=>import("./Calendar-_loW0paP.js"),[]).then(t=>({default:t.Calendar}))),sD=b.lazy(()=>Ke(()=>import("./ConnectAI-DQ_N7ZF3.js"),[]).then(t=>({default:t.ConnectAI}))),iD=b.lazy(()=>Ke(()=>import("./DayView-DtlzBMFH.js"),__vite__mapDeps([8,4])).then(t=>({default:t.DayView}))),lD=b.lazy(()=>Ke(()=>import("./Export-kSyvEi0u.js"),[]).then(t=>({default:t.Export}))),oD=b.lazy(()=>Ke(()=>import("./Import-3fbKo4w8.js"),__vite__mapDeps([9,10])).then(t=>({default:t.Import}))),uD=b.lazy(()=>Ke(()=>import("./NoteEditor-CpulwbX3.js"),__vite__mapDeps([11,10,12,13,14,15])).then(t=>({default:t.NoteEditor}))),cD=b.lazy(()=>Ke(()=>import("./NoteNew-Cc6a1vru.js"),__vite__mapDeps([16,10,12,13,17,18,15])).then(t=>({default:t.NoteNew}))),fD=b.lazy(()=>Ke(()=>import("./NoteView-BQ3li7s2.js"),__vite__mapDeps([19,14,13])).then(t=>({default:t.NoteView}))),dD=b.lazy(()=>Ke(()=>import("./OAuthCallback-pBSW2lKo.js"),__vite__mapDeps([20,3,4,5])).then(t=>({default:t.OAuthCallback}))),hD=b.lazy(()=>Ke(()=>import("./Settings-CPo-Wt-I.js"),__vite__mapDeps([21,17,18,15])).then(t=>({default:t.Settings}))),mD=b.lazy(()=>Ke(()=>import("./Tags-CylsLohS.js"),__vite__mapDeps([22,23])).then(t=>({default:t.Tags}))),pD=b.lazy(()=>Ke(()=>import("./TagPage-BnEENXCy.js"),__vite__mapDeps([24,25,23])).then(t=>({default:t.TagPage}))),gD=b.lazy(()=>Ke(()=>import("./VaultGraph-BUmNoSkm.js"),[]).then(t=>({default:t.VaultGraph}))),yD=b.lazy(()=>Ke(()=>import("./Vaults-BLhnLLYV.js"),__vite__mapDeps([26,1,18])).then(t=>({default:t.Vaults}))),vD=b.lazy(()=>Ke(()=>import("./Welcome-Ch_SVwda.js"),__vite__mapDeps([27,3,4,1])).then(t=>({default:t.Welcome}))),bD=b.lazy(()=>Ke(()=>import("./CheckEmail-PBWODeVZ.js"),__vite__mapDeps([28,3,4])).then(t=>({default:t.CheckEmail}))),xD=b.lazy(()=>Ke(()=>import("./ViewNew-AysTVG25.js"),[]).then(t=>({default:t.ViewNew}))),wD=b.lazy(()=>Ke(()=>import("./ViewSurface-CIpzYIN8.js"),__vite__mapDeps([25,23])).then(t=>({default:t.ViewSurface})));function SD(){const t=ne(h=>h.getActiveVault()),[a]=Yh(),[r,i]=b.useState(null),o=b.useRef(!1),c=b.useCallback(()=>{o.current=!0,i(null),Gw().catch(()=>{}),SO({hasLocalActiveVault:!1}).then(i).catch(()=>i({kind:"front-door"}))},[]);if(b.useEffect(()=>{t||o.current||c()},[t,c]),a.get("add"))return u.jsx(dn,{to:`/add?${a.toString()}`,replace:!0});if(t)return u.jsx(Le,{children:u.jsx(Mh,{lens:"recent"})});if(!r)return u.jsx(Le,{resetKey:"boot-loading",children:u.jsx(ED,{})});switch(r.kind){case"home":return u.jsx(Le,{children:u.jsx(Mh,{lens:"recent"})});case"signed-in":return u.jsx(Le,{resetKey:"boot-signed-in",children:u.jsx(Bd,{signedIn:{email:r.email,username:r.username,vaults:r.vaults}})});case"net-error":return u.jsx(Le,{resetKey:"boot-net-error",children:u.jsx(Bd,{netError:r.message,onRetry:c})});default:return u.jsx(Le,{resetKey:"boot-front-door",children:u.jsx(Bd,{})})}}function ED(){return u.jsx("output",{"aria-live":"polite",className:"mx-auto flex min-h-[50dvh] items-center justify-center text-sm text-fg-dim",children:u.jsx("span",{className:"animate-pulse",children:"Loading…"})})}function TD(){return u.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 ex({suffix:t=""}){const{id:a}=rj();return a?AO(window.location.pathname)?u.jsx(dn,{to:"/",replace:!0}):u.jsx(dn,{to:`/n/${encodeURIComponent(a)}${t}`,replace:!0}):u.jsx(dn,{to:"/",replace:!0})}function tx({to:t}){const a=Ie();return u.jsx(dn,{to:`${t}${a.search}`,replace:!0})}function jD(){return u.jsx("div",{className:"page",children:u.jsx(Ah,{title:u.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:u.jsx(Ne,{to:"/notes",className:"btn btn-primary btn-touch",children:"Back to notes"})})})}function ND(){const{pathname:t}=Ie();return Nw(t)?null:u.jsx("footer",{className:"mx-auto max-w-5xl px-6 py-10 text-center text-sm text-fg-dim",children:u.jsxs("p",{children:["Part of the"," ",u.jsx("a",{href:"https://parachute.computer",className:"focus-ring text-accent hover:underline",children:"Parachute Computer"})," ","ecosystem. AGPL-3.0."]})})}function AD(){const t=ne(r=>r.activeVaultId),a=ze();return DR(t,a),null}function _D(){const t=Ie(),r=ju(i=>i.on)&&Cw(t.pathname);return u.jsxs("div",{className:"app-canvas min-h-dvh overflow-x-hidden text-fg",children:[u.jsx(ZM,{}),u.jsx(iO,{}),u.jsx(lO,{}),u.jsx(eN,{}),u.jsx(tN,{}),u.jsx(_M,{}),u.jsx(HC,{}),u.jsxs("div",{className:"md:flex",children:[r?null:u.jsx(OM,{}),r?null:u.jsx(GM,{}),u.jsxs("div",{className:`flex min-w-0 flex-1 flex-col ${r?"":"pb-16 md:pb-0"}`,children:[r?null:u.jsx(AM,{}),u.jsx(IM,{}),u.jsx("main",{className:"flex-1","data-focus-safe-area":r?"true":void 0,style:r?{paddingTop:"env(safe-area-inset-top)"}:void 0,children:u.jsx(b.Suspense,{fallback:u.jsx(TD,{}),children:u.jsxs(bj,{children:[u.jsx(je,{path:"/",element:u.jsx(SD,{})}),u.jsx(je,{path:"/check-email",element:u.jsx(Le,{children:u.jsx(bD,{})})}),u.jsx(je,{path:"/notes",element:u.jsx(Le,{children:u.jsx(Mh,{})})}),u.jsx(je,{path:"/all",element:u.jsx(tx,{to:"/notes"})}),u.jsx(je,{path:"/pinned",element:u.jsx(dn,{to:"/notes?view=pinned",replace:!0})}),u.jsx(je,{path:"/archived",element:u.jsx(dn,{to:"/notes?view=archived",replace:!0})}),u.jsx(je,{path:"/untagged",element:u.jsx(dn,{to:"/notes?view=untagged",replace:!0})}),u.jsx(je,{path:"/orphaned",element:u.jsx(dn,{to:"/notes?view=orphaned",replace:!0})}),u.jsx(je,{path:"/tags",element:u.jsx(Le,{children:u.jsx(mD,{})})}),u.jsx(je,{path:"/tags/:name",element:u.jsx(Le,{children:u.jsx(pD,{})})}),u.jsx(je,{path:"/new",element:u.jsx(Le,{children:u.jsx(cD,{})})}),u.jsx(je,{path:"/capture",element:u.jsx(dn,{to:"/new",replace:!0})}),u.jsx(je,{path:"/import",element:u.jsx(Le,{children:u.jsx(oD,{})})}),u.jsx(je,{path:"/export",element:u.jsx(Le,{children:u.jsx(lD,{})})}),u.jsx(je,{path:"/connect",element:u.jsx(Le,{children:u.jsx(sD,{})})}),u.jsx(je,{path:"/map",element:u.jsx(Le,{children:u.jsx(gD,{})})}),u.jsx(je,{path:"/graph",element:u.jsx(tx,{to:"/map"})}),u.jsx(je,{path:"/today",element:u.jsx(Le,{children:u.jsx(iD,{})})}),u.jsx(je,{path:"/calendar",element:u.jsx(Le,{children:u.jsx(rD,{})})}),u.jsx(je,{path:"/activity",element:u.jsx(Le,{children:u.jsx(W3,{})})}),u.jsx(je,{path:"/views/new",element:u.jsx(Le,{children:u.jsx(xD,{})})}),u.jsx(je,{path:"/views/:id",element:u.jsx(Le,{children:u.jsx(wD,{})})}),u.jsx(je,{path:"/n/:id",element:u.jsx(Le,{children:u.jsx(fD,{})})}),u.jsx(je,{path:"/n/:id/edit",element:u.jsx(Le,{children:u.jsx(uD,{})})}),u.jsx(je,{path:"/:id",element:u.jsx(ex,{})}),u.jsx(je,{path:"/:id/edit",element:u.jsx(ex,{suffix:"/edit"})}),u.jsx(je,{path:"/add",element:u.jsx(Le,{children:u.jsx(eD,{})})}),u.jsx(je,{path:"/add-vault",element:u.jsx(Le,{children:u.jsx(tD,{})})}),u.jsx(je,{path:"/add-vault/create",element:u.jsx(Le,{children:u.jsx(nD,{})})}),u.jsx(je,{path:"/add-vault/ready",element:u.jsx(Le,{children:u.jsx(aD,{})})}),u.jsx(je,{path:"/welcome",element:u.jsx(Le,{children:u.jsx(vD,{})})}),u.jsx(je,{path:"/oauth/callback",element:u.jsx(Le,{children:u.jsx(dD,{})})}),u.jsx(je,{path:"/vaults",element:u.jsx(Le,{children:u.jsx(yD,{})})}),u.jsx(je,{path:"/account",element:u.jsx(Le,{children:u.jsx(J3,{})})}),u.jsx(je,{path:"/settings",element:u.jsx(Le,{children:u.jsx(hD,{})})}),u.jsx(je,{path:"*",element:u.jsx(jD,{})})]})})}),r?null:u.jsx(ND,{})]})]}),r?null:u.jsx(OC,{}),r?null:u.jsx(MC,{}),r?null:u.jsx(FM,{}),r?u.jsx(qC,{}):null]})}function RD(){vR(),b.useEffect(()=>{Dw(Ts())},[]);const t=ne(a=>{var r;return((r=a.getActiveVault())==null?void 0:r.name)??null});return b.useEffect(()=>{document.title=t?`Parachute — ${t}`:"Parachute"},[t]),u.jsx(VC,{children:u.jsx(jO,{children:u.jsxs(f2,{children:[u.jsx(AD,{}),u.jsx(tM,{}),u.jsx(Ij,{basename:yl(),children:u.jsx(RC,{children:u.jsx(_D,{})})})]})})})}var qd={exports:{}},Zi={},$d={exports:{}},Qd={};/**
|
|
34
|
+
`)}const J0=512*1024*1024,wb=200;function bh(t){return t.contentEvicted?0:typeof t.byteSize=="number"&&Number.isFinite(t.byteSize)&&t.byteSize>=0?t.byteSize:L_(t)}function L_(t){var r,i,o,c;let a=(((r=t.content)==null?void 0:r.length)??0)+(((i=t.preview)==null?void 0:i.length)??0);return(o=t.links)!=null&&o.length&&(a+=JSON.stringify(t.links).length),(c=t.attachments)!=null&&c.length&&(a+=JSON.stringify(t.attachments).length),a}function U_(t){var a,r;return!!(t.content||(a=t.links)!=null&&a.length||(r=t.attachments)!=null&&r.length)}function z_(t){const a=t.preview??V_(t.content),i=t.displayTitle??ym(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 V_(t){if(!t)return;const a=R_(t).replace(/\s+/g," ").trim();if(a)return a.length>wb?`${a.slice(0,wb).trimEnd()}…`:a}function B_(t,a,r){let i=0;for(const h of t)i+=bh(h);const o=i,c=[];if(i>a)for(const h of t){if(i<=a)break;h.contentEvicted||r(h.id)||U_(h)&&(c.push(h),i-=bh(h))}return{toEvict:c,totalBefore:o,totalAfter:i,freedBytes:o-i}}async function H_(t,a,r=J0){const i=await Hu(t,a),o=await vh(t,a),c=K0(o),h=B_(i,r,c);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(z_(p));return await m.done,{evicted:h.toEvict.length,freedBytes:h.freedBytes,totalBytes:h.totalAfter}}async function rk(t,a){const r=await Hu(t,a);let i=0;for(const o of r)i+=bh(o);return i}function W0(t){return`mirror:${t}`}function ew(){const t=typeof navigator<"u"?navigator.locks:void 0;return t!=null&&t.request?t:void 0}async function q_(t,a,r){const i=ew();return i?i.request(W0(t),{ifAvailable:!0},async o=>o?await r():await a()):r()}const $_=15e3;async function Q_(t,a,r=$_){const i=ew();return i?i.request(W0(t),{signal:AbortSignal.timeout(r)},async()=>await a()):a()}const I_={includeContent:!0,includeLinks:!0,includeAttachments:!0},Sb={includeContent:!1,includeLinks:!1,includeAttachments:!1},K_=6e4,G_=200,Y_=1e3,P_=360*60*1e3,F_=1e3;function X_(t){return t instanceof Error?/cursor_invalid|cursor_query_mismatch/i.test(t.message):!1}class Z_{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??K_,this.pageLimit=a.pageLimit??G_,this.maxDrainPages=a.maxDrainPages??F_,this.sweepEnumLimit=a.sweepEnumLimit??Y_,this.sweepIntervalMs=a.sweepIntervalMs??P_,this.ceilingBytes=a.ceilingBytes??J0,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){return q_(a,r,i)}async drainCursor(a,r){var p,y,x,v,w,T,E,_,R,M;let i=await s_(this.db,r)??"";const o=await xu(this.db,r)===void 0;if(o){const V={phase:"hydrating"};await Ed(this.db,r,V),(y=(p=this.opts).onStateChange)==null||y.call(p,r,V),(v=(x=this.opts).onProgress)==null||v.call(x,r,0)}let c=0,h=0,m=!1;try{let V=!1;for(;;){const k=i;let Y;try{Y=await a.queryNotesCursor(I_,k,this.pageLimit)}catch(F){if(!m&&X_(F)){await B0(this.db,r),i="",m=!0;continue}throw F}const $=Y.items??[];if($.length>0&&(await h_(this.db,r,$),h+=$.length,o&&((T=(w=this.opts).onProgress)==null||T.call(w,r,h))),$.length>0&&Y.nextCursor===void 0)throw new Error(`mirror drain: ${$.length}-row page returned no next_cursor — cursor pagination contract violated (stale surface-client?)`);if(Y.nextCursor!==void 0&&(i=Y.nextCursor,await i_(this.db,r,i)),c+=1,$.length===0){V=!0;break}if(Y.nextCursor===k)break;if(c>=this.maxDrainPages)throw new Error(`mirror drain: exceeded ${this.maxDrainPages} pages without exhausting the cursor`)}V&&await o_(this.db,r,Date.now());const H={phase:"live"};return await Ed(this.db,r,H),(_=(E=this.opts).onStateChange)==null||_.call(E,r,H),{pagesApplied:c,notesApplied:h,reWalked:m}}catch(V){const H=V instanceof Error?V.message:String(V),k={phase:"error",lastError:H};return await Ed(this.db,r,k),(M=(R=this.opts).onStateChange)==null||M.call(R,r,k),{pagesApplied:c,notesApplied:h,reWalked:m,error:H}}}async maybeSweep(a,r){if(r.error||r.skipped)return;const i=await u_(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"),()=>H_(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 o=await vh(this.db,r),c=K0(o),h=await Hu(this.db,r),m=T_(h,i.index,c);await m_(this.db,r,m.toDelete);let p=0,y=0;if(a.getNote){for(const x of m.toBackfill){const v=await a.getNote(x,{includeLinks:!0,includeAttachments:!0});v&&(await yh(this.db,r,v),p+=1)}for(const x of m.toRefetch){const v=await a.getNote(x,{includeLinks:!0,includeAttachments:!0});v&&(await yh(this.db,r,v),y+=1)}}return await this.refreshTags(a,r),await c_(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="",o=0;try{for(;;){const c=i,h=await a.queryNotesCursor(Sb,c,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===c)return{index:r,complete:!1};if(o+=1,o>=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 f_(this.db,r,i)}catch{}}ensureSubscription(a){var c;const r=a.client;if(!r.subscribe||((c=this.subscription)==null?void 0:c.vaultId)===a.vaultId)return;this.teardownSubscription();const i=a.vaultId,o=r.subscribe(Sb,{onSnapshot:()=>{},onUpsert:()=>{},onRemove:h=>this.applyWsRemove(i,h)});this.subscription={vaultId:i,unsubscribe:o}}teardownSubscription(){var a;(a=this.subscription)==null||a.unsubscribe(),this.subscription=null}async applyWsRemove(a,r){try{if(Hs(r)||(await vh(this.db,a)).has(r))return;await q0(this.db,a,r)}catch{}}}const J_="lens-blobs";function W_(){return typeof navigator<"u"&&typeof navigator.storage<"u"&&typeof navigator.storage.getDirectory=="function"}async function jd(){return(await navigator.storage.getDirectory()).getDirectoryHandle(J_,{create:!0})}function sk(){return crypto.randomUUID()}class e2{constructor(){fe(this,"backend","opfs")}async put(a,r,i){const o=await jd(),h=await(await o.getFileHandle(a,{create:!0})).createWritable();await h.write(r),await h.close();const p=await(await o.getFileHandle(`${a}.meta`,{create:!0})).createWritable();await p.write(i),await p.close()}async get(a){try{const r=await jd(),c=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:c,mimeType:h}}catch(r){if(r instanceof DOMException&&r.name==="NotFoundError")return null;throw r}}async delete(a){const r=await jd();for(const i of[a,`${a}.meta`])try{await r.removeEntry(i)}catch(o){if(o instanceof DOMException&&o.name==="NotFoundError")continue;throw o}}}class t2{constructor(a){fe(this,"backend","idb");this.db=a}async put(a,r,i,o){await this.db.put("blobs",{blobId:a,data:r,mimeType:i,vaultId:o,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 n2(t){return W_()?new e2:new t2(t)}const a2=3e4;class r2{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??a2,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,o,c;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 T2({db:this.opts.db,client:a.client,vaultId:a.vaultId,blobStore:this.opts.blobStore,...this.opts.mirror&&{mirror:this.opts.mirror}});return(c=(o=this.opts).onDrain)==null||c.call(o,h),h}finally{this.draining=!1}}}async function s2(){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 i2(){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 l2(){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([i2(),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 tw="lens:sync:lastSyncedAt";function o2(){try{const t=localStorage.getItem(tw);if(!t)return null;const a=Number(t);return Number.isFinite(a)?a:null}catch{return null}}const u2={enabled:!1,state:"off",lastSyncedAt:null,syncNow:async()=>{},clearOffline:async()=>{}},nw=b.createContext({db:null,blobStore:null,engine:null,isOnline:!0,isDraining:!1,lastSyncedAt:null,mirror:u2});function c2(t,a,r,i){return t?a?r==="error"?"error":r==="hydrating"||r===void 0&&i===null?"hydrating":"synced":"offline":"off"}function Wt(){return b.useContext(nw)}function f2({children:t}){const[a,r]=b.useState(null),[i,o]=b.useState(null),[c,h]=b.useState(typeof navigator<"u"?navigator.onLine:!0),[m,p]=b.useState(!1),[y,x]=b.useState(()=>o2()),v=ze(),w=ne(se=>se.activeVaultId),T=pt(),E=b.useMemo(()=>ia(),[]),[_,R]=b.useState(void 0),[M,V]=b.useState(void 0),[H,k]=b.useState(null);b.useEffect(()=>{let se=!1,ee=null;return a_().then(O=>{if(se){O.close();return}ee=O,r(O),o(n2(O)),s2()}).catch(()=>{}),()=>{se=!0,ee==null||ee.close()}},[]),b.useEffect(()=>{if(typeof window>"u")return;const se=()=>h(!0),ee=()=>h(!1);return window.addEventListener("online",se),window.addEventListener("offline",ee),()=>{window.removeEventListener("online",se),window.removeEventListener("offline",ee)}},[]);const Y=b.useRef(v),$=b.useRef(w),F=b.useRef(T);Y.current=v,$.current=w,F.current=T;const G=b.useMemo(()=>!a||!i?null:new r2({db:a,blobStore:i,mirror:b_(a),resolveContext:()=>{const se=Y.current,ee=$.current;return!se||!ee?null:{client:se,vaultId:ee}},onDrainStart:()=>{p(!0)},onDrain:se=>{if(p(!1),se.drained>0){const ee=Date.now();x(ee);try{localStorage.setItem(tw,String(ee))}catch{}const O=$.current;F.current.invalidateQueries({queryKey:["notes",O]}),F.current.invalidateQueries({queryKey:["tags",O]}),F.current.invalidateQueries({queryKey:["vaultInfo",O]})}}}),[a,i]);b.useEffect(()=>{if(G)return G.start(),()=>G.stop()},[G]);const Z=b.useMemo(()=>{if(!a||!E)return null;const se=ee=>ee===$.current;return new Z_({db:a,resolveContext:()=>{const ee=Y.current,O=$.current;return!ee||!O?null:{client:ee,vaultId:O}},onStateChange:(ee,O)=>{se(ee)&&(R(O.phase),O.phase==="live"&&(V(void 0),xu(a,ee).then(P=>{se(ee)&&k(P??null)})))},onProgress:(ee,O)=>{se(ee)&&V({done:O})}})},[a,E]);b.useEffect(()=>{if(Z)return Z.start(),()=>Z.stop()},[Z]),b.useEffect(()=>{if(!a||!E||!w){R(void 0),V(void 0),k(null);return}let se=!0;return V(void 0),Promise.all([l_(a,w),xu(a,w)]).then(([ee,O])=>{se&&(R(ee==null?void 0:ee.phase),k(O??null))}),()=>{se=!1}},[a,E,w]);const le=b.useCallback(async()=>{await(Z==null?void 0:Z.syncOnce())},[Z]),de=b.useCallback(async()=>{!a||!w||(await Q_(w,async()=>{await y_(a,w),await B0(a,w),await d_(a,w)}),R(void 0),V(void 0),k(null),T.invalidateQueries({queryKey:["notes",w]}),T.invalidateQueries({queryKey:["notesForDateViews",w]}),T.invalidateQueries({queryKey:["notesForPathTree",w]}),T.invalidateQueries({queryKey:["tags",w]}))},[a,w,T]),ge=b.useMemo(()=>({enabled:E,state:c2(E,c,_,H),progress:M,lastSyncedAt:H,syncNow:le,clearOffline:de}),[E,c,_,M,H,le,de]),we=b.useMemo(()=>({db:a,blobStore:i,engine:G,isOnline:c,isDraining:m,lastSyncedAt:y,mirror:ge}),[a,i,G,c,m,y,ge]);return u.jsx(nw.Provider,{value:we,children:t})}const Vt={pinned:"pinned",archived:"archived",captureVoice:"capture",captureText:"capture",view:"view"},ik=["pinned","archived","captureVoice","captureText","view"],d2="lens:tag-roles:";function h2(t){return d2+t}function Xi(t,a){if(typeof t!="string")return a;const r=t.trim().replace(/^#/,"");return r.length>0?r:a}function Qu(t){if(!t||typeof t!="object")return{...Vt};const a=t;return{pinned:Xi(a.pinned,Vt.pinned),archived:Xi(a.archived,Vt.archived),captureVoice:Xi(a.captureVoice,Vt.captureVoice),captureText:Xi(a.captureText,Vt.captureText),view:Xi(a.view,Vt.view)}}function m2(t){try{const a=localStorage.getItem(h2(t));return a?Qu(JSON.parse(a)):{...Vt}}catch{return{...Vt}}}const Nr=".parachute/notes/settings",aw=1,la={schemaVersion:aw,tagRoles:{...Vt}};function xh(t){if(!t||typeof t!="object")return{...la,tagRoles:{...Vt}};const a=t,r=typeof a.schemaVersion=="number"?a.schemaVersion:aw,i=Qu(a.tagRoles);return{schemaVersion:r,tagRoles:i}}function vm(t){if(!t||!t.metadata||typeof t.metadata!="object")return{...la,tagRoles:{...Vt}};const a=t.metadata;return xh(a.notes??a.lens)}function ra(t,a){return{schemaVersion:a.schemaVersion??t.schemaVersion,tagRoles:a.tagRoles?Qu({...t.tagRoles,...a.tagRoles}):t.tagRoles}}function p2(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 g2="notes:settings:";function rw(t){return g2+t}function sw(t){return{settings:t??{...la,tagRoles:{...Vt}},serverSettings:t,serverUpdatedAt:null,noteExists:!1,dirtyPatch:null}}function y2(t){try{const a=localStorage.getItem(rw(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?xh(r.serverSettings):null,o=r.dirtyPatch??null,c=i??{...la,tagRoles:{...Vt}};return{settings:o?ra(c,o):xh(r.settings??c),serverSettings:i,serverUpdatedAt:typeof r.serverUpdatedAt=="string"?r.serverUpdatedAt:null,noteExists:r.noteExists===!0,dirtyPatch:o}}catch{return null}}function nu(t,a){try{localStorage.setItem(rw(t),JSON.stringify(a))}catch{}}function v2(t){if(typeof localStorage>"u"||!localStorage.getItem(`lens:tag-roles:${t}`))return null;const r={tagRoles:m2(t)};return{settings:ra(la,r),serverSettings:null,serverUpdatedAt:null,noteExists:!1,dirtyPatch:r}}function b2(t){const a=y2(t);if(a)return a;const r=v2(t);return r||sw(null)}async function Eb(t,a,r,i){if(!a.noteExists){const o=ra(a.serverSettings??la,r);try{const c=await t.createNote({path:Nr,content:"",metadata:{notes:o}},{signal:i});return{server:o,serverUpdatedAt:c.updatedAt??c.createdAt??null,noteExists:!0}}catch(c){if(c instanceof ta||x2(c))return Nd(t,r,i);throw c}}if(a.serverUpdatedAt&&a.serverSettings)try{const o=ra(a.serverSettings,r),c=await t.updateNote(Nr,{metadata:{notes:o},if_updated_at:a.serverUpdatedAt},{signal:i});return{server:o,serverUpdatedAt:c.updatedAt??a.serverUpdatedAt,noteExists:!0}}catch(o){if(o instanceof ta)return Nd(t,r,i);throw o}return Nd(t,r,i)}async function Nd(t,a,r){let i=null;try{i=await t.getNote(Nr)}catch(p){if(!(p instanceof El))throw p;i=null}if(!i){const p=ra(la,a),y=await t.createNote({path:Nr,content:"",metadata:{notes:p}},{signal:r});return{server:p,serverUpdatedAt:y.updatedAt??y.createdAt??null,noteExists:!0}}const o=vm(i),c=ra(o,a),h=i.updatedAt??i.createdAt,m=await t.updateNote(Nr,{metadata:{notes:c},if_updated_at:h},{signal:r});return{server:c,serverUpdatedAt:m.updatedAt??h??null,noteExists:!0}}function x2(t){if(!(t instanceof Error))return!1;const a=t.message.toLowerCase();return a.includes("already exists")||a.includes("duplicate")||a.includes("conflict")}function w2(t){const a=ze(),r=pt(),{db:i}=Wt(),o=b.useMemo(()=>t?b2(t):sw(null),[t]),[c,h]=b.useState(o),[m,p]=b.useState(a?"loading":"offline");b.useEffect(()=>{h(o),p(a?"loading":"offline")},[o,a]);const y=ct({queryKey:["vault-settings",t],enabled:!!t&&!!a,queryFn:async()=>{try{const v=await a.getNote(Nr);return v?{server:vm(v),serverUpdatedAt:v.updatedAt??v.createdAt??null,noteExists:!0}:{server:null,serverUpdatedAt:null,noteExists:!1}}catch(v){if(!(v instanceof El))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(c.dirtyPatch){const T=c.dirtyPatch;(async()=>{try{const E=await Eb(a,{serverSettings:v.server,serverUpdatedAt:v.serverUpdatedAt,noteExists:v.noteExists},T),_={settings:E.server,serverSettings:E.server,serverUpdatedAt:E.serverUpdatedAt,noteExists:!0,dirtyPatch:null};h(_),nu(t,_),p("synced"),r.invalidateQueries({queryKey:["vault-settings",t]})}catch{p("offline")}})();return}const w=v.server?{settings:v.server,serverSettings:v.server,serverUpdatedAt:v.serverUpdatedAt,noteExists:v.noteExists,dirtyPatch:null}:{settings:c.settings,serverSettings:null,serverUpdatedAt:null,noteExists:!1,dirtyPatch:null};h(w),nu(t,w),p("synced")},[t,a,y.data]),b.useEffect(()=>{y.isError&&p("offline")},[y.isError]);const x=b.useCallback(async v=>{if(!t)return;const w=p2(c.dirtyPatch,v),E={settings:ra(c.serverSettings??la,w),serverSettings:c.serverSettings,serverUpdatedAt:c.serverUpdatedAt,noteExists:c.noteExists,dirtyPatch:w};if(h(E),nu(t,E),!a){p("offline");return}const _=i?async()=>(await Tl(i,{kind:"update-settings",notePath:Nr,patch:w,baselineUpdatedAt:c.serverUpdatedAt},{vaultId:t}),null):null;try{const R=await Iu(M=>Eb(a,{serverSettings:c.serverSettings,serverUpdatedAt:c.serverUpdatedAt,noteExists:c.noteExists},v,M),_);if(R){const M={settings:R.server,serverSettings:R.server,serverUpdatedAt:R.serverUpdatedAt,noteExists:!0,dirtyPatch:null};h(M),nu(t,M),p("synced"),r.invalidateQueries({queryKey:["vault-settings",t]})}else p(Zs()?"offline":"queued")}catch(R){R instanceof ta?p("conflict"):p("offline")}},[t,a,i,c,r]);return{settings:c.settings,update:x,status:m}}function Xs(t){const{settings:a,update:r}=w2(t),i=b.useCallback(o=>{if(!t)return;const c=o??{...Vt};r({tagRoles:Qu(c)})},[t,r]);return{roles:a.tagRoles,setRoles:i}}const iw="auth-halted",S2=600*1e3;function E2(t){const a=2**t*1e3;return Math.min(a,S2)}async function Tl(t,a,r){const i={id:crypto.randomUUID(),vaultId:r.vaultId,mutation:a,createdAt:Date.now(),attemptCount:0,nextAttemptAt:0,status:"pending"},o=await t.add("pending",i);return{...i,seq:o}}async function lw(t,a){return a?t.getAllFromIndex("pending","by-vault",a):t.getAll("pending")}async function T2(t){const a=t.now??(()=>Date.now()),r={drained:0,stashed:0,deferred:0,authHalted:!1};for(;;){const i=await j2(t.db,t.vaultId,a());if(!i)break;try{await N2(t,i),await t.db.delete("pending",i.seq),r.drained+=1}catch(o){if(o instanceof qu){await Fs(t.db,iw,{vaultId:t.vaultId,at:a(),message:o.message}),r.authHalted=!0,await Tb(t.db,i,o,a),r.deferred+=1;break}if(o instanceof ta){await t.db.put("pending",{...i,status:"needs-human",lastError:`Conflict: current=${o.currentUpdatedAt??"?"} expected=${o.expectedUpdatedAt??"?"}`,attemptCount:i.attemptCount+1}),r.stashed+=1;continue}if(o instanceof hr){await t.db.put("pending",{...i,attemptCount:i.attemptCount+1,lastError:o.message,nextAttemptAt:a()+5e3}),r.deferred+=1;break}if(o instanceof El){await t.db.delete("pending",i.seq),r.drained+=1;continue}await Tb(t.db,i,o,a),r.deferred+=1;break}}return r}async function j2(t,a,r){let o=await t.transaction("pending","readonly").store.openCursor();for(;o;){const c=o.value;if(c.vaultId===a&&c.status==="pending"&&c.nextAttemptAt<=r)return c;o=await o.continue()}return null}async function Tb(t,a,r,i){const o=a.attemptCount+1;await t.put("pending",{...a,attemptCount:o,nextAttemptAt:i()+E2(o),lastError:r instanceof Error?r.message:String(r)})}class hr extends Error{}async function N2(t,a){var i,o,c;const r=a.mutation;switch(r.kind){case"create-note":{const h=await t.client.createNote(r.payload);await HA(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 ws(t.db,r.targetId,t.vaultId);if(!h)throw new hr(`Awaiting local id ${r.targetId}`);const m=await R2(t.client,h,r.payload,r.baselineUpdatedAt);m&&await((o=t.mirror)==null?void 0:o.upsert(t.vaultId,m));return}case"update-settings":{await C2(t.client,r.notePath,r.patch);return}case"delete-note":{const h=await ws(t.db,r.targetId,t.vaultId);if(!h)throw new hr(`Awaiting local id ${r.targetId}`);await t.client.deleteNote(h),await((c=t.mirror)==null?void 0:c.remove(t.vaultId,h));return}case"upload-attachment":{const h=await t.blobStore.get(r.blobId);if(!h)throw new hr(`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 $A(t.db,r.blobId,y.path,t.vaultId),await t.blobStore.delete(r.blobId);return}case"link-attachment":{const h=await ws(t.db,r.noteId,t.vaultId);if(!h)throw new hr(`Awaiting local id ${r.noteId}`);let m=r.pathRef;if(L0(r.pathRef)&&(m=await qA(t.db,r.pathRef,t.vaultId),!m))throw new hr(`Awaiting blob ${U0(r.pathRef)}`);await t.client.linkAttachment(h,{path:m,mimeType:r.mimeType,...r.transcribe!==void 0?{transcribe:r.transcribe}:{},...r.segment_index!==void 0?{segment_index:r.segment_index}:{}});return}case"delete-attachment":{const h=await ws(t.db,r.noteId,t.vaultId);if(!h)throw new hr(`Awaiting local id ${r.noteId}`);await t.client.deleteAttachment(h,r.attachmentId);return}}}async function A2(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 _2(t,a){await t.delete("pending",a)}const Ad=3,jb=3;async function R2(t,a,r,i){let o=i;for(let c=0;c<=jb;c++){const h=o?{...r,if_updated_at:o}:{...r};try{return await t.updateNote(a,h)}catch(m){if(m instanceof ta&&c<jb){if(m.currentUpdatedAt)o=m.currentUpdatedAt;else{const p=await t.getNote(a);if(!p)throw new El(`Note ${a} disappeared during retry`);o=p.updatedAt??p.createdAt}continue}if(m instanceof ta)return await t.updateNote(a,{...r,force:!0});throw m}}}async function C2(t,a,r){for(let i=0;i<=Ad;i++){let o=null;try{o=await t.getNote(a)}catch(p){if(!(p instanceof El))throw p}if(!o)try{await t.createNote({path:a,content:"",metadata:{notes:ra(la,r)}});return}catch(p){if(p instanceof ta&&i<Ad)continue;throw p}const c=vm(o),h=ra(c,r),m=o.updatedAt??o.createdAt;try{await t.updateNote(a,{metadata:{notes:h},if_updated_at:m});return}catch(p){if(p instanceof ta&&i<Ad)continue;if(p instanceof ta){await t.updateNote(a,{metadata:{notes:h},force:!0});return}throw p}}}async function M2(t,a){const r=await lw(t,a),i=t.transaction("pending","readwrite");for(const o of r)await i.store.delete(o.seq);return await i.done,r.length}let O2=1;const sa=Ka(t=>({toasts:[],push(a,r,i){const o=O2++;return t(c=>({toasts:[...c.toasts,{id:o,message:a,tone:r??"info",durationMs:i==null?void 0:i.durationMs}]})),o},dismiss(a){t(r=>({toasts:r.toasts.filter(i=>i.id!==a)}))},clear(){t({toasts:[]})}})),Su="lens:auth-halt:";function Nb(){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(Su)))continue;const i=localStorage.getItem(r);if(i)try{const o=JSON.parse(i);o!=null&&o.vaultId&&(t[o.vaultId]=o)}catch{}}}catch{}return t}const Ar=Ka(t=>({byVault:Nb(),markHalted(a,r){const i={vaultId:a,reason:r,at:Date.now()};try{localStorage.setItem(Su+a,JSON.stringify(i))}catch{}t(o=>({byVault:{...o.byVault,[a]:i}}))},clearHalt(a){try{localStorage.removeItem(Su+a)}catch{}t(r=>{if(!(a in r.byVault))return r;const{[a]:i,...o}=r.byVault;return{byVault:o}})},reloadFromStorage(){t({byVault:Nb()})}})),D2=Su,k2=Mx;function bm({queryKey:t,params:a,client:r,enabled:i=!0}){const o=pt(),[c,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(!k2(y))return;let x=!0;const v=pT(r,y),w=v.getList();let T=null;const E=()=>{if(!x)return;const R=v.getState();h(R.status==="live"),R.list!==w&&R.list!==T&&(T=R.list,o.setQueryData(t,R.list))},_=v.subscribe(E);return E(),()=>{x=!1,h(!1),_(),v.close()}},[r,m,p,i,o]),{isLive:c}}const mr=50,ow={search:"",tags:[],tagMatch:"any",pathPrefix:"",sort:"desc",limit:mr,offset:0};function L2(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 U2(t){return t.search.trim().length>0||t.tags.length>0||t.pathPrefix.trim().length>0}const z2=6e4;class uw extends Error{constructor(a){super(`This date window reached its ${a.toLocaleString()}-note safety ceiling. Retry after narrowing the window or filters.`),this.name="DateViewOverflowError"}}function xm(t){return t instanceof uw}function V2(t){return xm(t)?!1:z2}const B2=3,au=[1e3,2e3,4e3,8e3,16e3,3e4];function H2(t){return{vaultId:t,state:"healthy",consecutiveFailures:0,lastErrorAt:null,lastErrorReason:null,nextProbeAt:null,backoffIndex:0}}function q2(t){const a=Math.min(t,au.length-1);return au[a]??au[au.length-1]??3e4}const Mr=Ka(t=>({byVault:{},reportSignal(a,r,i){t(o=>{const c=o.byVault[a]??H2(a);if(r==="healthy"){if(!(a in o.byVault))return o;const{[a]:v,...w}=o.byVault;return{byVault:w}}const h=c.consecutiveFailures+1,m=c.backoffIndex+1,p=h>=B2?"down":"retrying",y=Date.now(),x={vaultId:a,state:p,consecutiveFailures:h,lastErrorAt:y,lastErrorReason:i??null,nextProbeAt:y+q2(m),backoffIndex:m};return{byVault:{...o.byVault,[a]:x}}})},resetToHealthy(a){t(r=>{if(!(a in r.byVault))return r;const{[a]:i,...o}=r.byVault;return{byVault:o}})}})),$2="Parachute Notes";async function cw(t,a=fetch.bind(globalThis)){return $E(t,a)}async function Q2(t,a,r=fetch.bind(globalThis)){return QE(t,{clientName:$2,redirectUri:a},r)}const I2="/oauth/callback",K2="vault:read vault:write";function G2(){return yl()}function Y2(t=window.location.origin){return`${t.replace(/\/$/,"")}${G2()}${I2}`}function P2(t){let a;try{a=new URL(Vh(t))}catch{return}const r=a.pathname.match(/^\/vault\/([^/]+)$/);if(r!=null&&r[1])try{return decodeURIComponent(r[1])}catch{return}}async function wm(t,a=K2,r=fetch.bind(globalThis),i={}){const o=Vh(t),c=Y2(),h=await cw(o,r);let m=CN(h.issuer,c);m||(m=(await Q2(h.registration_endpoint,c,r)).client_id,MN(h.issuer,c,m));const p=YE(),y=await PE(p),x=FE(),v={issuerUrl:o,issuer:h.issuer,tokenEndpoint:h.token_endpoint,clientId:m,codeVerifier:p,state:x,redirectUri:c,scope:a,startedAt:new Date().toISOString(),...i.priorHaltedVaultId?{priorHaltedVaultId:i.priorHaltedVaultId}:{},...i.redirect?{redirect:i.redirect}:{}};RN(v);const w=new URL(h.authorization_endpoint);if(w.searchParams.set("response_type","code"),w.searchParams.set("client_id",m),w.searchParams.set("redirect_uri",c),w.searchParams.set("code_challenge",y),w.searchParams.set("code_challenge_method","S256"),w.searchParams.set("state",x),w.searchParams.set("scope",a),i.params)for(const[T,E]of Object.entries(i.params))w.searchParams.has(T)||w.searchParams.set(T,E);if(!w.searchParams.has("vault")){const T=P2(o);T&&w.searchParams.set("vault",T)}return{authorizeUrl:w.toString(),pending:v}}function F2(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 X2(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=F2(r.approve_url);return i?{approveUrl:i}:null}async function lk(t,a,r=fetch.bind(globalThis)){const i=_N();if(!i)throw new Error("No pending OAuth flow. Start the connect flow from the vault page.");if(i.state!==a)throw Wo(),new Error("OAuth state mismatch. The flow was likely interrupted; please try again.");const o=new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:i.codeVerifier,client_id:i.clientId,redirect_uri:i.redirectUri}),c=await r(i.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:o.toString()});if(!c.ok){const m=await c.text();Wo();const p=X2(m);throw p?new ZE(p.approveUrl):new Error(`Token exchange failed (${c.status}): ${m}`)}const h=await c.json();if(!h.access_token)throw Wo(),new Error("Token response missing access_token");return Wo(),{pending:i,token:h}}async function Z2(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 c=await i.text();throw new Ax(i.status,c)}const o=await i.json();if(!o.access_token)throw new Error("Refresh response missing access_token");return o}const _d=new Map;async function J2(t){const a=_d.get(t);if(a)return a;const r=W2(t).finally(()=>{_d.delete(t)});return _d.set(t,r),r}async function W2(t){const a=ne.getState().vaults[t];if(a){const{isHostedVaultRecord:i,remintHostedVault:o}=await Ke(async()=>{const{isHostedVaultRecord:c,remintHostedVault:h}=await Promise.resolve().then(()=>FN);return{isHostedVaultRecord:c,remintHostedVault:h}},[]);if(i(a.clientId)){try{await o(a.name);const c=Vs(t);if(c!=null&&c.accessToken)return Ar.getState().clearHalt(t),c.accessToken}catch{}return null}}const r=Vs(t);if(!(r!=null&&r.refreshToken)||!(a!=null&&a.tokenEndpoint)||!a.clientId)return null;try{const i=await Z2({tokenEndpoint:a.tokenEndpoint,clientId:a.clientId,refreshToken:r.refreshToken}),o=XE(i);return!o.refreshToken&&r.refreshToken&&(o.refreshToken=r.refreshToken),o0(t,o),Ar.getState().clearHalt(t),o.accessToken}catch(i){if(i instanceof Ax&&i.status>=400&&i.status<500){const o=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.`;Ar.getState().markHalted(t,o)}return null}}const Eu=new Map;function eR(t,a){return`${t}\0${a}`}ne.subscribe(t=>{for(const a of[...Eu.keys()]){const r=a.indexOf("\0"),i=a.slice(0,r),o=a.slice(r+1),c=t.vaults[i];(!c||c.url!==o)&&Eu.delete(a)}});function ze(){const t=ne(r=>r.activeVaultId),a=ne(r=>{var o;const i=r.activeVaultId;return i?((o=r.vaults[i])==null?void 0:o.url)??null:null});return b.useMemo(()=>{if(!t||!a)return null;const r=Vs(t);if(!r)return null;const i=eR(t,a),o=Eu.get(i);if(o)return o.setAccessToken(r.accessToken),o;const c=new S_({vaultUrl:a,accessToken:r.accessToken,onAuthError:()=>J2(t),onAuthRevoked:h=>Ar.getState().markHalted(t,`Vault rejected the current session (${h}).`),onReachability:(h,m)=>Mr.getState().reportSignal(t,h,m)});return Eu.set(i,c),c},[t,a])}async function Sm(t,a,r,i){const o=()=>t&&a?I0(t,a,r):Promise.resolve(null);if(t&&a&&Zs()){const c=await o();if(c)return c}try{return await i()}catch(c){if(c instanceof ll){const h=await o();if(h)return h}throw c}}async function tR(t,a,r,i){const o=()=>t&&a&&r?Q0(t,a,r):Promise.resolve(void 0);if(t&&a&&r&&Zs()){const c=await o();if(c)return c}try{return await i()}catch(c){if(c instanceof ll){const h=await o();if(h)return h}throw c}}async function nR(t,a,r){const i=()=>t&&a?H0(t,a):Promise.resolve(void 0);if(t&&a&&Zs()){const o=await i();if(o)return o}try{return await r()}catch(o){if(o instanceof ll){const c=await i();if(c)return c}throw o}}function Em(t,a,r,i){const[o,c]=b.useState(void 0),h=r.toString();return b.useEffect(()=>{if(!i||!t||!a){c(void 0);return}let m=!0;return I0(t,a,new URLSearchParams(h)).then(p=>{m&&p&&c(p)}).catch(()=>{}),()=>{m=!1}},[i,t,a,h]),o}function aR(t,a,r,i){const[o,c]=b.useState(void 0);return b.useEffect(()=>{if(c(void 0),!i||!t||!a||!r)return;let h=!0;return Q0(t,a,r).then(m=>{h&&m&&c(m)}).catch(()=>{}),()=>{h=!1}},[i,t,a,r]),o}function rR(t,a,r){const[i,o]=b.useState(void 0);return b.useEffect(()=>{if(!r||!t||!a){o(void 0);return}let c=!0;return H0(t,a).then(h=>{c&&h&&o(h)}).catch(()=>{}),()=>{c=!1}},[r,t,a]),i}function fw(){const t=ze(),a=ne(r=>r.activeVaultId);return ct({queryKey:["vaultInfo",a],enabled:!!t,queryFn:()=>t.vaultInfo(!0),staleTime:3e4})}function ok(){return dw().capability}function dw(){var m,p,y;const t=ze(),a=ne(x=>x.activeVaultId),r=fw(),i=!!t&&r.isSuccess&&((m=r.data)==null?void 0:m.transcription)===void 0,o=ct({queryKey:["vaultLanding",a],enabled:i,queryFn:()=>t.vaultLanding(),staleTime:5*6e4,retry:!1}),c=r.isSuccess||r.isError,h=!i||o.isSuccess||o.isError;return{capability:((p=r.data)==null?void 0:p.transcription)??((y=o.data)==null?void 0:y.transcription),settled:c&&h}}function hw(t,a){const r=ze(),i=ne(v=>v.activeVaultId),{db:o}=Wt(),c=ia(),h=(a==null?void 0:a.live)??!0,m=b.useMemo(()=>["notes",i,t],[i,t]),p=b.useMemo(()=>{const v=L2(t);return v.set("include_content","false"),v},[t]),{isLive:y}=bm({queryKey:m,params:p,client:r,enabled:h}),x=Em(o,i,p,c);return ct({queryKey:m,enabled:!!r,queryFn:()=>c?Sm(o,i,p,()=>r.queryNotes(p)):r.queryNotes(p),staleTime:y?Number.POSITIVE_INFINITY:1e4,refetchInterval:y?!1:3e4,refetchOnWindowFocus:!y,placeholderData:c?v=>v??x:x0,networkMode:c?"always":"online"})}const Tm=5e3;function sR(t){const a=ze(),r=ne(i=>i.activeVaultId);return ct({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(Tm)),a.queryNotes(i)},staleTime:6e4})}const iR=5e3;function lR({field:t,from:a,to:r,excludeTag:i,limit:o,enabled:c=!0}){const h=ze(),m=ne(E=>E.activeVaultId),{db:p}=Wt(),y=ia(),x=b.useMemo(()=>{const E=new URLSearchParams;return E.set("sort","desc"),E.set(`meta[${t}][gte]`,a),r&&E.set(`meta[${t}][lt]`,r),i&&E.set("exclude_tag",i),E.set("limit",String(o)),E.set("include_content","false"),E},[i,t,a,o,r]),v=x.toString(),w=b.useMemo(()=>["notesForDateViews",m,v],[m,v]),T=Em(p,m,x,y);return ct({queryKey:w,enabled:!!h&&c,queryFn:async()=>{const E=await(y?Sm(p,m,x,()=>h.queryNotes(x)):h.queryNotes(x));if(E.length>=o)throw new uw(o);return E},staleTime:6e4,refetchInterval:E=>V2(E.state.error),refetchOnWindowFocus:E=>!xm(E.state.error),placeholderData:y?E=>E??T:void 0,networkMode:y?"always":"online"})}function oR(t){const a=ze(),r=ne(m=>m.activeVaultId),{db:i}=Wt(),o=ia(),c=b.useMemo(()=>{const m=new URLSearchParams;return m.set("sort","desc"),m.set("limit",String(Tm)),m},[]),h=Em(i,r,c,o&&t);return ct({queryKey:["notesForPathTree",r],enabled:!!a&&t,queryFn:()=>o?Sm(i,r,c,()=>a.queryNotes(c)):a.queryNotes(c),staleTime:6e4,placeholderData:o?m=>m??h:void 0,networkMode:o?"always":"online"})}function uk(){const t=ze(),a=ne(r=>r.activeVaultId);return ct({queryKey:["allNotesWithLinks",a],enabled:!!t,queryFn:()=>{const r=new URLSearchParams;return r.set("include_links","true"),r.set("sort","desc"),r.set("limit",String(Tm)),t.queryNotes(r)},staleTime:6e4})}function uR(){const t=ze(),a=ne(c=>c.activeVaultId),{db:r}=Wt(),i=ia(),o=rR(r,a,i);return ct({queryKey:["tags",a],enabled:!!t,queryFn:()=>i?nR(r,a,()=>t.listTags()):t.listTags(),staleTime:6e4,placeholderData:i?c=>c??o:void 0,networkMode:i?"always":"online"})}function cR(){const t=ze(),a=ne(r=>r.activeVaultId);return ct({queryKey:["tags",a,"with-schema"],enabled:!!t,queryFn:()=>t.listTags({includeSchema:!0}),staleTime:6e4})}function ck(t){const a=ze(),r=ne(i=>i.activeVaultId);return ct({queryKey:["tag",r,t],enabled:!!a&&!!t,queryFn:()=>a.getTag(t),staleTime:3e4})}function fk(){const t=ze(),a=ne(i=>i.activeVaultId),r=pt();return Rn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.updateTag(i.name,i.payload)},onSuccess:(i,o)=>{r.setQueryData(["tag",a,o.name],i),r.invalidateQueries({queryKey:["tags",a]})}})}function fR(t,a){return t&&Hs(t)&&!(a&&!Hs(a.id))?2e3:a&&N_(a)?4e3:!1}function dR(t){const a=ze(),r=ne(m=>m.activeVaultId),{db:i}=Wt(),o=pt(),c=ia(),h=aR(i,r,t,c);return ct({queryKey:["note",r,t],enabled:!!a&&!!t,queryFn:()=>{const m=async()=>{if(t&&Hs(t)){const p=i&&r?await ws(i,t,r):null;if(!p){const y=o.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 c?tR(i,r,t,m):m()},refetchInterval:m=>fR(t,m.state.data),staleTime:1e4,placeholderData:c?h:void 0,networkMode:c?"always":"online"})}const hR=8e3;function Zs(){return typeof navigator<"u"&&navigator.onLine===!1}async function Iu(t,a){if(a&&Zs())return a();const r=new AbortController,i=setTimeout(()=>r.abort(new Error("offline-timeout")),hR);try{return await t(r.signal)}catch(o){if(a)return a();throw o}finally{clearTimeout(i)}}function mR(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 pR(t,a,r){const i=BA();return await Tl(t,{kind:"create-note",localId:i,payload:r},{vaultId:a}),mR(r,i)}async function gR(t,a,r,i,o){const c=o==null?void 0:o.updatedAt;return await Tl(t,{kind:"update-note",targetId:r,payload:i,...c&&{baselineUpdatedAt:c}},{vaultId:a}),{...o??{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 yR(t){const a=ze(),r=ne(c=>c.activeVaultId),{db:i}=Wt(),o=pt();return Rn({mutationFn:async c=>{if(!t)throw new Error("No note id");return Iu(m=>{if(!a)throw new Error("No active vault");return a.updateNote(t,c,{signal:m})},i&&r?()=>{const m=o.getQueryData(["note",r,t]);return gR(i,r,t,c,m)}:null)},onSuccess:c=>{o.setQueryData(["note",r,t],c),o.setQueriesData({queryKey:["viewList",r]},h=>h==null?void 0:h.map(m=>m.id===t?c:m)),o.invalidateQueries({queryKey:["viewList",r]}),o.invalidateQueries({queryKey:["notes",r]}),o.invalidateQueries({queryKey:["notesForDateViews",r]}),o.invalidateQueries({queryKey:["tags",r]}),c!=null&&c.id&&c.id!==t&&o.setQueryData(["note",r,c.id],c),i&&r&&c&&pm(i,r,c)}})}function mw(){const t=ze(),a=ne(o=>o.activeVaultId),{db:r}=Wt(),i=pt();return Rn({mutationFn:async o=>Iu(h=>{if(!t)throw new Error("No active vault");return t.createNote(o,{signal:h})},r&&a?()=>pR(r,a,o):null),onSuccess:o=>{i.setQueryData(["note",a,o.id],o),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&&pm(r,a,o)}})}function dk(){const t=ze();return Rn({mutationFn:async a=>{if(!t)throw new Error("No active vault");return t.uploadStorageFile(a.file,{onProgress:a.onProgress,signal:a.signal})}})}function hk(){const t=ze(),a=ne(i=>i.activeVaultId),r=pt();return Rn({mutationFn:async i=>{if(!t)throw new Error("No active vault");return t.linkAttachment(i.noteId,{path:i.path,mimeType:i.mimeType})},onSuccess:(i,o)=>{r.invalidateQueries({queryKey:["note",a,o.noteId]})}})}function mk(){const t=ze(),a=ne(o=>o.activeVaultId),r=pt(),i=sa(o=>o.push);return Rn({mutationFn:async o=>{if(!t)throw new Error("No active vault");await t.retryTranscription(o.serverId)},onMutate:async({cacheId:o})=>{const c=["note",a,o];await r.cancelQueries({queryKey:c});const h=r.getQueryData(c);return h&&r.setQueryData(c,A_(h)),{prev:h,key:c}},onError:(o,c,h)=>{h!=null&&h.prev&&h.key&&r.setQueryData(h.key,h.prev),i("Couldn't retry transcription right now.","error")},onSettled:(o,c,{cacheId:h})=>{r.invalidateQueries({queryKey:["note",a,h]})}})}function pk(){const t=ze(),a=ne(o=>o.activeVaultId),{db:r}=Wt(),i=pt();return Rn({mutationFn:async o=>{if(Zs()&&r&&a)return await Tl(r,{kind:"delete-attachment",noteId:o.noteId,attachmentId:o.attachmentId},{vaultId:a}),o;if(!t)throw new Error("No active vault");return await t.deleteAttachment(o.noteId,o.attachmentId),o},onSuccess:o=>{i.invalidateQueries({queryKey:["note",a,o.noteId]})}})}function gk(){const t=ze(),a=ne(i=>i.activeVaultId),r=pt();return Rn({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 yk(){const t=ze(),a=ne(i=>i.activeVaultId),r=pt();return Rn({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 vk(){const t=ze(),a=ne(o=>o.activeVaultId),{db:r}=Wt(),i=pt();return Rn({mutationFn:async o=>Iu(async h=>{if(!t)throw new Error("No active vault");return await t.deleteNote(o,{signal:h}),o},r&&a?async()=>(await Tl(r,{kind:"delete-note",targetId:o},{vaultId:a}),o):null),onSuccess:o=>{i.removeQueries({queryKey:["note",a,o]}),i.invalidateQueries({queryKey:["notes",a]}),i.invalidateQueries({queryKey:["notesForDateViews",a]}),i.invalidateQueries({queryKey:["tags",a]}),i.invalidateQueries({queryKey:["vaultInfo",a]}),i.invalidateQueries({queryKey:["hasUserAuthoredNote",a]}),r&&a&&$0(r,a,o)}})}function vR(){b.useEffect(()=>{if(typeof window>"u")return;function t(a){if(a.key===null){ne.setState({vaults:Fd(),activeVaultId:Xd()}),Ar.getState().reloadFromStorage();return}if(a.key===yu){ne.setState({activeVaultId:Xd()});return}if(a.key===Xh){ne.setState({vaults:Fd()});return}if(a.key.startsWith(D2)){Ar.getState().reloadFromStorage();return}}return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[])}const bk={search:"",tags:[]};function bR(t){const a=new Map;for(const c of t)a.set(c.id,c);const r=new Map,i=new Map;for(const c of t)for(const h of c.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(c=>{var m;const h=c.tags??[];return{id:c.id,path:c.path,title:xR(c),tags:h,topTag:h[0],degree:i.get(c.id)??0,summary:typeof((m=c.metadata)==null?void 0:m.summary)=="string"?c.metadata.summary:void 0}}),edges:[...r.values()]}}function xR(t){return t.path?(t.path.split("/").pop()??t.path).replace(/\.md$/i,""):t.id}function xk(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(o=>t.tags.includes(o)))}function wk(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 Sk(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 wR(t){try{return new URL(t.issuer).origin}catch{return null}}function SR(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 ER(t,a=fetch.bind(globalThis),r){const i=`${t.replace(/\/$/,"")}/.well-known/parachute.json`;let o;try{o=await a(i,{headers:{Accept:"application/json"},signal:r})}catch{return null}if(!o.ok)return null;let c;try{c=await o.json()}catch{return null}if(typeof c!="object"||c===null)return null;const h=c.vaults;return Array.isArray(h)?h.filter(SR):null}const TR=15,jR=2;function NR(t){if(!t||t.length===0)return 0;const a=bR([...t]);let r=0;for(const i of a.nodes)i.degree>0&&r++;return r}function AR(t,a){return t>=jR||a>=TR}function pw(){const t=ne(o=>Object.keys(o.vaults).length),a=ne(o=>o.activeVaultId),r=ct({queryKey:["allNotesWithLinks",a],queryFn:()=>{throw new Error("useMapEarned reads the query cache only")},enabled:!1}),i=b.useMemo(()=>NR(r.data),[r.data]);return AR(t,i)}const _R="lens:pinned-tags:";function gw(t){return _R+t}function wh(t){return t.trim().replace(/^#/,"")}function jm(t){const a=new Set,r=[];for(const i of t){const o=wh(i);if(!o)continue;const c=o.toLowerCase();a.has(c)||(a.add(c),r.push(o))}return r}function Ab(t){try{const a=localStorage.getItem(gw(t));if(!a)return[];const r=JSON.parse(a);return Array.isArray(r)?jm(r.filter(i=>typeof i=="string")):[]}catch{return[]}}function _b(t,a){try{localStorage.setItem(gw(t),JSON.stringify(jm(a)))}catch{}}function RR(t){const[a,r]=b.useState(()=>t?Ab(t):[]);b.useEffect(()=>{r(t?Ab(t):[])},[t]);const i=b.useCallback(h=>{if(!t)return;const m=jm(h);_b(t,m),r(m)},[t]),o=b.useCallback(h=>{if(!t)return;const m=wh(h);m&&r(p=>{const x=p.some(v=>v.toLowerCase()===m.toLowerCase())?p.filter(v=>v.toLowerCase()!==m.toLowerCase()):[...p,m];return _b(t,x),x})},[t]),c=b.useCallback(h=>{const m=wh(h).toLowerCase();return a.some(p=>p.toLowerCase()===m)},[a]);return{pinnedTags:a,setPinnedTags:i,togglePin:o,isPinned:c}}const yw=2500,CR="http://127.0.0.1:1939";async function Rd(t,a=yw,r=fetch.bind(globalThis)){return MR(t,a,r)}async function MR(t,a,r){const i=new AbortController,o=setTimeout(()=>i.abort(),a),c=(h,m)=>r(h,{...m??{},signal:i.signal});try{return await cw(t,c),t}catch{return null}finally{clearTimeout(o)}}async function vw(t,a=yw,r=fetch.bind(globalThis),i=KE()){if(i){const c=await Rd(i,a,r);if(c)return c}const o=await Rd(t,a,r);if(o)return o;if(OR(t)){const c=await Rd(CR,a,r);if(c)return c}return null}function OR(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 Ek(){const t=ne(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}),vw(window.location.origin).then(o=>{i||r(o?{status:"found",origin:o}:{status:"not-found",origin:null})}),()=>{i=!0}},[t]),a}function DR(t,a){const r=Mr(o=>t?o.byVault[t]:void 0),i=pt();b.useEffect(()=>{if(!t||!a||!r||r.state==="healthy"||r.nextProbeAt===null)return;const o=Date.now(),c=Math.max(0,r.nextProbeAt-o);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(()=>{})},c);return()=>{h=!0,clearTimeout(m)}},[t,a,r,i])}function tl(t){if(t.name)return t.name;try{return new URL(t.url).host}catch{return t.url}}function Nm(t){sa.getState().push(`Now in ${t}`,"success")}function kR(t,a={}){const r=ne.getState(),i=r.vaults[t];if(!i)return!1;const o=r.activeVaultId===t;return r.setActiveVault(t),(a.toast??!0)&&!o&&Nm(tl(i)),!0}const Cd=25,Rb=40;async function LR(t){for(let a=0;a<Rb;a++){const r=a*Cd,i=new URLSearchParams;i.set("exclude_tag",M0),i.set("sort","desc"),i.set("limit",String(Cd)),i.set("include_content","false"),r>0&&i.set("offset",String(r));const o=await t.queryNotes(i);if(O0(o))return!0;if(o.length<Cd)return!1}throw new Error(`first-note probe: ${Rb} full pages without ending the set — offset paging appears broken`)}function UR(){const t=ze(),a=ne(r=>r.activeVaultId);return ct({queryKey:["hasUserAuthoredNote",a],enabled:!!t,queryFn:()=>LR(t),staleTime:6e4})}const zR=["list","board","calendar","gallery","table"];function VR(t){return typeof t=="string"&&zR.includes(t)}const Md={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 BR(t){return t.path?$u(t.path):t.id}function Am(t){const a=t.metadata??{},r=VR(a.kind)?a.kind:"list",i=[];let o={};if(typeof a.query=="string"&&a.query.trim().length>0)try{const c=JSON.parse(a.query);c&&typeof c=="object"&&!Array.isArray(c)?o=c:(o=null,i.push(Md))}catch{o=null,i.push(Md)}else a.query!==void 0&&a.query!==null&&typeof a.query!="string"&&(o=null,i.push(Md));return{noteId:t.id,path:t.path,title:BR(t),kind:r,query:o,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:HR(a.fields),problems:i}}function HR(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 qR(t,a){return(t.tags??[]).includes(a)}function $R(t){const a=t.metadata;return(a==null?void 0:a.kind)==="saved-view"}const QR="Views/All notes",IR="Views/Recent",bw="Views/Pinned",xw="Views/Archive",ww=[QR,IR,bw,xw];function KR(t){const a=t==null?void 0:t.toLowerCase();return a!==void 0&&ww.some(r=>r.toLowerCase()===a)}const GR="Views/";function _m(t){const a=t.trim().replace(/[/\\]/g,"-");return`${GR}${a||"Untitled view"}`}function YR(t,a,r){const i=_m(t).toLowerCase(),o=r==null?void 0:r.toLowerCase();return[...ww,...a].some(c=>{const h=c.toLowerCase();return h===i&&h!==o})}const PR={pinned:bw,archived:xw},FR={pinned:"Pinned",archived:"Archive"};function XR(t){return PR[t]}function ZR(t,a){const r=t==="pinned"?a.pinned:a.archived;return{noteId:`builtin:${t}`,title:FR[t],kind:"list",query:{tag:r},problems:[]}}function JR(t,a,r){if(a&&qR(a,r.view)){const i=Am(a);if(i.query!==null)return{def:i,isPackNote:!0}}return{def:ZR(t,r),isPackNote:!1}}function WR(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,"/"),o=i+"=".repeat((4-i.length%4)%4),c=atob(o),h=JSON.parse(c),m=h==null?void 0:h.sub;return typeof m=="string"?m:null}catch{return null}}function Cb(t){if(typeof t=="string"||Array.isArray(t)&&t.every(a=>typeof a=="string"))return t}function eC(t){const a=[],r={};let i;for(const[c,h]of Object.entries(t))switch(c){case"tag":r.tag=Cb(h);break;case"exclude_tags":r.excludeTag=Cb(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 "${c}", which this app can't run yet; results may be broader than intended.`})}let o;try{o=Kd(r)}catch(c){const h=c instanceof Error?c.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;o=Kd(p)}return i&&o.set("search",i),{params:o,problems:a}}function Tk(t){return t.addTags.length>0||t.removeExcludes.length>0||!!t.search||!!t.sort}function jk(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 Nk(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 ol(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(a=>typeof a=="string"):[]}function tC(t,a){if(t===null)return null;const r={...t};if(a.addTags.length>0&&(r.tag=[...ol(t.tag),...a.addTags],r.tag_match="all"),a.removeExcludes.length>0){const i=ol(t.exclude_tags).filter(o=>!a.removeExcludes.includes(o));r.exclude_tags=i}return a.search&&(r.search=a.search),a.sort&&(r.sort=a.sort),r}function Sw(t){return t?ol(t.tag):[]}function nC(t){return Sw(t)[0]}function Ak(t){if(!t)return[];const a=[];for(const r of ol(t.tag))a.push({kind:"tag",value:r,label:`#${r}`});for(const r of ol(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 _k=dR;function Ew(t,a=!0){const r=ze(),i=ne(m=>m.activeVaultId),o=b.useMemo(()=>{const m=new URLSearchParams;return m.set("tag",t),m.set("sort","asc"),m},[t]),c=b.useMemo(()=>["viewList",i,t],[i,t]),{isLive:h}=bm({queryKey:c,params:o,client:r,enabled:a&&!!t});return ct({queryKey:c,enabled:a&&!!r&&!!t,queryFn:()=>r.queryNotes(o),staleTime:h?Number.POSITIVE_INFINITY:3e4,refetchInterval:h?!1:3e4,refetchOnWindowFocus:!h})}function aC(t,a){const r=ze(),i=ne(h=>h.activeVaultId),o=t?XR(t):null,c=ct({queryKey:["defaultViewNote",i,o],queryFn:async()=>(await r.queryNotes({path:o}))[0]??null,enabled:!!r&&!!o,staleTime:3e4,refetchOnWindowFocus:!1});return b.useMemo(()=>t?JR(t,c.data??null,a):{def:null,isPackNote:!1},[t,c.data,a])}function Rk(t,a,r){const i=ze(),o=ne(v=>v.activeVaultId),c=(r==null?void 0:r.live)??!0,h=b.useMemo(()=>t?tC(t.query,a):null,[t,a]),m=b.useMemo(()=>h?eC(h):null,[h]),p=b.useMemo(()=>["viewResults",o,t==null?void 0:t.noteId,(m==null?void 0:m.params.toString())??null],[o,t==null?void 0:t.noteId,m]),{isLive:y}=bm({queryKey:p,params:(m==null?void 0:m.params)??new URLSearchParams,client:m?i:null,enabled:!!m&&c}),x=ct({queryKey:p,enabled:!!i&&!!m,queryFn:()=>i.queryNotes(m.params),staleTime:y?Number.POSITIVE_INFINITY:1e4,refetchInterval:y?!1:3e4,refetchOnWindowFocus:!y,placeholderData:x0});return{data:x.data,isPending:x.isPending,isError:x.isError,error:x.error,refetch:()=>void x.refetch(),problems:(m==null?void 0:m.problems)??[],queryKey:p}}function Ck(){const t=ne(a=>a.activeVaultId);return b.useMemo(()=>{if(!t)return null;const a=Vs(t);return a!=null&&a.accessToken?WR(a.accessToken):null},[t])}function Mk(t,a){return a&&(t!=null&&t.createdBy)&&t.createdBy===a?"update":"fork"}function Tw(t){return t.pathname==="/"||t.pathname==="/today"||t.pathname.startsWith("/n/")}function Rm(t){return new URLSearchParams(t.search).get("view")}function rC(t){if(t.pathname!=="/notes")return!1;const a=Rm(t);return a!=="pinned"&&a!=="archived"}function sC(t){return t.pathname==="/notes"&&Rm(t)==="pinned"}function iC(t){return t.pathname==="/notes"&&Rm(t)==="archived"}function lC(t){return Tw(t)||t.pathname==="/notes"}const jw="/",oC="/notes",Tu="/map";function mn(t){return a=>a.pathname===t}const uC=["/welcome","/check-email","/add","/add-vault","/oauth/callback"];function Nw(t){return uC.some(a=>t===a||t.startsWith(`${a}/`))}const cC={id:"recent",label:"Recent",to:jw,icon:u.jsx(nN,{}),match:Tw},fC={id:"notes",label:"All notes",to:oC,icon:u.jsx(Ph,{}),match:rC},dC={id:"pinned",label:"Pinned",to:"/notes?view=pinned",icon:u.jsx(fN,{}),match:sC},hC={id:"archive",label:"Archive",to:"/notes?view=archived",icon:u.jsx(dN,{}),match:iC},Mb="/views/new",mC={id:"new-view",label:"New view",to:Mb,icon:u.jsx(Fh,{}),match:mn(Mb)},pC={id:"calendar",label:"Calendar",to:"/calendar",icon:u.jsx(e0,{}),match:mn("/calendar")},gC={id:"tags",label:"Tags",to:"/tags",icon:u.jsx(aN,{}),match:mn("/tags")},yC={id:"activity",label:"Activity",to:"/activity",icon:u.jsx(iN,{}),match:mn("/activity")},vC={id:"map",label:"Map",to:Tu,icon:u.jsx(r0,{}),match:mn(Tu)},bC={id:"vaults",label:"Vaults",to:"/vaults",icon:u.jsx(lN,{}),match:mn("/vaults")},xC={id:"connect",label:"Connect AI",to:"/connect",icon:u.jsx(t0,{}),match:mn("/connect")},wC={id:"import",label:"Import notes",to:"/import",icon:u.jsx(n0,{}),match:mn("/import")},SC={id:"export",label:"Export notes",to:"/export",icon:u.jsx(oN,{}),match:mn("/export")},EC={id:"settings",label:"Settings",to:"/settings",icon:u.jsx(sN,{}),match:mn("/settings")},TC={write:{label:"Write a note",to:"/new",icon:u.jsx(jC,{}),match:()=>!1}};function jC(){return u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 place-items-center rounded-full border border-border text-[10px]",children:"✦"})}function NC({daysLeft:t}){return u.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 AC(t){const a=[cC,fC,dC,hC],r=[pC,gC,yC];t.mapEarned&&r.push(vC);const i={id:"account",label:"Account & plan",to:"/account",icon:u.jsx(rN,{}),match:mn("/account"),badge:t.trialDaysLeft!==null?u.jsx(NC,{daysLeft:t.trialDaysLeft}):void 0},o=[{id:"notes",label:"Your notes",items:a},{id:"views",label:"Views",items:[...t.viewItems,mC]},{id:"explore",label:"Explore",items:r},{id:"parachute",label:"Your parachute",items:[i,bC,xC,wC,SC]}];return t.setup&&t.setup.steps.length>0&&o.push({id:"setup",label:"Set up",sublabel:`${t.setup.done} of ${t.setup.total}`,items:t.setup.steps.map(c=>({id:`setup-${c}`,...TC[c]}))}),o.push({id:"foot",items:[EC]}),o}function _C(){var T;const t=ne(E=>E.getActiveVault()),a=pw(),r=UR(),{roles:i}=Xs((t==null?void 0:t.id)??null),o=Ew(i.view),c=t!==null&&Gs(t.clientId),h=lm({enabled:c}),m=((T=c?im(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(o.data)?o.data.filter(E=>!KR(E.path)&&!$R(E)).map(E=>{const _=Am(E),R=`/views/${encodeURIComponent(E.id)}`;return{id:`view-${E.id}`,label:_.title,to:R,icon:u.jsx(EN,{kind:_.kind,hueTag:nC(_.query)}),match:mn(R)}}).sort((E,_)=>E.label.localeCompare(_.label)):[],[o.data]);if(!t)return[];const x=D0({hasUserNote:r.data===!0}),v=x.filter(E=>!E.done),w=r.data===void 0||v.length===0?null:{steps:v.map(E=>E.id),done:x.length-v.length,total:x.length};return AC({mapEarned:a,trialDaysLeft:p,setup:w,viewItems:y})}const Aw=b.createContext(null);function RC({children:t}){const a=_C();return u.jsx(Aw.Provider,{value:a,children:t})}function Ku(){const t=b.useContext(Aw);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 CC=Ka(t=>({shown:!1,setShown(a){t({shown:a})}}));function MC(){const t=ne(o=>o.activeVaultId!==null),a=pw(),r=CC(o=>o.shown),{pathname:i}=Ie();return!t||a||i===Tu||r?null:u.jsx(Ne,{to:Tu,"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 md:right-6 md:bottom-6",children:u.jsx(r0,{width:22,height:22})})}const Es=Ka(t=>({open:!1,setOpen(a){t({open:a})},toggle(){t(a=>({open:!a.open}))}}));function OC(){const t=ne(o=>o.activeVaultId!==null),a=Es(o=>o.setOpen),r=Ie();if(!t)return null;const i=lC(r);return u.jsx("nav",{"aria-label":"Primary",className:"fixed inset-x-0 bottom-0 z-20 border-t border-border bg-bg/95 backdrop-blur md:hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:u.jsxs("ul",{className:"mx-auto flex max-w-(--w-page) items-stretch justify-around px-2",children:[u.jsx(DC,{to:jw,label:"Notes",active:i,icon:u.jsx(Ph,{})}),u.jsx(LC,{}),u.jsx(kC,{label:"Search",icon:u.jsx(rl,{}),onClick:()=>a(!0)})]})})}function DC({to:t,label:a,icon:r,active:i}){return u.jsx("li",{className:"flex-1",children:u.jsxs(Ne,{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:[u.jsx("span",{"aria-hidden":"true",children:r}),u.jsx("span",{children:a})]})})}function kC({label:t,icon:a,onClick:r}){return u.jsx("li",{className:"flex-1",children:u.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:[u.jsx("span",{"aria-hidden":"true",children:a}),u.jsx("span",{children:t})]})})}function LC(){return u.jsx("li",{className:"flex flex-1 items-center justify-center",children:u.jsx(Ne,{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:u.jsx(Fh,{width:26,height:26,strokeWidth:2})})})}function _w({title:t,message:a,retry:r,retryLabel:i="Try again",action:o,className:c=""}){return u.jsxs("div",{className:`rounded-lg border border-(--color-danger-border) bg-(--color-danger-soft) p-6 ${c}`.trim(),children:[u.jsx("p",{className:"mb-2 font-medium text-(--color-danger)",children:t}),a?u.jsx("p",{className:"mb-4 text-sm text-fg-muted",children:a}):null,r||o?u.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r?u.jsx("button",{type:"button",onClick:r,className:"btn btn-secondary btn-touch",children:i}):null,o]}):null]})}class Rw 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 UC({error:t}){return u.jsx("div",{className:"page",children:u.jsx(_w,{title:"Something went wrong",message:u.jsxs(u.Fragment,{children:["This page hit an unexpected error. You can head back to your notes.",u.jsxs("details",{className:"mt-3",children:[u.jsx("summary",{className:"cursor-pointer text-xs text-fg-dim hover:text-fg-muted",children:"Technical detail"}),u.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-xs text-fg-dim",children:t.message})]})]}),action:u.jsx(Ne,{to:"/notes",className:"btn btn-secondary btn-touch",children:"Back to notes"})})})}function Le({children:t,resetKey:a}){const r=Ie();return u.jsx(Rw,{fallback:i=>u.jsx(UC,{error:i}),children:t},a??r.key)}function zC({error:t}){return u.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:[u.jsx("p",{className:"font-serif text-xl text-fg",children:"Something went wrong"}),u.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."}),u.jsxs("details",{className:"w-full text-left",children:[u.jsx("summary",{className:"cursor-pointer text-xs text-fg-dim hover:text-fg-muted",children:"Technical detail"}),u.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-xs text-fg-dim",children:t.message})]}),u.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"btn btn-primary btn-touch",children:"Reload"})]})}function VC({children:t}){return u.jsx(Rw,{fallback:a=>u.jsx(zC,{error:a}),children:t})}const ju=Ka(t=>({on:!1,setOn(a){t({on:a})},toggle(){t(a=>({on:!a.on}))}})),BC=/^\/n\/[^/]+(\/edit)?$/;function Cw(t){return BC.test(t)}function HC(){const t=Ie(),a=ju(i=>i.setOn),r=ju(i=>i.toggle);return b.useEffect(()=>{a(!1)},[t.pathname]),b.useEffect(()=>{const i=o=>{(o.metaKey||o.ctrlKey)&&(o.altKey||o.shiftKey||o.key==="."&&Cw(t.pathname)&&(o.preventDefault(),r()))};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[t.pathname,r]),null}function qC(){const t=ju(a=>a.setOn);return u.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:u.jsx(gN,{width:18,height:18})})}function $C(){const t=sa(o=>o.push),[a,r]=b.useState(!1);return{copied:a,copy:async o=>{try{await navigator.clipboard.writeText(o),r(!0),t("Copied to clipboard.","success"),window.setTimeout(()=>r(!1),2e3)}catch{t("Couldn't copy — select and copy manually.","error")}}}}function QC({value:t,label:a,className:r}){const{copied:i,copy:o}=$C();return u.jsxs("div",{className:`flex items-stretch gap-2 ${r??""}`,children:[u.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}),u.jsx("button",{type:"button",onClick:()=>o(t),className:"btn btn-secondary btn-touch shrink-0","aria-label":`Copy ${a}`,children:i?"Copied":"Copy"})]})}function IC(t=navigator,a=window){var r;return(r=a.matchMedia)!=null&&r.call(a,"(display-mode: standalone)").matches?!0:t.standalone===!0}function KC(t=navigator.userAgent,a=typeof document<"u"&&navigator.maxTouchPoints>1){return/iPad|iPhone|iPod/.test(t)?!0:/Macintosh/.test(t)&&a}let Ss=null,Mw=!1;const Sh=new Set;function Cm(){for(const t of Sh)t()}function GC(t){t.preventDefault(),Ss=t,Cm()}function YC(){Ss=null,Mw=!0,Cm()}let Ob=!1;function PC(){Ob||typeof window>"u"||(Ob=!0,window.addEventListener("beforeinstallprompt",GC),window.addEventListener("appinstalled",YC))}PC();function Db(t){return Sh.add(t),()=>{Sh.delete(t)}}function FC(){const t=b.useSyncExternalStore(Db,()=>Ss,()=>null),a=b.useSyncExternalStore(Db,()=>Mw,()=>!1),[r,i]=b.useState({standalone:!0,ios:!1});b.useEffect(()=>{i({standalone:IC(),ios:KC()})},[]);const c=r.standalone||a?"installed":t!==null||r.ios?"available":"unsupported",h=b.useCallback(async()=>{const m=Ss;if(!m)return"unavailable";try{return await m.prompt(),(await m.userChoice).outcome}catch{return"unavailable"}finally{Ss===m&&(Ss=null,Cm())}},[]);return{state:c,isIOSDevice:r.ios,promptInstall:h}}function Ow(){const{state:t,isIOSDevice:a,promptInstall:r}=FC(),i=ne(m=>{var p;return((p=m.getActiveVault())==null?void 0:p.url)??null}),[o,c]=b.useState(!1);if(t!=="available")return null;const h=async()=>{await r()==="unavailable"&&a&&c(!0)};return u.jsxs(u.Fragment,{children:[u.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"}),o?u.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:[u.jsx("h2",{id:"ios-install-title",className:"mb-3 font-serif text-xl",children:"Add Parachute to your home screen"}),u.jsxs("ol",{className:"mb-5 list-decimal space-y-2 pl-5 text-sm text-fg-muted",children:[u.jsx("li",{children:"Tap the Share icon in Safari's toolbar."}),u.jsxs("li",{children:["Choose ",u.jsx("strong",{className:"text-fg",children:"Add to Home Screen"}),"."]}),u.jsx("li",{children:"Tap Add. Parachute will open standalone from your home screen."})]}),i?u.jsxs("div",{className:"mb-5 rounded-md border border-border bg-bg-soft/60 p-3",children:[u.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:"}),u.jsx(QC,{value:i,label:"vault address"})]}):null,u.jsx("div",{className:"flex justify-end",children:u.jsx("button",{type:"button",onClick:()=>c(!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]})}function Mm(t,a){return t==="notes"&&a==="pinned"}function XC(){const t=ne(o=>o.getActiveVault()),{roles:a}=Xs((t==null?void 0:t.id)??null),r=b.useMemo(()=>({...ow,tags:[a.pinned],sort:"desc",limit:5}),[a.pinned]),i=hw(r,{live:!1});return{vault:t,notes:i.data}}function Om({variant:t,onNavigate:a}){const{vault:r,notes:i}=XC();if(!r||!i||i.length===0)return null;const o=t==="rail"?"focus-ring block min-w-0 truncate rounded-lg px-3 pl-11 py-1 font-round text-xs text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:bg-bg hover:text-fg-muted":"focus-ring flex min-h-11 min-w-0 items-center rounded-lg px-3 pl-11 py-1 font-round text-sm text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:bg-bg hover:text-fg-muted";return u.jsx("ul",{"aria-label":"Pinned notes",className:"min-w-0 space-y-0.5 pb-1",children:i.map(c=>{const h=wu(c);return u.jsx("li",{className:"min-w-0",children:u.jsx(Ne,{to:`/n/${encodeURIComponent(c.id)}`,"data-pinned-note":c.id,onClick:a,className:o,children:t==="rail"?h.text:u.jsx("span",{className:"min-w-0 truncate",children:h.text})})},c.id)})})}const Eh="notes:textSize",_r=["default","larger","largest"];function ZC(t){return t==="default"||t==="larger"||t==="largest"}function Ts(){try{const t=localStorage.getItem(Eh);return ZC(t)?t:"default"}catch{return"default"}}function JC(t){try{t==="default"?localStorage.removeItem(Eh):localStorage.setItem(Eh,t)}catch{}}function Dw(t,a=document.documentElement){t==="default"?a.removeAttribute("data-text-size"):a.setAttribute("data-text-size",t)}function Od(t){return t==="larger"?"Larger":t==="largest"?"Largest":"Default"}function WC(t){const a=_r.indexOf(t);return _r[(a+1)%_r.length]??"default"}function eM(t){const a=_r.indexOf(t),r=_r.length;return _r[(a-1+r)%r]??"default"}const Th="notes:text-size-change";function fu(t){JC(t),Dw(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Th,{detail:t}))}function tM(){return b.useEffect(()=>{const t=a=>{if((a.metaKey||a.ctrlKey)&&!(a.altKey||a.shiftKey)){if(a.key==="="||a.key==="+"){a.preventDefault(),fu(WC(Ts()));return}if(a.key==="-"||a.key==="_"){a.preventDefault(),fu(eM(Ts()));return}if(a.key==="0"){a.preventDefault(),fu("default");return}}};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[]),null}const Dd=8;function kw(){const[t,a]=b.useState(()=>Ts()),[r,i]=b.useState(!1),o=b.useRef(null),c=b.useRef(null),[h,m]=b.useState("down"),[p,y]=b.useState(null),x=b.useCallback(v=>{a(v),fu(v)},[]);return b.useEffect(()=>{const v=T=>{T.key==="notes:textSize"&&a(Ts())},w=T=>{const E=T.detail;a(E||Ts())};return window.addEventListener("storage",v),window.addEventListener(Th,w),()=>{window.removeEventListener("storage",v),window.removeEventListener(Th,w)}},[]),b.useEffect(()=>{if(!r)return;const v=w=>{o.current&&(o.current.contains(w.target)||i(!1))};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[r]),b.useLayoutEffect(()=>{if(!r)return;const v=()=>{const w=o.current,T=c.current;if(!w||!T)return;const E=w.getBoundingClientRect(),_=T.getBoundingClientRect(),R=_.height||T.offsetHeight,M=_.width||T.offsetWidth,V=window.innerHeight-E.bottom;m(V<R+Dd?"up":"down");const H=E.right-M,k=Dd,Y=Math.max(k,window.innerWidth-M-Dd),$=Math.min(Math.max(H,k),Y);y($-E.left)};return v(),window.addEventListener("resize",v),window.addEventListener("scroll",v,!0),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0)}},[r]),u.jsxs("div",{ref:o,className:"relative",children:[u.jsx("button",{type:"button","aria-label":`Text size: ${Od(t)}. Click to change.`,"aria-expanded":r,title:`Text size: ${Od(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:u.jsxs("span",{"aria-hidden":"true",className:"font-serif",children:["A",u.jsx("span",{className:"text-xs",children:"a"})]})}),r?u.jsx("div",{role:"dialog",ref:c,"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:u.jsx("ul",{className:"flex flex-col gap-0.5",children:_r.map(v=>{const w=v===t;return u.jsx("li",{children:u.jsxs("button",{type:"button",onClick:()=>{x(v),i(!1)},"aria-pressed":w,className:`flex w-full items-center justify-between rounded px-2 py-1.5 text-left hover:bg-bg/60 ${w?"text-accent":"text-fg-muted"}`,children:[u.jsx("span",{children:Od(v)}),w?u.jsx("span",{"aria-hidden":"true",className:"text-xs",children:"✓"}):null]})},v)})})}):null]})}const jh="lens:theme",kd=["system","light","dark"];function nM(t){return t==="system"||t==="light"||t==="dark"}function aM(){try{const t=localStorage.getItem(jh);return nM(t)?t:"system"}catch{return"system"}}function rM(t){try{t==="system"?localStorage.removeItem(jh):localStorage.setItem(jh,t)}catch{}}function kb(t,a=document.documentElement){t==="system"?a.removeAttribute("data-theme"):a.setAttribute("data-theme",t)}function sM(t){const a=kd.indexOf(t);return kd[(a+1)%kd.length]}function iM(t){return t==="light"?"Light":t==="dark"?"Dark":"System"}function Nu(){const[t,a]=b.useState("system");b.useEffect(()=>{const o=aM();a(o),kb(o)},[]);const r=()=>{const o=sM(t);a(o),rM(o),kb(o)},i=iM(t);return u.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:u.jsx(lM,{theme:t})})}function lM({theme:t}){return t==="light"?u.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:[u.jsx("circle",{cx:"10",cy:"10",r:"3.5"}),u.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"?u.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"currentColor",children:u.jsx("path",{d:"M15.5 11.8a6 6 0 0 1-7.3-7.3 6 6 0 1 0 7.3 7.3z"})}):u.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",className:"h-4 w-4",fill:"none",stroke:"currentColor",strokeWidth:"1.6",children:[u.jsx("circle",{cx:"10",cy:"10",r:"6"}),u.jsx("path",{d:"M10 4v12",fill:"currentColor",stroke:"none"}),u.jsx("path",{d:"M10 4a6 6 0 0 1 0 12",fill:"currentColor",stroke:"none"})]})}function Lw(){const t=typeof window<"u"&&window.location?window.location.origin:"(unknown origin)";return u.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:[u.jsxs("p",{className:"mb-2 flex items-center gap-2 font-medium text-amber-100",children:[u.jsx("span",{"aria-hidden":!0,children:"⚠"}),"Insecure context — OAuth unavailable"]}),u.jsxs("p",{className:"mb-2 text-xs text-amber-100/90",children:["Your hub URL must be served over HTTPS or accessed at ",u.jsx("code",{children:"http://localhost"}),". This page is at ",u.jsx("code",{className:"font-mono",children:t}),", which the browser treats as insecure for Web Crypto. To connect:"]}),u.jsxs("ul",{className:"ml-4 list-disc space-y-1 text-xs text-amber-100/90",children:[u.jsxs("li",{children:["Use ",u.jsx("code",{children:"http://localhost"})," or ",u.jsx("code",{children:"http://127.0.0.1"})," directly (replace your hub URL with the localhost form), ",u.jsx("strong",{children:"or"})]}),u.jsx("li",{children:"Serve your hub over HTTPS via Tailscale Serve, Cloudflare Tunnel, or a reverse proxy."})]})]})}const oM={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."},uM="Something went wrong. Try again.";function cM(t){return/^[a-z][a-z0-9_]*$/.test(t)}function fM(t,a=uM){if(!(t instanceof Error))return a;const r=t.message.trim();return r?cM(r)?oM[r]??a:r:a}function dr(t){try{return Vh(t)}catch{return t.replace(/\/$/,"")}}function dM(t,a,r,i,o){const c=new Set(r.map(w=>dr(w.url))),h=new Set(t.map(w=>dr(w.url))),m=new Set(t.filter(w=>Gs(w.clientId)).map(w=>w.name)),p=[...t].sort((w,T)=>tl(w).localeCompare(tl(T))).map(w=>({kind:"device",id:w.id,label:tl(w),isActive:w.id===a,hubKnown:c.has(dr(w.url)),vault:w})),y=(o??[]).filter(w=>!(w.url!==void 0&&h.has(dr(w.url)))&&!m.has(w.name)).sort((w,T)=>w.name.localeCompare(T.name)).map(w=>({kind:"account",name:w.name,url:w.url})),x=new Set(y.filter(w=>w.url!==void 0).map(w=>dr(w.url))),v=i===null?[]:r.filter(w=>!h.has(dr(w.url))&&!x.has(dr(w.url))).sort((w,T)=>w.name.localeCompare(T.name)).map(w=>({kind:"hub",name:w.name,url:w.url,hubOrigin:i}));return[...p,...y,...v]}function Ld({label:t,here:a}){const r=(t.trim()[0]??"?").toUpperCase();return u.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 Ud({tone:t,children:a}){return u.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 Lb({layout:t,onAfterAction:a}){const r=ne(j=>j.vaults),i=ne(j=>j.activeVaultId),o=i?r[i]??null:null,[c,h]=b.useState(null),[m,p]=b.useState(!1),[y,x]=b.useState(null),[v,w]=b.useState(null),[T,E]=b.useState(null),[_,R]=b.useState(null),[M,V]=b.useState(!1),H=b.useMemo(()=>o?wR(o):null,[o]),k=lm(),Y=im(k.data),$=Zt(j=>j.identityEpoch),F=ct({queryKey:["account","vaults",$],queryFn:async()=>{try{return(await g0()).vaults}catch{return null}},staleTime:6e4}),G=F.data??null;b.useEffect(()=>{if(!H)return;const j=new AbortController;return p(!0),ER(H,fetch.bind(globalThis),j.signal).then(q=>{j.signal.aborted||(h(q),p(!1))}),()=>{j.abort(),p(!1)}},[H]);const Z=b.useMemo(()=>dM(Object.values(r),i,c??[],H,G),[r,i,c,H,G]),le=Z.filter(j=>j.kind==="device"),de=Z.filter(j=>j.kind==="account"),ge=Z.filter(j=>j.kind==="hub"),we=(Y==null?void 0:Y.plan)??null,se=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,O=b.useCallback(j=>{j.isActive||kR(j.id,{toast:!0}),a()},[a]),P=b.useCallback(async j=>{if(!T){E(j.name),R(null);try{await Vu(j.name),Nm(j.name),a()}catch(q){R(fM(q,"Couldn't open that vault."))}finally{E(null)}}},[T,a]),ae=b.useCallback(async j=>{x(j.name),w(null),V(!1);try{const{authorizeUrl:q}=await wm(j.hubOrigin,void 0,void 0,{params:{vault:j.name}});window.location.assign(q)}catch(q){x(null),q instanceof Mu?V(!0):w(q.message)}},[]),oe=m||F.isPending,ye=u.jsxs(u.Fragment,{children:[le.length>0?u.jsxs("div",{className:"border-b border-border-light",children:[u.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"On this device"}),u.jsx("ul",{className:"pb-2",children:le.map(j=>u.jsx("li",{children:u.jsxs("button",{type:"button",onClick:()=>O(j),className:"focus-ring flex w-full items-center gap-2.5 px-3 py-1.5 text-left hover:bg-bg-soft",children:[u.jsx(Ld,{label:j.label,here:!0}),u.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-fg",children:j.label}),j.isActive?u.jsx("span",{className:"shrink-0 text-2xs font-medium text-grass-ink",children:"✓ current"}):null]})},j.id))})]}):null,de.length>0?u.jsxs("div",{className:"border-b border-border-light",children:[u.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"In your account"}),u.jsx("ul",{className:"pb-2",children:de.map(j=>u.jsx("li",{children:u.jsxs("div",{className:"flex w-full items-center gap-2.5 px-3 py-1.5",children:[u.jsx(Ld,{label:j.name,here:!1}),u.jsx("span",{className:"min-w-0 flex-1 truncate text-fg-muted",children:j.name}),u.jsx("button",{type:"button",onClick:()=>P(j),disabled:T===j.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===j.name?"Opening…":"Open →"})]})},j.name))})]}):null,ge.length>0?u.jsxs("div",{className:"border-b border-border-light",children:[u.jsx("p",{className:"eyebrow px-3 pt-3 pb-1 text-2xs",children:"From your hub"}),u.jsx("ul",{className:"pb-2",children:ge.map(j=>u.jsx("li",{children:u.jsxs("div",{className:"flex w-full items-center gap-2.5 px-3 py-1.5",children:[u.jsx(Ld,{label:j.name,here:!1}),u.jsx("span",{className:"min-w-0 flex-1 truncate text-fg-muted",children:j.name}),u.jsx("button",{type:"button",onClick:()=>ae(j),disabled:y===j.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===j.name?"Connecting…":"Connect"})]})},j.url))})]}):null,M?u.jsx("div",{className:"border-b border-border-light px-3 py-2",children:u.jsx(Lw,{})}):null,v||_?u.jsx("div",{className:"border-b border-border-light px-3 py-2 text-xs text-(--color-danger)",children:v??_}):null,u.jsxs("div",{className:"border-b border-border-light py-2",children:[se&&we?u.jsxs(Ne,{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:[u.jsx(Ud,{tone:"sun",children:"↑"}),u.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"]}),u.jsx("span",{className:"shrink-0 text-sm font-semibold text-accent",children:"Upgrade →"})]}):u.jsxs(Ne,{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:[u.jsx(Ud,{tone:"accent",children:"+"}),u.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-accent",children:"Create a vault"})]}),u.jsxs(Ne,{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:[u.jsx(Ud,{tone:"sky",children:"⌂"}),u.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold",style:{color:"var(--color-sky)"},children:"Connect your own"})]})]}),u.jsxs("div",{className:"px-3 py-2",children:[ee!==null?u.jsxs(Ne,{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,u.jsxs("div",{className:"flex items-center justify-between gap-3",children:[u.jsx(Ne,{to:"/vaults",onClick:a,className:"focus-ring text-xs text-fg-muted hover:text-accent",children:"Manage vaults →"}),oe?u.jsx("span",{className:"text-[10px] text-fg-dim",children:"Looking for more vaults…"}):null]})]})]});return t==="inline"?u.jsx("section",{"aria-label":"Vaults",className:"text-sm",children:ye}):u.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:ye})}function Gu({variant:t="header",onOpenNavSheet:a,onAction:r,collapsed:i=!1}){const o=ne(w=>w.vaults),c=ne(w=>w.activeVaultId),h=c?o[c]??null:null,[m,p]=b.useState(!1),y=b.useRef(null);b.useEffect(()=>{if(!m)return;const w=E=>{y.current&&(y.current.contains(E.target)||p(!1))},T=E=>{E.key==="Escape"&&p(!1)};return document.addEventListener("mousedown",w),document.addEventListener("keydown",T),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",T)}},[m]);const x=b.useCallback(()=>p(!1),[]),v=h?tl(h):"Choose vault";if(t==="sheet")return u.jsx(Lb,{layout:"inline",onAfterAction:r??(()=>{})});if(t==="rail"){const w=(v.trim()[0]??"?").toUpperCase();return u.jsxs("div",{ref:y,className:"relative",children:[u.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:[u.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:w}),i?null:u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"min-w-0 flex-1 truncate font-round font-semibold text-fg",children:v}),u.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-xs text-fg-dim",children:"▾"})]})]}),m?u.jsx(Lb,{layout:"popover",onAfterAction:x}):null]})}return u.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:[u.jsx("span",{"aria-hidden":!0,className:"inline-block h-2 w-2 shrink-0 rounded-full bg-accent"}),u.jsx("span",{className:"min-w-0 truncate",children:v}),u.jsx("span",{"aria-hidden":!0,className:"ml-1 shrink-0 text-xs text-fg-dim",children:"▾"})]})}function hM({open:t,onClose:a,initialFocus:r}){return t?u.jsx(mM,{onClose:a,initialFocus:r}):null}function mM({onClose:t,initialFocus:a}){const r=ne(w=>Object.keys(w.vaults).length>0),i=Ku(),o=Ie(),c=b.useRef(null),h=b.useRef(null),m=b.useRef(null),p=i.filter(w=>w.id!=="foot"),y=i.find(w=>w.id==="foot");b.useEffect(()=>{var E;const w=document.activeElement,T=a==="switcher"?((E=h.current)==null?void 0:E.querySelector("button, a"))??c.current:c.current;return T==null||T.focus(),()=>{var _;return(_=w==null?void 0:w.focus)==null?void 0:_.call(w)}},[a]),b.useEffect(()=>{const w=T=>{if(T.key==="Escape"){t();return}if(T.key!=="Tab"||!c.current)return;const E=Array.from(c.current.querySelectorAll('a[href], button:not([disabled]), input, select, textarea, [tabindex]:not([tabindex="-1"])'));if(E.length===0)return;const _=E[0],R=E[E.length-1],M=document.activeElement;if(!(M instanceof HTMLElement)||!E.includes(M)){T.preventDefault(),(T.shiftKey?R:_).focus();return}T.shiftKey&&document.activeElement===_?(T.preventDefault(),R.focus()):!T.shiftKey&&document.activeElement===R&&(T.preventDefault(),_.focus())};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[t]),b.useEffect(()=>{const w=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=w}},[]);const x=w=>{m.current=c.current&&c.current.scrollTop<=0?w.touches[0].clientY:null},v=w=>{m.current!==null&&w.touches[0].clientY-m.current>64&&(m.current=null,t())};return u.jsxs("div",{className:"fixed inset-0 z-40 md:hidden",children:[u.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"}),u.jsxs("div",{role:"dialog",ref:c,"aria-modal":"true","aria-label":"Menu",tabIndex:-1,onTouchStart:x,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:[u.jsx("div",{"aria-hidden":!0,className:"sticky top-0 z-10 flex justify-center pt-2.5 pb-1.5",children:u.jsx("span",{className:"h-1 w-10 rounded-full bg-border"})}),r?u.jsx("div",{ref:h,"data-nav-band":"switcher",className:"border-b border-border-light",children:u.jsx(Gu,{variant:"sheet",onAction:t})}):null,p.length>0?u.jsx("nav",{"aria-label":"Primary",className:"px-3 pb-1",children:p.map(w=>u.jsx(pM,{band:w},w.id))}):null,u.jsxs("div",{"data-nav-band":"foot",className:"border-t border-border px-3 py-3",children:[y==null?void 0:y.items.map(w=>u.jsx(Uw,{item:w,loc:o},w.id)),u.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 px-3",children:[u.jsx(Ow,{}),u.jsx(kw,{}),u.jsx(Nu,{})]})]})]})]})}function pM({band:t}){const a=Ie();return u.jsxs("div",{"data-nav-band":t.id,children:[t.label?u.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[u.jsx("span",{children:t.label}),t.sublabel?u.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.items.map(r=>u.jsxs(b.Fragment,{children:[u.jsx(Uw,{item:r,loc:a}),Mm(t.id,r.id)?u.jsx(Om,{variant:"touch"}):null]},r.id))]})}function Uw({item:t,loc:a}){const r=t.match(a);return u.jsxs(Ne,{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:[u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),u.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})}const Ub={rows:[],byKind:{},total:0,pendingCount:0,needsHumanCount:0,authHalt:null};function zw(t,a,r=2e3){const[i,o]=b.useState(Ub),c=b.useRef(!1);return b.useEffect(()=>{if(c.current=!1,!t||!a){o(Ub);return}let h=null;const m=async()=>{try{const[p,y]=await Promise.all([lw(t,a),Ps(t,iw)]);if(c.current)return;const x={};let v=0,w=0;for(const E of p){const _=E.mutation.kind;x[_]=(x[_]??0)+1,E.status==="needs-human"?w+=1:v+=1}const T=y&&y.vaultId===a?y:null;o({rows:p,byKind:x,total:p.length,pendingCount:v,needsHumanCount:w,authHalt:T})}catch{}};return m(),h=setInterval(m,r),()=>{c.current=!0,h&&clearInterval(h)}},[t,a,r]),i}const gM=[["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 Dm(t,a=new Date){if(!t)return"";const i=new Date(t).getTime();if(Number.isNaN(i))return"";const o=a.getTime()-i,c=Math.abs(o);for(const[h,m]of gM)if(c>=m){const p=Math.floor(c/m);return o>=0?`${p}${h} ago`:`in ${p}${h}`}return"just now"}const yM={"create-note":"new notes","update-note":"note edits","delete-note":"deletions","upload-attachment":"uploads","link-attachment":"attachment links","delete-attachment":"attachment removals"},vM=.8;function bM({onDismiss:t}){const{db:a,isOnline:r,isDraining:i,lastSyncedAt:o}=Wt(),c=ne(M=>M.activeVaultId),h=sa(M=>M.push),m=zw(a,c),[p,y]=b.useState(null),x=Mr(M=>c?M.byVault[c]??null:null),[,v]=b.useState(0);b.useEffect(()=>{const M=setInterval(()=>v(V=>V+1),15e3);return()=>clearInterval(M)},[]),b.useEffect(()=>{let M=!1;return l2().then(V=>{M||V.supported&&typeof V.usage=="number"&&typeof V.quota=="number"&&y({usage:V.usage,quota:V.quota})}),()=>{M=!0}},[]);const w=(x==null?void 0:x.state)==="down",T=m.authHalt?"Reconnect needed":w?"Vault not reachable":r?i?"Syncing…":m.total>0?"Sync pending":"All caught up":"Offline — changes queued",E=async M=>{a&&(await A2(a,M),h("Retrying…","success"))},_=async(M,V)=>{a&&confirm(`Discard this ${zb(V.mutation)}? It cannot be recovered.`)&&(await _2(a,M),h("Row discarded.","success"))},R=async()=>{if(!a||!c||!confirm(`Clear every pending row for this vault (${m.total} total)? Destructive.`))return;const M=await M2(a,c);h(`Cleared ${M} pending row${M===1?"":"s"}.`,"success")};return u.jsxs("div",{className:"space-y-4",children:[u.jsxs("header",{className:"flex items-baseline justify-between",children:[u.jsx("h3",{className:"font-serif text-base text-fg",children:T}),t?u.jsx("button",{type:"button",onClick:t,"aria-label":"Close sync status",className:"text-xs text-fg-dim hover:text-accent",children:"×"}):null]}),m.authHalt?u.jsxs("div",{className:"rounded-md border border-red-500/30 bg-red-500/5 p-3 text-xs text-red-300",children:[u.jsx("p",{className:"mb-2",children:m.authHalt.message||"Vault rejected the current session."}),u.jsx(Ne,{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?u.jsx("p",{className:"text-xs text-fg-dim",children:"Nothing pending in this vault."}):u.jsxs("section",{children:[u.jsx("h4",{className:"mb-1 text-xs uppercase tracking-wider text-fg-dim",children:"Queue"}),u.jsx("ul",{className:"space-y-0.5 text-xs",children:Object.entries(m.byKind).map(([M,V])=>u.jsxs("li",{className:"flex justify-between",children:[u.jsx("span",{className:"text-fg-muted",children:yM[M]??M}),u.jsx("span",{className:"tabular-nums text-fg-dim",children:V})]},M))})]}),m.needsHumanCount>0?u.jsxs("section",{children:[u.jsx("h4",{className:"mb-1 text-xs uppercase tracking-wider text-fg-dim",children:"Needs your help"}),u.jsx("ul",{className:"space-y-1.5",children:m.rows.filter(M=>M.status==="needs-human").map(M=>u.jsxs("li",{className:"rounded border border-amber-500/30 bg-amber-500/5 p-2 text-xs",children:[u.jsx("p",{className:"font-medium text-amber-200",children:zb(M.mutation)}),M.lastError?u.jsx("p",{className:"mt-0.5 break-words text-amber-100/70",children:M.lastError}):null,u.jsxs("div",{className:"mt-1 flex gap-2",children:[u.jsx("button",{type:"button",onClick:()=>E(M.seq),className:"text-accent hover:underline",children:"Retry"}),u.jsx("button",{type:"button",onClick:()=>_(M.seq,M),className:"text-red-300 hover:underline",children:"Discard"})]})]},M.seq))})]}):null,u.jsx("section",{className:"text-xs text-fg-dim",children:u.jsxs("p",{children:["Last synced:"," ",u.jsx("span",{className:"text-fg-muted",children:o?Dm(new Date(o).toISOString()):"never"})]})}),p?u.jsx(xM,{usage:p.usage,quota:p.quota}):null,m.total>0?u.jsx("div",{className:"flex justify-end border-t border-border pt-3",children:u.jsx("button",{type:"button",onClick:R,className:"text-xs text-red-400 hover:underline",children:"Clear all pending"})}):null]})}function zb(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 xM({usage:t,quota:a}){const r=a>0?t/a:0,i=r>=vM;return u.jsxs("section",{className:"text-xs",children:[u.jsxs("div",{className:"flex justify-between text-fg-dim",children:[u.jsx("span",{children:"Offline cache"}),u.jsx("span",{className:i?"text-amber-300":"text-fg-muted",children:wM(t)})]}),i?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"mt-1 h-1.5 w-full overflow-hidden rounded-full bg-border/40",children:u.jsx("div",{className:"h-full bg-amber-400",style:{width:`${Math.min(100,Math.round(r*100))}%`}})}),u.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 wM(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 SM(t){return t.authHalt?"halted":t.unreachable?"unreachable":t.isOnline?t.isDraining?"syncing":"online":"offline"}function EM(){const{db:t,isOnline:a,isDraining:r}=Wt(),i=ne(w=>w.activeVaultId),o=zw(t,i),c=Mr(w=>i?w.byVault[i]??null:null),[h,m]=b.useState(!1),p=b.useRef(null);b.useEffect(()=>{if(!h)return;const w=T=>{p.current&&(p.current.contains(T.target)||m(!1))};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[h]);const y=SM({isOnline:a,isDraining:r,authHalt:o.authHalt!==null,unreachable:(c==null?void 0:c.state)==="down"}),x=TM(y),v=o.total>0?o.total:null;return u.jsxs("div",{ref:p,className:"relative",children:[u.jsxs("button",{type:"button","aria-label":`Sync status: ${x}${v?`, ${v} pending`:""}`,"aria-expanded":h,onClick:()=>m(w=>!w),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:[u.jsx(jM,{tone:y}),u.jsx("span",{className:"hidden text-xs sm:inline",children:x}),v!==null?u.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?u.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:u.jsx(bM,{onDismiss:()=>m(!1)})}):null]})}function TM(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 jM({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 u.jsx("span",{"aria-hidden":!0,className:`inline-block h-2 w-2 rounded-full ${t==="syncing"?"animate-pulse":""}`,style:{backgroundColor:a}})}const NM="(max-width: 767.98px)";function AM(){const t=Ie(),a=ne(o=>Object.keys(o.vaults).length>0),[r,i]=b.useState(null);return b.useEffect(()=>{i(null)},[t.pathname]),b.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const o=window.matchMedia(NM),c=h=>{h.matches||i(null)};return o.addEventListener("change",c),()=>o.removeEventListener("change",c)},[]),!a&&t.pathname==="/"?null:u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"sticky top-0 z-10 border-b border-border bg-bg/90 backdrop-blur md:hidden",style:{paddingTop:"env(safe-area-inset-top)"},children:u.jsxs("nav",{className:"flex items-center justify-between gap-3 px-4 py-3",children:[a?u.jsx("div",{className:"min-w-0 flex-1",children:u.jsx(Gu,{variant:"header",onOpenNavSheet:()=>i("switcher")})}):u.jsx(Ne,{to:"/",className:"focus-ring min-w-0 shrink truncate font-serif text-lg tracking-tight text-fg hover:text-accent",children:"Parachute"}),u.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a?u.jsx(EM,{}):null,u.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:u.jsx("span",{"aria-hidden":"true",className:"font-mono text-base leading-none",children:"☰"})})]})]})}),u.jsx(hM,{open:r!==null,onClose:()=>i(null),initialFocus:r==="switcher"?"switcher":void 0})]})}function _M(){const{mirror:t}=Wt();return t.state==="hydrating"&&t.progress?u.jsx(RM,{done:t.progress.done}):t.state==="offline"&&t.lastSyncedAt!==null?u.jsxs(Vw,{children:["Offline — showing your saved vault · updated ",CM(t.lastSyncedAt)]}):null}function RM({done:t}){var o;const a=(o=fw().data)==null?void 0:o.stats,r=a==null?void 0:a.totalNotes,i=typeof r=="number"&&r>0?`${t} of ~${r}`:`${t}`;return u.jsxs(Vw,{live:"off",children:["Saving your vault for offline · ",i]})}function Vw({children:t,live:a}){return u.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 CM(t){return Dm(new Date(t).toISOString())}const Vb="nav-drawer-panel",MM="(min-width: 768px) and (max-width: 1023.98px)";function OM(){const t=ne(x=>x.getActiveVault()),a=Ku(),r=Ie(),[i,o]=b.useState(!1),c=b.useCallback(()=>o(!1),[]),h=b.useRef(null),m=b.useRef(null);if(b.useEffect(()=>{if(!i)return;const x=v=>{var T,E;if(v.key!=="Escape"||v.defaultPrevented)return;const w=((T=h.current)==null?void 0:T.contains(document.activeElement))??!1;o(!1),w&&((E=m.current)==null||E.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[i]),b.useEffect(()=>{o(!1)},[r.pathname]),b.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const x=window.matchMedia(MM),v=w=>{w.matches||o(!1)};return x.addEventListener("change",v),()=>x.removeEventListener("change",v)},[]),!t)return null;const p=a.filter(x=>x.id!=="foot"),y=a.find(x=>x.id==="foot");return u.jsx("div",{ref:h,"data-nav-projection":"drawer","data-drawer-open":i?"true":"false",className:`glass-panel sticky top-0 hidden h-dvh shrink-0 flex-col border-r border-border transition-[width] duration-(--dur-move) ease-out md:flex lg:hidden ${i?"w-72":"w-14"}`,style:{paddingTop:"env(safe-area-inset-top)"},children:u.jsxs("nav",{"aria-label":"Vault navigation",id:i?Vb:void 0,className:"flex min-h-0 flex-1 flex-col",children:[u.jsxs("div",{className:`flex shrink-0 items-start justify-center gap-1.5 ${i?"p-1.5":"p-1"}`,children:[i?u.jsx("div",{className:"min-w-0 flex-1",children:u.jsx(Gu,{variant:"rail"})}):null,u.jsx("button",{ref:m,type:"button",onClick:()=>o(x=>!x),"aria-expanded":i,"aria-controls":i?Vb:void 0,"aria-label":i?"Close the navigation drawer":"Open the navigation drawer",title:i?"Close navigation":"Open navigation",className:"focus-ring grid h-11 w-11 shrink-0 place-items-center rounded-lg text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:bg-bg hover:text-fg-muted",children:u.jsx("span",{"aria-hidden":!0,className:`transition-transform duration-(--dur-move) ease-out ${i?"":"rotate-180"}`,children:u.jsx(a0,{width:20,height:20})})})]}),i?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"shrink-0 px-3 pb-3",children:u.jsx(kM,{onDone:c})}),u.jsx("div",{className:"enter-fade min-h-0 flex-1 overflow-y-auto px-3 pb-3",children:p.map(x=>u.jsx(DM,{band:x,onNavigate:c},x.id))}),u.jsxs("div",{"data-nav-band":"foot",className:"enter-fade shrink-0 border-t border-border px-3 pt-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))]",children:[y==null?void 0:y.items.map(x=>u.jsx(Bw,{item:x,loc:r,onNavigate:c},x.id)),u.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 px-3",children:[u.jsx(Ow,{}),u.jsx(kw,{}),u.jsx(Nu,{})]})]})]}):u.jsx("div",{"aria-hidden":!0,className:"mt-1 flex justify-center",children:u.jsx("span",{className:"h-10 w-1 rounded-full bg-border-light"})})]})})}function DM({band:t,onNavigate:a}){const r=Ie();return u.jsxs("div",{"data-nav-band":t.id,children:[t.label?u.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[u.jsx("span",{children:t.label}),t.sublabel?u.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.items.map(i=>u.jsxs(b.Fragment,{children:[u.jsx(Bw,{item:i,loc:r,onNavigate:a}),Mm(t.id,i.id)?u.jsx(Om,{variant:"touch",onNavigate:a}):null]},i.id))]})}function Bw({item:t,loc:a,onNavigate:r}){const i=t.match(a);return u.jsxs(Ne,{to:t.to,"data-nav-item":t.id,onClick:r,"aria-current":i?"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 ${i?"bg-grass-soft font-semibold text-grass-ink":"font-medium text-fg-muted hover:bg-bg hover:text-fg"}`,children:[u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),u.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})}function kM({onDone:t}){const a=Es(r=>r.setOpen);return u.jsxs("button",{type:"button",onClick:()=>{a(!0),t()},className:"focus-ring flex min-h-11 w-full items-center gap-2.5 rounded-lg border border-border bg-card px-3 py-2.5 text-left font-round text-base text-fg-dim transition-colors duration-(--dur-quick) ease-out hover:border-accent/50 hover:text-fg-muted",children:[u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:u.jsx(rl,{width:18,height:18})}),u.jsx("span",{className:"flex-1",children:"Search…"})]})}const Hw=10,LM="lens:recents:";function qw(t){return LM+t}function $w(t){try{const a=localStorage.getItem(qw(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,Hw):[]}catch{return[]}}function Ok(t,a,r=Date.now()){try{const i=$w(t).filter(c=>c.id!==a),o=[{id:a,viewedAt:r},...i].slice(0,Hw);localStorage.setItem(qw(t),JSON.stringify(o))}catch{}}const UM=new Set([" ","/","-","_",".","\\"]);function nl(t,a){if(!t)return{score:0,indices:[]};if(!a)return null;const r=t.toLowerCase(),i=a.toLowerCase();let o=0,c=0,h=-2,m=!0;const p=[];for(let y=0;y<i.length&&o<r.length;y+=1){const x=i[y]??"";if(x===r[o]){p.push(y);let v=1;y===0?v+=4:m&&(v+=2),h===y-1&&(v+=3),c+=v,h=y,o+=1}m=UM.has(x)}return o<r.length?null:(c-=Math.floor(i.length/20),{score:c,indices:p})}const zd=20,Bb=[{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 zM(t,a){let r=null;for(const i of t){const o=nl(a,i);o&&(r===null||o.score>r)&&(r=o.score)}return r}function VM(t,a){const r=__(t),i=nl(a,r),o=t.path?nl(a,t.path):null;let c=null;i&&(c=i.score+2),o&&(c===null||o.score>c)&&(c=o.score);for(const h of t.tags??[]){const m=nl(a,h);m&&(c===null||m.score>c)&&(c=m.score)}return c}function BM(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(w=>[w.id,w])),x=[];for(const w of t.recents){const T=y.get(w.id);if(!T)continue;const E=wu(T);x.push({kind:"note",id:T.id,title:E.text,titleKind:E.kind,path:T.path,score:0})}const v=Bb.map(w=>({kind:"command",id:w.id,label:w.label,description:w.description,action:w.action,score:0}));return[...x,...v].slice(0,zd)}const o=Bb.flatMap(y=>{const x=zM([y.label,...y.keywords],i);return x===null?[]:[{kind:"command",id:y.id,label:y.label,description:y.description,action:y.action,score:x+(r?1e3:0)}]});if(r)return o.sort((y,x)=>x.score-y.score).slice(0,zd);const c=t.notes.flatMap(y=>{const x=VM(y,i);if(x===null)return[];const v=wu(y);return[{kind:"note",id:y.id,title:v.text,titleKind:v.kind,path:y.path,score:x}]}),m=[...t.tags.flatMap(y=>{const x=nl(i,y.name);return x?[{kind:"tag",name:y.name,count:y.count,score:x.score}]:[]})].sort((y,x)=>x.score-y.score),p=[...o,...c].sort((y,x)=>x.score-y.score);return[...m,...p].slice(0,zd)}const HM=150;function qM({onClose:t}){const a=ne(k=>k.activeVaultId),r=Cr(),i=b.useRef(null),o=b.useRef(null),c=b.useId(),h=b.useId(),[m,p]=b.useState(""),[y,x]=b.useState(""),[v,w]=b.useState(0),T=sR(!0),E=uR(),_=b.useMemo(()=>a?$w(a):[],[a]);b.useEffect(()=>{const k=setTimeout(()=>x(m),HM);return()=>clearTimeout(k)},[m]);const R=b.useMemo(()=>BM({query:y,notes:T.data??[],tags:E.data??[],recents:_}),[y,T.data,E.data,_]);b.useEffect(()=>{w(0)},[R.length]),b.useEffect(()=>{var k;(k=i.current)==null||k.focus()},[]);const M=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]),V=b.useCallback(k=>{if(k.key==="Escape"){k.preventDefault(),t();return}if(k.key==="ArrowDown"){k.preventDefault(),w(Y=>Math.min(R.length-1,Y+1));return}if(k.key==="ArrowUp"){k.preventDefault(),w(Y=>Math.max(0,Y-1));return}if(k.key==="Enter"){k.preventDefault();const Y=R[v];Y&&M(Y);return}},[R,v,M,t]);b.useEffect(()=>{var Y,$;const k=(Y=o.current)==null?void 0:Y.querySelector(`[data-qs-idx="${v}"]`);($=k==null?void 0:k.scrollIntoView)==null||$.call(k,{block:"nearest"})},[v]);const H=T.isPending;return u.jsx("dialog",{open:!0,"aria-labelledby":c,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:u.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:[u.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:[u.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:[u.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-fg-dim",children:u.jsx(rl,{width:18,height:18})}),u.jsx("input",{id:c,ref:i,type:"text",value:m,onChange:k=>p(k.target.value),onKeyDown:V,placeholder:"Search your vault…","aria-label":"Quick switch query","aria-controls":h,"aria-activedescendant":R[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"}),u.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:[u.jsx(t0,{width:13,height:13}),"Smart"]})]}),u.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"})]}),u.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:[u.jsx("div",{id:h,ref:o,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&&R.length===0?u.jsx("div",{className:"px-4 py-3 text-sm text-fg-dim",children:"Loading notes…"}):R.length===0?u.jsx("div",{className:"px-4 py-3 text-sm text-fg-dim",children:m.trim().length===0?"Start typing to search.":"No matches."}):R.map((k,Y)=>u.jsx(QM,{entry:k,index:Y,selected:Y===v,onPick:()=>M(k),onHover:()=>w(Y)},$M(k)))}),u.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:[u.jsxs("span",{children:[u.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"↑↓"})," navigate"," ",u.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"↵"})," open"," ",u.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:"esc"})," close"," ",u.jsx("kbd",{className:"rounded bg-bg/60 px-1",children:">"})," commands"]}),u.jsx("span",{className:"tabular-nums",children:R.length>0?`${R.length} result${R.length===1?"":"s"}`:""})]})]})]})})}function $M(t){return t.kind==="note"?`note:${t.id}`:t.kind==="tag"?`tag:${t.name}`:`cmd:${t.id}`}function QM({entry:t,index:a,selected:r,onPick:i,onHover:o}){const c=r?"bg-accent/10 text-fg":"text-fg-muted";return u.jsx("div",{id:`qs-opt-${a}`,role:"option",tabIndex:-1,"aria-selected":r,"data-qs-idx":a,onMouseEnter:o,onMouseDown:h=>{h.preventDefault(),i()},className:`mx-1.5 flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-sm ${c}`,children:t.kind==="note"?u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"note"}),u.jsx("span",{className:t.titleKind==="timestamp"?"truncate title-timestamp":"truncate font-medium",children:t.title}),t.path?u.jsx("span",{className:"ml-auto truncate font-mono text-xs text-fg-dim",children:t.path}):null]}):t.kind==="tag"?u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"tag"}),u.jsxs("span",{className:"font-mono",children:["#",t.name]}),u.jsx("span",{className:"ml-auto text-xs tabular-nums text-fg-dim",children:t.count})]}):u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"text-xs uppercase tracking-wider text-accent",children:"cmd"}),u.jsx("span",{className:"font-medium",children:t.label}),u.jsx("span",{className:"ml-auto text-xs text-fg-dim",children:t.description})]})})}function IM(){const t=Es(c=>c.open),a=Es(c=>c.setOpen),r=Es(c=>c.toggle),i=ne(c=>c.activeVaultId);b.useEffect(()=>{const c=h=>{h.key==="k"&&(h.metaKey||h.ctrlKey)&&!h.altKey&&!h.shiftKey&&(h.preventDefault(),r())};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[r]);const o=b.useRef(i);return b.useEffect(()=>{o.current!==i&&(o.current=i,a(!1))},[i,a]),!t||i===null?null:u.jsx(qM,{onClose:()=>a(!1)})}const Hb="parachute.rail-collapsed";function KM(){const[t,a]=b.useState(()=>{try{return localStorage.getItem(Hb)==="1"}catch{return!1}}),r=b.useCallback(()=>{a(i=>{const o=!i;try{localStorage.setItem(Hb,o?"1":"0")}catch{}return o})},[]);return[t,r]}function GM(){const t=ne(h=>h.getActiveVault()),a=Ku(),[r,i]=KM();if(!t)return null;const o=a.filter(h=>h.id!=="foot"),c=a.find(h=>h.id==="foot");return u.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:[u.jsxs("div",{className:r?"flex flex-col items-stretch gap-2 p-3":"p-3",children:[u.jsxs("div",{className:r?"":"flex items-start gap-1.5",children:[u.jsx("div",{className:"min-w-0 flex-1",children:u.jsx(Gu,{variant:"rail",collapsed:r})}),u.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:u.jsx("span",{"aria-hidden":!0,className:`transition-transform duration-(--dur-move) ease-out ${r?"rotate-180":""}`,children:u.jsx(a0,{width:16,height:16})})})]}),u.jsx(PM,{collapsed:r})]}),u.jsx("nav",{"aria-label":"Your vault",className:"flex-1 overflow-y-auto px-3 pb-3",children:o.map(h=>u.jsx(YM,{band:h,collapsed:r},h.id))}),u.jsxs("div",{"data-nav-band":"foot",className:"border-t border-border p-3",children:[c==null?void 0:c.items.map(h=>r?u.jsx(Nh,{item:h,collapsed:!0},h.id):u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("div",{className:"min-w-0 flex-1",children:u.jsx(Nh,{item:h,collapsed:!1})}),u.jsx(Nu,{})]},h.id)),r?u.jsx("div",{className:"mt-1 flex justify-center",children:u.jsx(Nu,{})}):null]})]})}function YM({band:t,collapsed:a}){return u.jsxs("div",{"data-nav-band":t.id,children:[t.label&&!a?u.jsxs("p",{className:"eyebrow flex items-baseline gap-2 px-3 pt-4 pb-1.5",children:[u.jsx("span",{children:t.label}),t.sublabel?u.jsx("span",{className:"font-round text-2xs normal-case text-fg-dim",children:t.sublabel}):null]}):null,t.label&&a?u.jsx("div",{"aria-hidden":!0,className:"mx-2 mt-3 mb-2 border-t border-border-light"}):null,t.items.map(r=>u.jsxs(b.Fragment,{children:[u.jsx(Nh,{item:r,collapsed:a}),Mm(t.id,r.id)&&!a?u.jsx(Om,{variant:"rail"}):null]},r.id))]})}function Nh({item:t,collapsed:a}){const r=Ie(),i=t.match(r);return u.jsxs(Ne,{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:[u.jsx("span",{"aria-hidden":!0,className:"grid h-5 w-5 shrink-0 place-items-center",children:t.icon}),a?null:u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),t.badge]})]})}function PM({collapsed:t}){const a=Es(r=>r.setOpen);return t?u.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:u.jsx(rl,{width:16,height:16})}):u.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:[u.jsx("span",{"aria-hidden":!0,className:"grid h-4 w-4 shrink-0 place-items-center",children:u.jsx(rl,{width:16,height:16})}),u.jsx("span",{className:"flex-1",children:"Search…"}),u.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 FM(){const t=ne(m=>m.activeVaultId!==null),{pathname:a}=Ie(),[r,i]=b.useState(!1),o=b.useRef(null),c=b.useRef(null),h=b.useId();return b.useEffect(()=>{i(!1)},[a]),b.useEffect(()=>{if(!r)return;const m=y=>{var x;y.key==="Escape"&&(i(!1),(x=c.current)==null||x.focus())},p=y=>{o.current&&y.target instanceof Node&&!o.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||Nw(a)||a==="/new"?null:u.jsxs("div",{ref:o,className:"fixed top-6 right-6 z-30 hidden md:block",children:[u.jsx("button",{ref:c,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:u.jsx("span",{"aria-hidden":"true",className:`transition-transform duration-(--dur-move) ease-out ${r?"rotate-45":""}`,children:u.jsx(Fh,{width:24,height:24,strokeWidth:2})})}),r?u.jsxs("div",{id:h,"aria-label":"Create",className:"mt-3 flex flex-col items-end gap-3",children:[u.jsx(Vd,{to:"/new",label:"New note",icon:u.jsx(uN,{width:18,height:18})}),u.jsx(Vd,{to:"/new?voice=1",label:"Voice note",icon:u.jsx(cN,{width:18,height:18})}),u.jsx(Vd,{to:"/import",label:"Import notes",icon:u.jsx(n0,{width:18,height:18})})]}):null]})}function Vd({to:t,label:a,icon:r}){return u.jsxs(Ne,{to:t,"data-speed-dial-verb":a,className:"focus-ring group flex items-center gap-3 rounded-full",children:[u.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}),u.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 XM=4e3;function ZM(){const t=sa(r=>r.toasts),a=sa(r=>r.dismiss);return b.useEffect(()=>{if(t.length===0)return;const r=t.map(i=>window.setTimeout(()=>a(i.id),i.durationMs??XM));return()=>{for(const i of r)window.clearTimeout(i)}},[t,a]),t.length===0?null:u.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=>u.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:[u.jsx("span",{children:r.message}),u.jsx("button",{type:"button",onClick:()=>a(r.id),"aria-label":"Dismiss",className:"focus-ring text-fg-dim hover:text-fg",children:"×"})]},r.id))})}function JM(t={}){const{immediate:a=!1,onNeedReload:r,onNeedRefresh:i,onOfflineReady:o,onRegistered:c,onRegisteredSW:h,onRegisterError:m}=t;let p,y;const x=async(w=!0)=>{await y};async function v(){if("serviceWorker"in navigator){if(p=await Ke(async()=>{const{Workbox:w}=await import("./workbox-window.prod.es5-BBnX5xw4.js");return{Workbox:w}},[]).then(({Workbox:w})=>new w("/sw.js",{scope:"/",type:"classic"})).catch(w=>{m==null||m(w)}),!p)return;p.addEventListener("activated",w=>{(w.isUpdate||w.isExternal)&&(r?r():window.location.reload())}),p.addEventListener("installed",w=>{w.isUpdate||o==null||o()}),p.register({immediate:a}).then(w=>{h?h("/sw.js",w):c==null||c(w)}).catch(w=>{m==null||m(w)})}}return y=v(),x}function WM(t={}){const{immediate:a=!0,onNeedReload:r,onNeedRefresh:i,onOfflineReady:o,onRegistered:c,onRegisteredSW:h,onRegisterError:m}=t,[p,y]=b.useState(!1),[x,v]=b.useState(!1),[w]=b.useState(()=>JM({immediate:a,onNeedReload:r,onOfflineReady(){v(!0),o==null||o()},onNeedRefresh(){y(!0),i==null||i()},onRegistered:c,onRegisteredSW:h,onRegisterError:m}));return{needRefresh:[p,y],offlineReady:[x,v],updateServiceWorker:w}}const qb={BASE_URL:"/"};function eO(t,a){const r=t&&t.length>0?t:a;return!r||r===""||r==="/"?"":r.replace(/\/$/,"")}function tO(){const t=typeof import.meta<"u"&&qb?qb:void 0,a=t?t.VITE_BASE_PATH:void 0,r=t?t.BASE_URL:void 0;return eO(a,r)}const nO=tO();function aO(t){return yl()===nO}async function rO(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=yl(),o=await r.getRegistrations();let c=0;for(const h of o)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(),c+=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 c}function sO(){return WM({onRegisteredSW(t,a){if(!a)return;const r=3600*1e3;setInterval(()=>{a.update().catch(()=>{})},r)},onNeedReload(){yT()}}),null}function iO(){return aO()?u.jsx(sO,{}):null}function lO(){const t=ne(o=>o.activeVaultId),a=ne(o=>o.getActiveVault()),r=Ar(o=>t?o.byVault[t]??null:null),i=Mr(o=>t?o.byVault[t]??null:null);return!a||!t?null:r&&!Gs(a.clientId)?u.jsx(oO,{reason:r.reason,vaultIssuer:a.issuer??a.url,vaultScope:a.scope,vaultId:t}):i&&i.state==="down"?u.jsx(uO,{vaultUrl:a.url,vaultId:t}):null}function oO({reason:t,vaultIssuer:a,vaultScope:r,vaultId:i}){const[o,c]=b.useState(!1),[h,m]=b.useState(null),[p,y]=b.useState(!1);async function x(){m(null),y(!1),c(!0);try{const{authorizeUrl:v}=await wm(a,r,void 0,{priorHaltedVaultId:i});window.location.assign(v)}catch(v){v instanceof Mu?y(!0):m(v instanceof Error?v.message:String(v))}finally{c(!1)}}return u.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:[u.jsxs("div",{className:"mx-auto flex max-w-5xl flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[u.jsxs("div",{children:[u.jsx("p",{className:"font-medium text-red-100",children:"Vault session expired"}),u.jsx("p",{className:"text-xs text-red-200/80",children:t}),h?u.jsx("p",{className:"mt-1 text-xs text-red-300",children:h}):null]}),u.jsx("button",{type:"button",onClick:x,disabled:o,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:o?"Starting OAuth…":"Reconnect to vault"})]}),p?u.jsx("div",{className:"mx-auto mt-2 max-w-5xl",children:u.jsx(Lw,{})}):null]})}function uO({vaultUrl:t,vaultId:a}){const r=ze(),i=pt(),o=Mr(y=>y.resetToHealthy),[c,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=fO(t)?"Try `parachute start vault` in a terminal.":null;return u.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:u.jsxs("div",{className:"mx-auto flex max-w-5xl flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[u.jsxs("div",{children:[u.jsx("p",{className:"font-medium text-red-100",children:"Vault not reachable"}),u.jsxs("p",{className:"text-xs text-red-200/80",children:["Notes can't sync until it's back online.",p?` ${p}`:""]})]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("button",{type:"button",onClick:m,disabled:c||!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:c?"Retrying…":"Retry now"}),u.jsx("button",{type:"button",onClick:()=>o(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 cO=/^(10|192\.168|172\.(1[6-9]|2\d|3[0-1]))\./;function fO(t){try{const r=new URL(t).hostname.replace(/^\[/,"").replace(/\]$/,"");return!!(r==="localhost"||r==="127.0.0.1"||r==="::1"||r.endsWith(".local")||cO.test(r))}catch{return!1}}function Ah({icon:t,title:a,description:r,action:i,className:o=""}){return u.jsxs("div",{className:`card p-10 text-center ${o}`.trim(),children:[t?u.jsx("div",{className:"mb-3 flex justify-center text-fg-dim","aria-hidden":"true",children:t}):null,u.jsx("p",{className:"text-fg-muted",children:a}),r?u.jsx("p",{className:"mt-1 text-sm text-fg-dim",children:r}):null,i?u.jsx("div",{className:"mt-4 flex justify-center",children:i}):null]})}const dO="parachute:door-descriptor";function Qw(){const t=typeof window<"u"&&window.location?window.location.origin:"";return`${dO}:${t}`}let Xt,_h=null,Rh=!1,Au=!1;const du=new Set,hO=["monthly","quarterly","yearly"];function mO(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 pO(t){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return;const a=t,r={};let i=!1;for(const o of hO){if(!(o in a))continue;const c=mO(a[o]);c&&(r[o]=c,i=!0)}return i?r:void 0}function gO(t){const a=t,{intervals:r,...i}=a,o=pO(r);return o!==void 0?{...i,intervals:o}:i}function Iw(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(x=>typeof x=="string")&&typeof r.signin_path=="string"&&r.signin_path.startsWith("/"),o=a.plans===void 0||Array.isArray(a.plans)&&a.plans.every(x=>!!x&&typeof x=="object"),c=o&&Array.isArray(a.plans)?a.plans.map(x=>gO(x)):void 0;if(i&&o)return c?{...a,plans:c}:a;const{auth:h,plans:m,...p}=a,y={...p};return i&&(y.auth=a.auth),o&&c&&(y.plans=c),y}async function yO(t){try{const a=await t("/.well-known/parachute-account");return a.ok?Iw(await a.json()):null}catch{return null}}function Kw(){try{const t=localStorage.getItem(Qw());if(t==null)return;const a=Iw(JSON.parse(t));return a===null?void 0:a}catch{return}}function vO(t){try{localStorage.setItem(Qw(),JSON.stringify(t))}catch{}}function bO(t){Rh||(Rh=!0,_h=yO(t).then(a=>{if(a!==null){const r=JSON.stringify(Xt)!==JSON.stringify(a);if(Xt=a,vO(a),r)for(const i of du)i(a)}else if(Xt===void 0){Xt=null;for(const r of du)r(null)}return Au=!0,du.clear(),Xt??null}).finally(()=>{_h=null}))}async function Gw(t=fetch.bind(globalThis),a){if(Xt===void 0){const r=Kw();r!==void 0&&(Xt=r)}return a&&!Au&&du.add(a),bO(t),Xt!==void 0?Xt:_h??null}function xO(){if(Xt===void 0){const t=Kw();t!==void 0&&(Xt=t)}return Xt??null}function wO(){Xt===null&&Au&&(Rh=!1,Au=!1)}function Dk(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 SO({hasLocalActiveVault:t,fetchImpl:a=fetch.bind(globalThis)}){let r;try{r=await Sl(a)}catch{return{kind:"front-door"}}if(!r.signed_in)return{kind:"front-door"};r.email&&xx(r.email),r.password_change_required&&Zt.getState().markGate("force_change_password");try{const i=await m0(r.csrf,a);Sx(i.token,r.email??r.username??null)}catch(i){if(EO(i))return{kind:"signed-in",email:r.email,username:r.username,vaults:[]}}try{const{vaults:i}=await g0(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 EO(t){return t instanceof wl?t.status===403&&t.message==="force_change_password"?(Zt.getState().markGate("force_change_password"),!0):t.status===423?(Zt.getState().markGate("admin_locked"),!0):!1:!1}function TO(t,a){var r;if(!(a instanceof Error))return t<2;if(xm(a)||a instanceof Qa)return!1;if(a instanceof ea){const i=ne.getState().activeVaultId;return(i?(r=Mr.getState().byVault[i])==null?void 0:r.state:void 0)==="down"?!1:t<1}return t<2}function jO({children:t}){const[a]=b.useState(()=>new wA({defaultOptions:{queries:{retry:TO,refetchOnWindowFocus:!1,staleTime:1e4}}}));return u.jsx(SA,{client:a,children:t})}const NO=[/^\/api\//,/^\/oauth\/(?!callback)/,/^\/\.well-known\//,/^\/signup/,/^\/login/,/^\/logout/,/^\/auth\//,/^\/console/,/^\/admin/,/^\/account\//,/^\/billing/,/^\/unsubscribe/,/^\/health/,/^\/vault\//,/^\/u\//];function AO(t){return NO.some(a=>a.test(t))}function Js({size:t=24,className:a}){return u.jsxs("svg",{width:t,height:t,viewBox:"0 0 64 64","aria-hidden":"true",className:a,children:[u.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)"}),u.jsx("path",{d:"M8 30 Q32 2 56 30",fill:"none",stroke:"var(--color-accent)",strokeWidth:"1.4"}),u.jsx("line",{x1:"8",y1:"30",x2:"30",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),u.jsx("line",{x1:"22",y1:"30",x2:"30",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),u.jsx("line",{x1:"42",y1:"30",x2:"34",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),u.jsx("line",{x1:"56",y1:"30",x2:"34",y2:"52",stroke:"var(--color-fg-muted)",strokeWidth:"1.3"}),u.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 _O({size:t=22}){return u.jsxs(Ne,{to:"/",className:"focus-ring inline-flex items-center gap-2 rounded-lg font-round font-bold text-fg hover:text-accent",children:[u.jsx(Js,{size:t}),u.jsx("span",{children:"Parachute"})]})}const Yw="/welcome";function Bd({signedIn:t,netError:a,onRetry:r}={}){return t?u.jsx(zO,{email:t.email,username:t.username,vaults:t.vaults}):a?u.jsx(VO,{message:a,onRetry:r}):u.jsx(DO,{})}function jl({children:t}){return u.jsxs("div",{className:"relative flex min-h-[calc(100dvh-4rem)] flex-col",children:[u.jsx("div",{className:"flex items-center px-6 pt-6 sm:px-10",children:u.jsx(_O,{})}),u.jsx("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-10 text-center",children:u.jsx("div",{className:"mx-auto w-full max-w-md",children:t})})]})}function Pw(){return u.jsx("div",{className:"mt-8 border-t border-border pt-6",children:u.jsxs("p",{className:"font-round text-sm text-fg-muted",children:["Self-hosting?"," ",u.jsx(Ne,{to:"/add",className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Connect your own vault →"})," ",u.jsx("span",{className:"text-fg-dim",children:"(your notes stay on your server)"})]})})}function RO(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 CO(t){var i;if(!t||t.length===0)return null;let a=null,r=null;for(const o of t){const c=(i=o.intervals)==null?void 0:i.yearly;c!=null&&c.available&&typeof c.price=="number"&&c.price>0&&(a=a===null?c.price:Math.min(a,c.price)),typeof o.price_month=="number"&&o.price_month>0&&(r=r===null?o.price_month:Math.min(r,o.price_month))}return a!==null?`Plans from $${a} a year.`:r!==null?`Plans from $${r} a month.`:null}const MO="Three months";function OO(t){const a=typeof t=="string"?t.trim():"";return`${a&&a.length<=40?a:MO} free, no card.`}function DO(){const[t,a]=b.useState(()=>xO());b.useEffect(()=>{let i=!0;return wO(),Gw(void 0,o=>{i&&a(o)}).then(o=>{i&&a(o)}),()=>{i=!1}},[]);const r=RO(t);return r==="hub"&&(t!=null&&t.auth)?u.jsx(UO,{auth:t.auth,signupPath:t.signup_path}):r==="cloud"?u.jsx(LO,{plans:t==null?void 0:t.plans,trialLengthLabel:t==null?void 0:t.trial_length_label}):u.jsx(kO,{})}function kO(){return u.jsxs(jl,{children:[u.jsx(Js,{size:60,className:"mx-auto mb-6 drop-in"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),u.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",u.jsx("span",{className:"accent-word",children:"land."})]}),u.jsx("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:"Sign in to your parachute."}),u.jsx(Ne,{to:"/add",className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Sign in →"})]})}function LO({plans:t,trialLengthLabel:a}){const r=Cr(),[i]=Yh(),o=i.get("link")==="expired",[c,h]=b.useState(VE()??""),[m,p]=b.useState(!1),[y,x]=b.useState(null),v=/.+@.+\..+/.test(c.trim()),w=CO(t),T=OO(a);async function E(_){if(_.preventDefault(),!(!v||m)){p(!0),x(null);try{const R=await Sl();await zN(c.trim(),R.csrf,Yw),xx(c.trim()),r("/check-email")}catch(R){p(!1),x(R instanceof Error?`Couldn't send the link: ${R.message}`:"Couldn't send the link. Please try again.")}}}return u.jsxs(jl,{children:[u.jsx(Js,{size:60,className:"mx-auto mb-6 drop-in"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),u.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",u.jsx("span",{className:"accent-word",children:"land."})]}),o?u.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 ",u.jsx("span",{className:"font-serif italic",children:"expired."})," No harm done — we'll send a fresh one."]}):null,u.jsx("form",{onSubmit:E,className:"mx-auto w-full max-w-sm",children:u.jsxs("div",{className:"composer flex flex-col gap-3 p-4 text-left",children:[u.jsx("label",{htmlFor:"email",className:"eyebrow",children:"Sign in or create your account"}),u.jsx("input",{id:"email",type:"email",inputMode:"email",autoComplete:"email",autoFocus:!0,value:c,onChange:_=>h(_.target.value),placeholder:"you@example.com","aria-label":"Email address",className:"input input-on-bg"}),u.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"})]})}),u.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."}),u.jsxs("p",{className:"mx-auto mt-3 max-w-sm font-round text-xs text-fg-dim",children:[T,w?` ${w}`:""]}),y?u.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,u.jsx(Pw,{})]})}function UO({auth:t,signupPath:a}){const r=Cr(),[i,o]=b.useState(!1),c=typeof window<"u"?window.location.host:"";async function h(){if(!i){o(!0);try{const p=await vw(window.location.origin)??window.location.origin,{authorizeUrl:y}=await wm(p);window.location.assign(y)}catch{o(!1),r("/add")}}}function m(){const p=encodeURIComponent(Dx(Yw));window.location.assign(`${t.signin_path}?next=${p}`)}return u.jsxs(jl,{children:[u.jsx(Js,{size:60,className:"mx-auto mb-6 drop-in"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Welcome"}),u.jsxs("h1",{className:"hero-title mb-4",children:["A soft place for your thoughts to ",u.jsx("span",{className:"accent-word",children:"land."})]}),u.jsxs("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:["Sign in to ",u.jsx("span",{className:"font-semibold text-fg",children:c||"your parachute"}),"."]}),u.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 →"}),u.jsx("p",{className:"mx-auto mt-6 max-w-sm font-round text-sm text-fg-muted",children:u.jsx("button",{type:"button",onClick:m,className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Manage this parachute →"})}),a?u.jsxs("p",{className:"mx-auto mt-3 max-w-sm font-round text-sm text-fg-muted",children:["New here?"," ",u.jsx("a",{href:a,className:"font-semibold hover:underline",style:{color:"var(--color-sky)"},children:"Create your account →"})]}):u.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."}),u.jsx(Pw,{})]})}function zO({email:t,username:a,vaults:r}){const i=Cr(),[o,c]=b.useState(!1),h=r.length===1?r[0]:null;async function m(){if(!(!h||o)){c(!0);try{await Vu(h.name),Nm(h.name),i("/")}catch{i("/welcome",{replace:!0})}}}async function p(){try{const y=await Sl();await $N(y.csrf)}finally{Lh(),i("/",{replace:!0}),window.location.assign("/")}}return u.jsxs(jl,{children:[u.jsx(Js,{size:56,className:"mx-auto mb-6"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Signed in"}),u.jsxs("h1",{className:"hero-title mb-6",style:{fontSize:"clamp(1.8rem, 4vw, 2.4rem)"},children:["You're already signed in as"," ",u.jsx("span",{className:"accent-word",children:t??a??"your account"}),"."]}),u.jsxs("div",{className:"flex flex-col items-center gap-4",children:[h?u.jsx("button",{type:"button",onClick:m,disabled:o,className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:o?`Opening ${h.name}…`:`Open ${h.name} →`}):u.jsx(Ne,{to:"/welcome",className:"btn btn-primary btn-lg justify-center rounded-full px-6 shadow-soft",children:"Choose a vault →"}),u.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 VO({message:t,onRetry:a}){return u.jsxs(jl,{children:[u.jsx(Js,{size:56,className:"mx-auto mb-6"}),u.jsx("p",{className:"eyebrow eyebrow-accent mb-3",children:"Almost there"}),u.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 ",u.jsx("span",{className:"accent-word",children:"vaults."})]}),u.jsx("p",{className:"mx-auto mb-6 max-w-sm text-fg-muted",children:t}),u.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 BO({tags:t,input:a,onInputChange:r,onAdd:i,onRemove:o}){return u.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-sm",children:[u.jsx("span",{className:"shrink-0 text-xs uppercase tracking-wider text-fg-dim",children:"Tags"}),t.map(c=>u.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:[u.jsx("span",{className:"min-w-0 break-all",children:c}),u.jsx("button",{type:"button",onClick:()=>o(c),"aria-label":`Remove tag ${c}`,className:"text-fg-dim hover:text-red-400",children:"×"})]},c)),u.jsx("input",{type:"text",value:a,onChange:c=>r(c.target.value),onKeyDown:c=>{c.key==="Enter"||c.key===","?(c.preventDefault(),i(a)):c.key==="Backspace"&&a===""&&t.length>0&&o(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 _u(t){return t.trim().replace(/^#/,"")}function HO({capability:t,className:a="mb-4 text-xs text-fg-dim"}){const r=typeof(t==null?void 0:t.minutes_remaining)=="number";return u.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 qO=["audio/webm;codecs=opus","audio/mp4","audio/ogg;codecs=opus"],$O=32e3;function kk(t=qO){if(typeof MediaRecorder>"u")return null;for(const a of t)if(MediaRecorder.isTypeSupported(a))return a;return null}function QO(t){return t.startsWith("audio/webm")?"webm":t.startsWith("audio/mp4")?"m4a":t.startsWith("audio/ogg")?"ogg":t.startsWith("audio/wav")?"wav":"bin"}function Lk(t){const a=t.now??(()=>Date.now()),r=t.releaseStreamOnStop??!0,i=t.MediaRecorderCtor??MediaRecorder,o=new i(t.stream,{mimeType:t.mimeType,audioBitsPerSecond:$O}),c=[];let h="idle",m=0,p=0;o.ondataavailable=x=>{x.data&&x.data.size>0&&c.push(x.data),t.onData&&t.onData(c.reduce((v,w)=>v+w.size,0))};const y=()=>{if(r)for(const x of t.stream.getTracks())x.stop()};return{get state(){return h},get mimeType(){return t.mimeType},start(){if(h!=="idle")throw new Error(`Cannot start from ${h}`);o.start(t.dataIntervalMs),m=a(),h="recording"},pause(){h==="recording"&&(o.pause(),p+=a()-m,h="paused")},resume(){h==="paused"&&(o.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 x=new Promise(v=>{o.onstop=async()=>{const w=await KO(c);v({data:w,mimeType:t.mimeType,durationMs:p})}});return o.stop(),h="stopped",y(),x},cancel(){if(h==="recording"||h==="paused")try{o.stop()}catch{}h="stopped",c.length=0,y()}}}async function IO(t){const a=t;return typeof a.arrayBuffer=="function"?a.arrayBuffer():new Promise((r,i)=>{const o=new FileReader;o.onload=()=>r(o.result),o.onerror=()=>i(o.error??new Error("FileReader error")),o.readAsArrayBuffer(t)})}async function KO(t){if(t.length===0)return new ArrayBuffer(0);const a=await Promise.all(t.map(c=>IO(c))),r=a.reduce((c,h)=>c+h.byteLength,0),i=new Uint8Array(r);let o=0;for(const c of a)i.set(new Uint8Array(c),o),o+=c.byteLength;return i.buffer}async function Uk(){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 zk(t,a=new Date,r){const i=a.toISOString().replace(/[:.]/g,"-").replace(/Z$/,""),o=r&&r>0?`-part${r}`:"";return`memo-${i}${o}.${QO(t)}`}function $b(t=new Date){const a=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),c=String(t.getMinutes()).padStart(2,"0"),h=String(t.getSeconds()).padStart(2,"0");return`Notes/${a}/${r}-${i}/${o}-${c}-${h}`}const GO=/(?:^|\s)#([a-zA-Z][\w-]*)/g;function YO(t){const a=new Set;for(const r of t.matchAll(GO)){const i=_u(r[1]??"");i&&a.add(i)}return[...a]}function PO(t){const a=Array.from(new Set([...t.tags,...YO(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 FO(t,a,r,i,o=600){const c=b.useRef(r);c.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){f0(t,a);return}const p=window.setTimeout(()=>Zd(t,a,c.current),o);return()=>window.clearTimeout(p)},[m,i,t,a,o]),b.useEffect(()=>{if(!t||!a)return;const p=()=>{h.current&&Zd(t,a,c.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 XO={tags:[{name:"capture",description:"Notes captured directly by the user (text or voice)."}]};function ZO(t,a){const r=t??[],i=a??[];if(r.length!==i.length)return!1;for(let o=0;o<r.length;o++)if(r[o]!==i[o])return!1;return!0}function JO(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 ZO(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 WO(t){const a=await t.listTagsWithSchema(),r=new Map(a.map(h=>[h.name,h])),i=XO.tags.map(h=>JO(h,r.get(h.name))),o=i.filter(h=>h.status==="missing"),c=i.filter(h=>h.status==="misaligned");return{ok:o.length===0&&c.length===0,missing:o,misaligned:c,rows:i}}const Hd=new Set;async function e3(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 t3(t,a){if(!Hd.has(t)){Hd.add(t);try{const i=(await WO(a)).missing.map(o=>o.expected);i.length>0&&await e3(a,i)}catch(r){Hd.delete(t),typeof console<"u"&&console.warn(`[schema-ensure] failed to ensure required schema for vault ${t}:`,r)}}}const Fw="home-composer-input";function Xw({vault:t,focused:a=!1}){var ee;const r=sa(O=>O.push),i=mw(),o=ze(),{roles:c}=Xs(t.id),h=dw(),m=((ee=h.capability)==null?void 0:ee.enabled)===!1,p=b.useRef($b()),[y]=b.useState(()=>DN(t.id,eu)),[x,v]=b.useState(()=>y?{...y.body,path:y.body.path||p.current}:{content:"",path:p.current,tags:[]}),[w,T]=b.useState(!1),[E,_]=b.useState(null),[R,M]=b.useState(""),V=b.useRef(y!==null),H=b.useRef(null);b.useEffect(()=>{V.current||(v(O=>{const P=H.current?O.tags.filter(oe=>oe!==H.current):O.tags,ae=P.includes(c.captureText)?P:[...P,c.captureText];return ae===O.tags?O:{...O,tags:ae}}),H.current=c.captureText)},[c.captureText]);const k=!V.current&&(x.tags.length===0||x.tags.length===1&&x.tags[0]===c.captureText),Y=x.content.trim().length>0||!k||x.path.trim().length>0&&x.path!==p.current;FO(t.id,eu,x,Y);const $=b.useRef(x);$.current=x;const F=b.useRef(Y);F.current=Y;const G=b.useCallback(()=>{F.current&&Zd(t.id,eu,$.current)},[t.id]);b.useEffect(()=>()=>G(),[G]);const Z=b.useRef(null);b.useEffect(()=>{const O=Z.current;O&&(O.style.height="",x.content&&(O.style.height=`${O.scrollHeight}px`))},[x.content]);const le=w||x.content.length>0,de=x.content.trim().length>0&&x.path.trim().length>0&&!i.isPending,ge=O=>{const P=_u(O);!P||x.tags.includes(P)||(V.current=!0,v(ae=>({...ae,tags:[...ae.tags,P]})),M(""))},we=O=>{V.current=!0,v(P=>({...P,tags:P.tags.filter(ae=>ae!==O)}))},se=()=>{de&&(o&&t3(t.id,o),_(null),i.mutate(PO({content:x.content,path:x.path,tags:x.tags}),{onSuccess:()=>{var O;f0(t.id,eu),p.current=$b(),V.current=!1,H.current=c.captureText,M(""),v({content:"",path:p.current,tags:[c.captureText]}),(O=Z.current)==null||O.blur(),T(!1),r(`Saved to ${t.name}`,"success")},onError:O=>{_(O instanceof qu?"Session expired. Reconnect to save.":O instanceof Error?O.message:"Couldn't save — try again.")}}))};return u.jsxs("form",{"aria-label":"Write a note",className:`composer mb-6 px-5 py-4 ${a?"composer-focus":""}`,onSubmit:O=>{O.preventDefault(),se()},onFocus:()=>T(!0),onBlur:O=>{G(),O.currentTarget.contains(O.relatedTarget)||T(!1)},children:[u.jsx("textarea",{id:Fw,ref:Z,rows:1,value:x.content,onChange:O=>v(P=>({...P,content:O.target.value})),onKeyDown:O=>{(O.metaKey||O.ctrlKey)&&O.key==="Enter"&&(O.preventDefault(),se())},"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?u.jsx("div",{className:"mt-2",children:u.jsx(BO,{tags:x.tags,input:R,onInputChange:M,onAdd:ge,onRemove:we})}):null,u.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[le?u.jsx(Ne,{to:"/new",onClick:G,className:"focus-ring rounded text-fg-dim text-xs hover:text-accent",children:"Open full editor →"}):u.jsxs("span",{className:"font-round text-fg-dim text-xs",children:["Autosaves to ",t.name]}),u.jsxs("div",{className:"flex items-center gap-2",children:[le?u.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:u.jsx(Ne,{to:"/new?voice=1",onClick:G,"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:u.jsx("span",{"aria-hidden":"true",children:"🎙"})})]})]}),m&&le?u.jsx(HO,{capability:h.capability,className:"mt-2 text-xs text-fg-dim"}):null,E?u.jsx("p",{role:"alert",className:"mt-2 text-danger text-xs",children:E}):null]})}function Zw(){const t=Ku(),a=Ie(),r=t.find(i=>i.id==="notes");return!r||r.items.length===0?null:u.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 o=i.match(a);return u.jsx(Ne,{to:i.to,"data-nav-item":i.id,"aria-current":o?"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 ${o?"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 n3={mcp:"MCP",api:"API",cli:"CLI",operator:"operator"};function Qb(t){const a=n3[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 a3(t){const a=t.createdVia?`via ${Qb(t.createdVia)}`:null,r=t.lastUpdatedVia?`via ${Qb(t.lastUpdatedVia)}`:null;if(!a&&!r)return null;const i=t.createdBy??t.createdVia??null,o=t.lastUpdatedBy??t.lastUpdatedVia??null,c=o!==null&&o!==i,h=c&&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:c,raw:m}}function r3({note:t,variant:a="compact",className:r}){const i=a3(t);return i?a==="detail"?u.jsxs("div",{className:`space-y-0.5 text-xs text-fg-dim${r?` ${r}`:""}`,title:i.raw,children:[i.created?u.jsxs("p",{children:["created ",i.created]}):null,i.updated&&i.differs?u.jsxs("p",{children:["updated ",i.updated]}):null]}):u.jsx("span",{className:`shrink-0 text-xs text-fg-dim${r?` ${r}`:""}`,title:i.raw,children:i.compact}):null}function Jw({note:t,pinnedTag:a,archivedTag:r,trailing:i,footer:o}){const c=wu(t),h=!!t.path&&t.path.replace(/\.md$/i,"")!==c.text,m=t.updatedAt??t.createdAt,p=(t.tags??[]).includes(a),y=(t.tags??[]).includes(r);return u.jsxs("li",{className:y?"opacity-60 italic":void 0,children:[u.jsxs("div",{className:"note-row items-stretch","data-note-id":t.id,children:[u.jsx("span",{"aria-hidden":"true",className:"note-dot"}),u.jsxs(Ne,{to:`/n/${encodeURIComponent(t.id)}`,className:"focus-ring block min-h-11 min-w-0 flex-1 md:min-h-0",children:[u.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[u.jsxs("span",{className:"flex min-w-0 items-baseline gap-1.5",children:[p?u.jsx("span",{className:"shrink-0 text-accent","aria-label":"pinned",title:"pinned",children:"★"}):null,u.jsx("span",{className:c.kind==="timestamp"?"min-w-0 truncate text-base title-timestamp":"min-w-0 truncate text-base font-medium text-fg",children:c.text})]}),u.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[u.jsx("span",{className:"text-xs tabular-nums text-fg-dim",children:Dm(m)}),u.jsx(r3,{note:t})]})]}),h?u.jsx("p",{className:"mt-0.5 min-w-0 truncate note-id",children:t.path}):null,t.preview?u.jsx("p",{className:"mt-1 truncate text-sm text-fg-muted",children:t.preview}):null,t.tags&&t.tags.length>0?u.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:t.tags.map(x=>u.jsxs("span",{className:"chip chip-tag max-w-full break-all",children:["#",x]},x))}):null]}),i?u.jsx("div",{className:"shrink-0 self-center",children:i}):null]}),o?u.jsx("div",{className:"pl-4",children:o}):null]})}function Ww({children:t,"aria-label":a}){return u.jsx("ol",{"aria-label":a,className:"flex flex-col gap-0.5",children:t})}const s3="lens:path-tree-expanded:";function eS(t){return s3+t}function Ib(t){try{const a=localStorage.getItem(eS(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 i3(t,a){try{localStorage.setItem(eS(t),JSON.stringify([...a].sort()))}catch{}}function l3(t){const[a,r]=b.useState(()=>t?Ib(t):new Set);b.useEffect(()=>{r(t?Ib(t):new Set)},[t]);const i=b.useCallback(o=>{t&&r(c=>{const h=new Set(c);return h.has(o)?h.delete(o):h.add(o),i3(t,h),h})},[t]);return{expanded:a,toggle:i}}function o3(t,a){return{name:t,fullPath:a,count:0,children:[],childMap:new Map}}function tS(t){const a=t.split("/").filter(r=>r.length>0);return a.length<=1?[]:a.slice(0,-1)}function u3(t){const a=new Map;for(const i of t){if(!i)continue;const o=tS(i);if(o.length===0)continue;let c=a,h="";for(const m of o){h=h?`${h}/${m}`:m;let p=c.get(m);p||(p=o3(m,h),c.set(m,p)),p.count+=1,c=p.childMap}}const r=i=>i.map(o=>({name:o.name,fullPath:o.fullPath,count:o.count,children:r([...o.childMap.values()])})).sort((o,c)=>o.name.localeCompare(c.name));return r([...a.values()])}const c3=5,f3=20;function d3(t){const a=new Set;let r=0;for(const i of t){if(!i)continue;const o=tS(i);if(o.length!==0&&(r+=1,a.add(o[0]),a.size>=c3||r>=f3))return!0}return!1}function h3({paths:t,vaultId:a,currentPrefix:r,onSelect:i}){const o=b.useMemo(()=>u3(t),[t]),{expanded:c,toggle:h}=l3(a),m=b.useMemo(()=>m3(r),[r]);return o.length===0?u.jsxs("aside",{"aria-label":"Path tree",children:[u.jsx("h2",{className:"mb-2 text-xs uppercase tracking-wider text-fg-dim",children:"Folders"}),u.jsx("p",{className:"text-xs text-fg-dim",children:"No folders yet."})]}):u.jsxs("aside",{"aria-label":"Path tree",className:"md:sticky md:top-6 md:self-start",children:[u.jsxs("div",{className:"mb-2 flex items-baseline justify-between",children:[u.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"Folders"}),r?u.jsx("button",{type:"button",onClick:()=>i(""),className:"text-xs text-fg-dim hover:text-accent",children:"Clear"}):null]}),u.jsx("ul",{className:"space-y-0.5",children:o.map(p=>u.jsx(nS,{node:p,depth:0,expanded:c,forcedOpen:m,currentPrefix:r,onToggle:h,onSelect:i},p.fullPath))})]})}function nS({node:t,depth:a,expanded:r,forcedOpen:i,currentPrefix:o,onToggle:c,onSelect:h}){const m=t.children.length>0,p=r.has(t.fullPath)||i.has(t.fullPath),y=o===t.fullPath;return u.jsxs("li",{children:[u.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?u.jsx("button",{type:"button",onClick:()=>c(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:u.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:p?"▾":"▸"})}):u.jsx("span",{"aria-hidden":"true",className:"inline-block h-4 w-4"}),u.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:[u.jsx("span",{className:"truncate",children:t.name}),u.jsx("span",{className:"text-xs text-fg-dim",children:t.count})]})]}),m&&p?u.jsx("ul",{className:"space-y-0.5",children:t.children.map(x=>u.jsx(nS,{node:x,depth:a+1,expanded:r,forcedOpen:i,currentPrefix:o,onToggle:c,onSelect:h},x.fullPath))}):null]})}function m3(t){const a=new Set;if(!t)return a;const r=t.split("/").filter(o=>o.length>0);let i="";for(const o of r)i=i?`${i}/${o}`:o,a.add(i);return a}function ul(t){return t<10?`0${t}`:String(t)}function Yu(t=new Date){return`${t.getFullYear()}-${ul(t.getMonth()+1)}-${ul(t.getDate())}`}function aS(t){if(!t)return null;const a=new Date(t);return Number.isNaN(a.getTime())?null:Yu(a)}function cl(t){if(!t||!/^\d{4}-\d{2}-\d{2}$/.test(t))return null;const[a,r,i]=t.split("-").map(Number),o=new Date(a,r-1,i);return Number.isNaN(o.getTime())?null:o}function rS(t,a){const r=cl(t);return r?(r.setDate(r.getDate()+a),`${r.getFullYear()}-${ul(r.getMonth()+1)}-${ul(r.getDate())}`):t}function p3(t){var a;return((a=cl(t))==null?void 0:a.toISOString())??null}function Vk(t=new Date){return`${t.getFullYear()}-${ul(t.getMonth()+1)}`}function Bk(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 Hk(t,a,r){const i=t*12+(a-1)+r;return{year:Math.floor(i/12),month:i%12+1}}function qk(t,a){const i=new Date(t,a-1,1).getDay(),o=new Date(t,a-1,1-i),c=[];for(let h=0;h<42;h++)c.push(new Date(o.getFullYear(),o.getMonth(),o.getDate()+h));return c}function $k(t,a=new Date){var h;const r=((h=t.match(/^\d{4}-\d{2}-\d{2}/))==null?void 0:h[0])??null,i=cl(r);if(!i)return t;const o=cl(Yu(a));if(!o)return t;const c=Math.round((i.getTime()-o.getTime())/864e5);return c===0?"Today":c===-1?"Yesterday":c===1?"Tomorrow":i.toLocaleDateString(void 0,i.getFullYear()===a.getFullYear()?{month:"short",day:"numeric"}:{month:"short",day:"numeric",year:"numeric"})}function g3(t){const a=cl(t);return a?a.toLocaleDateString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"}):t}function Qk(t,a){return new Date(t,a-1,1).toLocaleDateString(void 0,{year:"numeric",month:"long"})}function y3(t){const a=new Map;for(const i of t){const o=aS(i.updatedAt??i.createdAt);if(!o)continue;const c=a.get(o);c?c.push(i):a.set(o,[i])}const r=i=>i.updatedAt??i.createdAt;return Array.from(a.entries()).sort(([i],[o])=>i<o?1:i>o?-1:0).map(([i,o])=>({key:i,notes:o.sort((c,h)=>r(c)<r(h)?1:r(c)>r(h)?-1:0)}))}function v3(t){const a=Yu();return t===a?"Today":t===rS(a,-1)?"Yesterday":g3(t)}function km({children:t}){return u.jsxs("h2",{className:"eyebrow mb-2 flex items-center gap-3",children:[u.jsx("span",{className:"shrink-0",children:t}),u.jsx("span",{"aria-hidden":"true",className:"h-px flex-1 bg-border"})]})}function b3({notes:t}){const a=ne(o=>o.getActiveVault()),{roles:r}=Xs((a==null?void 0:a.id)??null),i=b.useMemo(()=>y3(t),[t]);return u.jsx("div",{className:"space-y-8",children:i.map(o=>u.jsxs("section",{children:[u.jsx(km,{children:u.jsx(Ne,{to:`/today?date=${o.key}`,className:"hover:text-accent",children:v3(o.key)})}),u.jsx(Ww,{children:o.notes.map(c=>u.jsx(Jw,{note:c,pinnedTag:r.pinned,archivedTag:r.archived},c.id))})]},o.key))})}const Lm="application/x-parachute-note";function sS(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(pointer: fine)").matches}function x3(t,a){t.setData(Lm,a),t.effectAllowed="move"}function ru(t){return t?Array.from(t.types??[]).includes(Lm):!1}function w3(t){if(!t)return null;const a=t.getData(Lm);return a===""?null:a}function Ik(t){const[a]=b.useState(sS),r=b.useRef(!1),i=b.useCallback(h=>{h.dataTransfer&&(x3(h.dataTransfer,t),r.current=!0)},[t]),o=b.useCallback(()=>{window.setTimeout(()=>{r.current=!1},0)},[]),c=b.useCallback(h=>{r.current&&(h.preventDefault(),h.stopPropagation(),r.current=!1)},[]);return a?{canDrag:!0,sourceProps:{draggable:!0,onDragStart:i,onDragEnd:o,onClickCapture:c}}:{canDrag:!1,sourceProps:{}}}function Kk(t){const[a,r]=b.useState(!1),i=b.useRef(0),o=b.useCallback(p=>{ru(p.dataTransfer)&&(p.preventDefault(),i.current+=1,r(!0))},[]),c=b.useCallback(p=>{ru(p.dataTransfer)&&(p.preventDefault(),p.dataTransfer&&(p.dataTransfer.dropEffect="move"))},[]),h=b.useCallback(p=>{ru(p.dataTransfer)&&(i.current=Math.max(0,i.current-1),i.current===0&&r(!1))},[]),m=b.useCallback(p=>{if(!ru(p.dataTransfer))return;p.preventDefault(),i.current=0,r(!1);const y=w3(p.dataTransfer);y&&t(y)},[t]);return{isOver:a,targetProps:{onDragEnter:o,onDragOver:c,onDragLeave:h,onDrop:m}}}function Gk(){const t=b.useRef(new Map),a=b.useCallback((i,o)=>(t.current.set(i,o),()=>{t.current.get(i)===o&&t.current.delete(i)}),[]),r=b.useCallback((i,o)=>{var c;(c=t.current.get(i))==null||c(o)},[]);return{register:a,dispatch:r}}const S3=10;function Ru(t){return Object.keys(t.fields??{}).length}function E3(t,a){const r=new Map;for(const p of t){const y=p.name.indexOf("/");if(y>0){const x=p.name.slice(0,y),v=r.get(x)??[];v.push(p),r.set(x,v)}}const i=new Set;for(const[p,y]of r)y.length>=2&&i.add(p);const o=new Map,c=[];for(const p of t){const y=p.name.indexOf("/"),x=y>0?p.name.slice(0,y):p.name;if(y>0&&i.has(x)){let w=o.get(x);w||(w={kind:"group",prefix:x,totalCount:0,children:[]},o.set(x,w)),w.children.push({...p,pinned:a.has(p.name)}),w.totalCount+=p.count??0}else if(i.has(p.name)){let w=o.get(p.name);w||(w={kind:"group",prefix:p.name,totalCount:0,children:[]},o.set(p.name,w)),w.selfTag={...p,pinned:a.has(p.name)},w.totalCount+=p.count??0}else c.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 o.values())p.children.sort((y,x)=>y.pinned!==x.pinned?y.pinned?-1:1:(x.count??0)-(y.count??0)||y.name.localeCompare(x.name));const h=[...c,...Array.from(o.values())],m=p=>{var v,w;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),x=Math.max(((w=p.selfTag)==null?void 0:w.count)??0,...p.children.map(T=>T.count??0))||0;return{pinned:y,count:x,label:p.prefix}};return h.sort((p,y)=>{const x=m(p),v=m(y);return x.pinned!==v.pinned?x.pinned?-1:1:v.count-x.count||x.label.localeCompare(v.label)}),h}function Kb(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 Gb(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 T3(t,a,r){const i=t.filter(p=>Gb(p,a)),o=t.filter(p=>!Gb(p,a)),c=o.filter(Kb),h=o.filter(p=>!Kb(p)),m=Math.max(0,r-i.length);return[...i,...[...c,...h].slice(0,m)]}function j3({tags:t,pinnedTags:a,selected:r,onToggle:i,onClear:o,isLoading:c}){const[h,m]=b.useState(""),[p,y]=b.useState(!1),x=b.useRef(null);b.useEffect(()=>{var $;sS()&&(($=x.current)==null||$.focus())},[]);const v=b.useMemo(()=>new Set(a.map($=>$.toLowerCase())),[a]),w=b.useMemo(()=>new Set(r.map($=>$.toLowerCase())),[r]),T=b.useMemo(()=>E3(t,v),[t,v]),E=b.useMemo(()=>T3(T,w,S3),[T,w]),[_,R]=b.useState(new Set),M=$=>{R(F=>{const G=new Set(F);return G.has($)?G.delete($):G.add($),G})},V=h.trim().toLowerCase(),H=b.useMemo(()=>V?t.filter($=>$.name.toLowerCase().includes(V)).sort(($,F)=>(F.count??0)-($.count??0)||$.name.localeCompare(F.name)):[],[t,V]),k=$=>{if($.key!=="Enter")return;const F=H[0];F&&($.preventDefault(),i(F.name))},Y=$=>$.kind==="leaf"?u.jsx("li",{children:u.jsx(Cu,{name:$.name,label:$.label,count:$.count,pinned:$.pinned,active:w.has($.name.toLowerCase()),fieldCount:Ru($),onToggle:()=>i($.name)})},$.name):u.jsx("li",{children:u.jsx(N3,{group:$,isOpen:_.has($.prefix),onToggleOpen:()=>M($.prefix),selectedSet:w,onToggleTag:i})},$.prefix);return u.jsxs("nav",{"aria-label":"Browse by tag",children:[u.jsxs("div",{className:"mb-2 flex items-baseline justify-between",children:[u.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:"Tags"}),r.length>0?u.jsx("button",{type:"button",onClick:o,className:"text-xs text-fg-dim hover:text-accent",children:"Clear"}):null]}),u.jsx("input",{ref:x,type:"search",value:h,onChange:$=>m($.target.value),onKeyDown:k,placeholder:"Filter tags…","aria-label":"Filter tags",className:"input mb-2 w-full text-sm"}),c?u.jsx("p",{className:"text-xs text-fg-dim",children:"Loading…"}):t.length===0?u.jsx("p",{className:"text-xs text-fg-dim",children:"No tags in this vault."}):V?H.length===0?u.jsxs("p",{className:"text-xs text-fg-dim",children:['No tags match "',h,'".']}):u.jsx("ul",{className:"max-h-[60vh] space-y-0.5 overflow-y-auto pr-1","aria-label":"Matching tags",children:H.map($=>u.jsx("li",{children:u.jsx(Cu,{name:$.name,label:$.name,count:$.count??0,pinned:v.has($.name.toLowerCase()),active:w.has($.name.toLowerCase()),fieldCount:Ru($),onToggle:()=>i($.name)})},$.name))}):u.jsxs(u.Fragment,{children:[u.jsx("ul",{className:"space-y-0.5","aria-label":"Shortlist",children:E.map(Y)}),T.length>E.length?u.jsxs("button",{type:"button",onClick:()=>y($=>!$),"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:[u.jsx("span",{"aria-hidden":"true",className:"font-mono",children:p?"▾":"▸"}),"All ",t.length," tags"]}):null,p?u.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 Cu({name:t,label:a,count:r,pinned:i,active:o,fieldCount:c,onToggle:h}){return u.jsxs("button",{type:"button",onClick:h,"aria-pressed":o,title:`#${t}`,className:`flex w-full items-center gap-1.5 rounded-lg px-2 py-1 text-left text-sm ${o?"bg-accent/15 text-accent":"text-fg-muted hover:bg-bg/60 hover:text-accent"}`,children:[i?u.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-accent",children:"★"}):null,u.jsxs("span",{className:"flex-1 truncate",children:["#",a]}),c?u.jsxs("span",{className:"shrink-0 text-xs text-fg-dim",title:`${c} schema field${c===1?"":"s"}`,children:["⊞ ",c]}):null,u.jsx("span",{className:"shrink-0 text-xs text-fg-dim",children:r})]})}function N3({group:t,isOpen:a,onToggleOpen:r,selectedSet:i,onToggleTag:o}){var y;const c=t.children.some(x=>i.has(x.name.toLowerCase())),h=t.selfTag?i.has(t.selfTag.name.toLowerCase()):!1,m=a||c||h,p=(((y=t.selfTag)==null?void 0:y.pinned)??!1)||t.children.some(x=>x.pinned);return u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center gap-1 rounded-lg px-1 py-0.5",children:[u.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:u.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:m?"▾":"▸"})}),t.selfTag?u.jsx(Cu,{name:t.selfTag.name,label:t.prefix,count:t.totalCount,pinned:t.selfTag.pinned,active:h,fieldCount:Ru(t.selfTag),onToggle:()=>o(t.selfTag.name)}):u.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?u.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-accent",children:"★"}):null,u.jsxs("span",{className:"flex-1 truncate",children:["#",t.prefix,"/"]}),u.jsx("span",{className:"shrink-0 text-xs text-fg-dim",children:t.totalCount})]})]}),m?u.jsx("ul",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:t.children.map(x=>{const v=x.name.slice(t.prefix.length+1)||x.name;return u.jsx("li",{children:u.jsx(Cu,{name:x.name,label:v,count:x.count??0,pinned:x.pinned,active:i.has(x.name.toLowerCase()),fieldCount:Ru(x),onToggle:()=>o(x.name)})},x.name)})}):null]})}function iS({className:t=""}){return u.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 su({label:t,onRemove:a}){return u.jsxs("span",{className:"chip chip-tag-active",children:[t,u.jsx("button",{type:"button",onClick:a,"aria-label":`Remove refinement ${t}`,className:"focus-ring ml-1 rounded-full",children:"×"})]})}function Ch({className:t="",width:a,height:r}){const i={};return a!==void 0&&(i.width=a),r!==void 0&&(i.height=r),u.jsx("div",{className:`skeleton ${t}`.trim(),style:Object.keys(i).length?i:void 0,"aria-hidden":"true"})}function Yb(t,a){const[r,i]=b.useState(t);return b.useEffect(()=>{const o=setTimeout(()=>i(t),a);return()=>clearTimeout(o)},[t,a]),r}function A3(t){const[a,r]=b.useState(!1),[i,o]=b.useState(t);t!==i&&(o(t),r(!1));const c=b.useCallback(()=>r(!0),[]);return{dismissed:a,dismiss:c}}const _3=["auto","always","never"],fl="auto",R3="lens:path-tree:";function lS(t){return R3+t}function C3(t){return typeof t=="string"&&_3.includes(t)?t:fl}function Pb(t){try{const a=localStorage.getItem(lS(t));if(!a)return fl;const r=JSON.parse(a);return C3(r.mode)}catch{return fl}}function M3(t,a){try{localStorage.setItem(lS(t),JSON.stringify({mode:a}))}catch{}}function O3(t){const[a,r]=b.useState(()=>t?Pb(t):fl);b.useEffect(()=>{r(t?Pb(t):fl)},[t]);const i=b.useCallback(o=>{t&&(M3(t,o),r(o))},[t]);return{mode:a,setMode:i}}function Fb(t){var r,i;const a=new URLSearchParams;(r=t.search)!=null&&r.trim()&&a.set("search",t.search.trim());for(const o of t.tags??[])a.append("tag",o);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 Xb(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 D3(t){var a,r;return!!((a=t.search)!=null&&a.trim()||t.tags&&t.tags.length>0||(r=t.pathPrefix)!=null&&r.trim())}function k3(t,a){var i,o;const r={};return(i=t.search)!=null&&i.trim()&&(r.search=t.search.trim()),t.tags&&t.tags.length>0&&(r.tag=[...t.tags]),t.tags&&t.tags.length>1&&t.tagMatch&&(r.tag_match=t.tagMatch),(o=t.pathPrefix)!=null&&o.trim()&&(r.path_prefix=t.pathPrefix.trim()),t.sort&&(r.sort=t.sort),t.showArchived||(r.exclude_tags=[a]),r}const L3=["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 U3(t){return L3.find(a=>a===t)}function Mh({preset:t,lens:a}={}){return a==="recent"?u.jsx(B3,{}):u.jsx(z3,{preset:t})}function uS({name:t}){return u.jsxs("header",{className:"mb-6",children:[u.jsx("h1",{className:"page-title",style:{fontSize:"clamp(2rem, 4vw, 2.6rem)"},children:t}),u.jsx("p",{className:"mt-1.5 text-fg-muted",children:"Everything here is yours. Open format. Export anytime."})]})}function z3({preset:t}){var Cl,ei;const a=ne(re=>re.getActiveVault()),{roles:r}=Xs((a==null?void 0:a.id)??null),{pinnedTags:i}=RR((a==null?void 0:a.id)??null),[o,c]=Yh(),h=t??U3(o.get("view")),m=b.useMemo(()=>Xb(o),[o]),[p,y]=b.useState(m.search??""),[x,v]=b.useState(m.pathPrefix??""),[w,T]=b.useState(m.tags??[]),[E,_]=b.useState(m.tagMatch??"any"),[R,M]=b.useState(m.sort??"desc"),[V,H]=b.useState(m.showArchived??!1),[k,Y]=b.useState(0),$=b.useMemo(()=>o.toString(),[o]);b.useEffect(()=>{const re=Xb(new URLSearchParams($));y(re.search??""),v(re.pathPrefix??""),T(re.tags??[]),_(re.tagMatch??"any"),M(re.sort??"desc"),H(re.showArchived??!1)},[$]);const F=Yb(p,300),G=Yb(x,300);b.useEffect(()=>{if(h)return;const re={search:F,tags:w,tagMatch:E,pathPrefix:G,sort:R,showArchived:V};Fb(re).toString()!==$&&c(Fb(re),{replace:!0})},[h,F,G,w,E,R,V]);const Z=h==="pinned"||h==="archived"?h:null,{def:le}=aC(Z,r),de=b.useMemo(()=>{if(!Z)return w;const re=le?Sw(le.query):[];return Array.from(new Set([...re,...w]))},[Z,le,w]),ge=Z?"all":E;b.useEffect(()=>{Y(0)},[F,G,de,ge,R,V]);const we=b.useMemo(()=>({...ow,search:F,pathPrefix:G,tags:de,tagMatch:ge,sort:R,offset:k,limit:mr+1,...h==="untagged"?{hasTags:!1}:{},...h==="orphaned"?{hasLinks:!1}:{}}),[F,G,de,ge,R,k,h]),se=hw(we,{live:!1}),ee=cR(),O=Ew(r.view),P=mw(),ae=pt(),oe=sa(re=>re.push),[ye,j]=b.useState(!1),[q,X]=b.useState(!1);b.useEffect(()=>{if(!q)return;const re=at=>{at.key==="Escape"&&X(!1)};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[q]);const{mode:W}=O3((a==null?void 0:a.id)??null),[me,Se]=b.useState(!1),Me=!h&&W!=="never",ft=Me&&me,Ge=oR(ft),oa=b.useMemo(()=>(Ge.data??[]).map(re=>re.path),[Ge.data]),Or=ft&&(W==="always"||W==="auto"&&d3(oa)),Ga=b.useMemo(()=>({search:F,tags:w,tagMatch:E,pathPrefix:G,sort:R,showArchived:V}),[F,G,w,E,R,V]),Nl=b.useCallback(async re=>{try{const at=await P.mutateAsync({content:"",path:_m(re),tags:[r.view],metadata:{kind:"list",query:JSON.stringify(k3(Ga,r.archived))}});ae.setQueriesData({queryKey:["viewList",a==null?void 0:a.id]},Ht=>[...(Ht??[]).filter(gt=>gt.id!==at.id),at]),ae.invalidateQueries({queryKey:["viewList",a==null?void 0:a.id]}),oe(`Saved view "${re}".`,"success"),j(!1)}catch(at){oe(`Could not save view: ${at.message}`,"error")}},[P,Ga,r.view,r.archived,ae,a==null?void 0:a.id,oe]),Cn=b.useMemo(()=>(O.data??[]).map(re=>Am(re).title),[O.data]),Bt=b.useMemo(()=>{if(!se.data)return se.data;let re=se.data.slice(0,mr);if(!h&&!V&&(re=re.filter(at=>!(at.tags??[]).includes(r.archived))),!h){const at=r.pinned;re=[...re].sort((Ht,gt)=>{const wn=(Ht.tags??[]).includes(at)?0:1,jt=(gt.tags??[]).includes(at)?0:1;return wn-jt})}return re},[se.data,h,V,r.archived,r.pinned]);if(!a)return u.jsx(dn,{to:"/",replace:!0});const Dr=oS[h??"all"],Pu=k+1,Al=k+((Bt==null?void 0:Bt.length)??0),kr=k>0,Lr=((Cl=se.data)==null?void 0:Cl.length)??0,Ya=Lr>mr,_l=Ya?null:k+Lr,Fu=_l!==null?` of ${_l}`:` of ${k+mr}+`,St=D3(Ga),Xu=(w.length>0?1:0)+(x.trim()?1:0)+(V?1:0)+(R!=="desc"?1:0),Ws=!h&&!St&&Xu===0&&!se.isPending&&(((ei=se.data)==null?void 0:ei.length)??0)===0&&k===0,Rl=!Ws,Ur=kr||Ya||((Bt==null?void 0:Bt.length)??0)>0;return u.jsxs("div",{className:"page-surface",children:[u.jsx(uS,{name:a.name}),u.jsx(Zw,{}),h?null:u.jsx(Xw,{vault:a,focused:!1},a.id),u.jsxs("div",{className:"mb-6",children:[u.jsxs("div",{"data-notes-chrome":!0,className:"flex items-center gap-3",children:[u.jsx("input",{type:"search",placeholder:"Search…",value:p,onChange:re=>y(re.target.value),className:"input min-w-0 flex-1","aria-label":"Search notes"}),Rl?u.jsxs("div",{className:"relative",children:[u.jsxs("button",{type:"button",onClick:()=>X(re=>!re),"aria-expanded":q,"aria-controls":"notes-filters",className:"btn btn-secondary btn-touch shrink-0",children:["Filters",u.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs",children:q?"▴":"▾"})]}),q?u.jsxs(u.Fragment,{children:[u.jsx("button",{type:"button","aria-hidden":"true",tabIndex:-1,onClick:()=>X(!1),className:"enter-fade fixed inset-0 z-30 cursor-default bg-black/40 sm:bg-transparent"}),u.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:u.jsxs("div",{className:"space-y-5",children:[u.jsxs("div",{children:[u.jsx("h2",{className:"eyebrow mb-3",children:"Refine"}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("button",{type:"button",onClick:()=>M(re=>re==="desc"?"asc":"desc"),className:"focus-ring block text-fg-muted text-sm hover:text-accent","aria-label":"Toggle sort direction",children:["Sort: ",R==="desc"?"newest":"oldest"," first"]}),h?null:u.jsxs("label",{className:"flex items-center gap-1.5 text-fg-muted text-sm hover:text-accent",children:[u.jsx("input",{type:"checkbox",checked:V,onChange:re=>H(re.target.checked)}),"Show archived"]}),u.jsx("input",{type:"text",placeholder:"Title starts with…",value:x,onChange:re=>v(re.target.value),className:"input w-full font-mono","aria-label":"Filter by path prefix"}),u.jsx(P3,{active:h})]})]}),h!=="untagged"?u.jsxs("div",{children:[u.jsx(j3,{tags:ee.data??[],pinnedTags:i,selected:w,onToggle:re=>T(at=>at.includes(re)?at.filter(Ht=>Ht!==re):[...at,re]),onClear:()=>T([]),isLoading:ee.isPending}),w.length>1?u.jsxs("fieldset",{className:"mt-3 flex items-center gap-3 text-xs",children:[u.jsx("legend",{className:"sr-only",children:"Match mode"}),u.jsx("span",{className:"text-fg-dim",children:"Match"}),u.jsxs("label",{className:"flex items-center gap-1.5",children:[u.jsx("input",{type:"radio",name:"tag-match",value:"any",checked:E==="any",onChange:()=>_("any")}),"Any"]}),u.jsxs("label",{className:"flex items-center gap-1.5",children:[u.jsx("input",{type:"radio",name:"tag-match",value:"all",checked:E==="all",onChange:()=>_("all")}),"All"]})]}):null]}):null,Me?u.jsxs("details",{className:"group",open:me,onToggle:re=>Se(re.currentTarget.open),children:[u.jsxs("summary",{className:"eyebrow flex cursor-pointer list-none items-center justify-between rounded-lg px-1 py-1 hover:text-accent",children:[u.jsx("span",{children:"Folders"}),u.jsx("span",{"aria-hidden":"true",className:"font-mono text-xs transition-transform group-open:rotate-90",children:"▸"})]}),u.jsx("div",{className:"mt-2",children:Or?u.jsx(h3,{paths:oa,vaultId:a.id,currentPrefix:x,onSelect:re=>v(re)}):Ge.isLoading?u.jsx("p",{className:"px-1 text-xs text-fg-dim",children:"Loading…"}):u.jsx("p",{className:"px-1 text-xs text-fg-dim",children:"Not enough folder variety to show a tree yet."})})]}):null]})})]}):null]}):null]}),u.jsx(K3,{selectedTags:w,onRemoveTag:re=>T(at=>at.filter(Ht=>Ht!==re)),tagMatch:E,onToggleTagMatch:()=>_(re=>re==="all"?"any":"all"),pathPrefix:x,onClearPathPrefix:()=>v(""),showArchived:V,onClearArchived:()=>H(!1),sort:R,onResetSort:()=>M("desc"),showSave:St,onSaveView:()=>j(!0)})]}),Ws?null:u.jsxs(km,{children:[Dr.label,u.jsxs("span",{className:"font-sans normal-case tracking-normal text-fg-muted",children:[" ","· ",Dr.hint]})]}),se.isPending?u.jsx(F3,{}):se.isError&&!se.data?u.jsx(X3,{error:se.error,retry:()=>se.refetch()}):Bt&&Bt.length>0?u.jsxs(u.Fragment,{children:[se.isError?u.jsx(iS,{}):null,u.jsx(Ww,{"aria-label":"Notes",children:Bt.map(re=>u.jsx(Jw,{note:re,pinnedTag:r.pinned,archivedTag:r.archived,trailing:h==="untagged"?u.jsx(Y3,{noteId:re.id,existing:re.tags??[],suggestions:ee.data??[]}):void 0},re.id))})]}):u.jsx(Z3,{filtering:U2(we)||!!h}),Ur?u.jsxs("div",{className:"mt-6 flex items-center justify-between text-fg-dim text-sm",children:[u.jsx("span",{children:se.data&&se.data.length>0?`Showing ${Pu}–${Al}${Fu}`:se.isFetching?"Loading…":""}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("button",{type:"button",disabled:!kr,onClick:()=>Y(re=>Math.max(0,re-mr)),className:"btn btn-secondary btn-touch",children:"Previous"}),u.jsx("button",{type:"button",disabled:!Ya,onClick:()=>Y(re=>re+mr),className:"btn btn-secondary btn-touch",children:"Next"})]})]}):null,ye?u.jsx(G3,{existingNames:Cn,isSaving:P.isPending,onCancel:()=>j(!1),onSave:Nl}):null]})}const V3=100;function B3(){var Y,$,F;const t=ne(G=>G.getActiveVault()),{dismissed:a,dismiss:r}=A3((t==null?void 0:t.id)??null),{roles:i}=Xs((t==null?void 0:t.id)??null),o=rS(Yu(),-13),c=lR({field:"updated_at",from:p3(o),excludeTag:i.archived,limit:iR}),h=t!==null&&Gs(t.clientId),m=lm({enabled:h}),p=((Y=h?im(m.data):null)==null?void 0:Y.plan)??null,y=typeof(p==null?void 0:p.trial_days_left)=="number"?p.trial_days_left:null,x=b.useMemo(()=>{if(!c.data)return;const G=Z=>Z.updatedAt??Z.createdAt;return c.data.filter(Z=>!(Z.tags??[]).includes(i.archived)).filter(Z=>(aS(G(Z))??"")>=o).sort((Z,le)=>G(Z)<G(le)?1:G(Z)>G(le)?-1:0).slice(0,V3)},[o,c.data,i.archived]);if(!t)return u.jsx(dn,{to:"/",replace:!0});const v=c.data!==void 0,w=O0(c.data),T=D0({hasUserNote:w}),E=UA(T),_=!a&&!E,R=T.filter(G=>!G.done),M=T.length-R.length,V=v&&!w&&_?"fresh":"returning",H=!c.isPending&&((($=c.data)==null?void 0:$.length)??0)===0,k=oS.recent;return u.jsxs("div",{className:"page-surface",children:[u.jsx(uS,{name:t.name}),u.jsx(Zw,{}),u.jsx(Xw,{vault:t,focused:V==="fresh"},t.id),u.jsx(H3,{daysLeft:y}),V==="fresh"?u.jsx(q3,{}):null,_&&R.length>0?u.jsx($3,{to:Wb[R[0].id].to,label:Wb[R[0].id].label,done:M,total:T.length,onDismiss:r}):null,u.jsxs("section",{"aria-label":"Recent notes",children:[H?null:u.jsxs(km,{children:[k.label,u.jsxs("span",{className:"font-sans normal-case tracking-normal text-fg-muted",children:[" ","· ",k.hint]})]}),c.isPending?u.jsx(Q3,{}):c.isError&&!c.data?u.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."}):(((F=c.data)==null?void 0:F.length)??0)===0?u.jsxs("div",{className:"rounded-xl border border-border bg-card p-8 text-center shadow-soft",children:[u.jsx("p",{className:"mb-1 font-serif text-fg text-lg",children:"A quiet, empty page."}),u.jsx("p",{className:"mb-5 text-fg-muted text-sm",children:"Anything at all can land here — a thought, a list, a memory."}),u.jsx("button",{type:"button",onClick:()=>{var G;return(G=document.getElementById(Fw))==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"})]}):((x==null?void 0:x.length)??0)===0?u.jsxs(u.Fragment,{children:[u.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."}),u.jsx(Zb,{})]}):u.jsxs(u.Fragment,{children:[c.isError?u.jsx(iS,{}):null,u.jsx(b3,{notes:x??[]}),u.jsx(Zb,{})]})]}),u.jsx(I3,{clientId:t.clientId,trialDaysLeft:y})]})}function Zb(){return u.jsxs("p",{className:"mt-6 text-fg-dim text-sm",children:["Looking for older notes?"," ",u.jsx(Ne,{to:"/notes",className:"text-accent hover:underline",children:"All notes →"})]})}function H3({daysLeft:t}){return t===null||t>7?null:u.jsxs("div",{className:"nudge-sun mb-6",children:[u.jsx("span",{"aria-hidden":"true",children:"✦"}),u.jsx(Ne,{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 q3(){return u.jsxs("nav",{"aria-label":"Quick actions",className:"mb-6 grid gap-3 sm:grid-cols-2",children:[u.jsx(Jb,{to:"/connect",emoji:"⚡",title:"Connect your AI",description:"Let Claude or ChatGPT read and write your vault."}),u.jsx(Jb,{to:"/import",emoji:"↯",title:"Bring your notes over",description:"Import from Obsidian or plain markdown."})]})}function Jb({to:t,emoji:a,title:r,description:i}){return u.jsxs(Ne,{to:t,className:"focus-ring tile flex items-start gap-3 p-4",children:[u.jsx("span",{"aria-hidden":"true",className:"text-lg leading-none",children:a}),u.jsxs("span",{className:"min-w-0",children:[u.jsx("span",{className:"block font-medium text-fg",children:r}),u.jsx("span",{className:"mt-0.5 block text-fg-muted text-sm",children:i})]})]})}const Wb={write:{label:"Write your first note",to:"/new"}};function $3({to:t,label:a,done:r,total:i,onDismiss:o}){return u.jsxs("div",{className:"nudge-sun mb-8",children:[u.jsx("span",{"aria-hidden":"true",children:"✦"}),u.jsxs(Ne,{to:t,className:"min-w-0 flex-1 truncate hover:underline",children:["Finish setting up — ",a]}),u.jsxs("span",{className:"font-round text-sm opacity-80",children:[r," / ",i]}),u.jsx("button",{type:"button",onClick:o,"aria-label":"Dismiss setup",className:"ml-1 text-sun-ink/70 hover:text-sun-ink",children:"✕"})]})}function Q3(){return u.jsx("div",{className:"space-y-3","aria-busy":"true",children:[0,1,2].map(t=>u.jsx(Ch,{className:"h-14 rounded-xl"},t))})}function I3({clientId:t,trialDaysLeft:a}){return Gs(t)?u.jsx("div",{className:"mt-10 border-t border-border pt-4 text-sm",children:u.jsx(Ne,{to:"/account",className:"text-fg-dim hover:text-accent",children:a!==null?u.jsxs(u.Fragment,{children:[u.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 K3({selectedTags:t,onRemoveTag:a,tagMatch:r,onToggleTagMatch:i,pathPrefix:o,onClearPathPrefix:c,showArchived:h,onClearArchived:m,sort:p,onResetSort:y,showSave:x,onSaveView:v}){const w=o.trim();return!(t.length>0||w.length>0||h||p==="asc")&&!x?null:u.jsxs("div",{"aria-label":"Active filters",className:"mt-3 flex flex-wrap items-center gap-2",children:[t.map(E=>u.jsx(su,{label:`#${E}`,onRemove:()=>a(E)},`tag-${E}`)),t.length>1?u.jsxs("button",{type:"button",onClick:i,"aria-label":`Tag match is currently "${r}" — click to switch`,className:"chip",children:["match ",r,u.jsx("span",{"aria-hidden":"true",className:"ml-1",children:"▾"})]}):null,w?u.jsx(su,{label:`title: ${w}`,onRemove:c}):null,h?u.jsx(su,{label:"archived shown",onRemove:m}):null,p==="asc"?u.jsx(su,{label:"oldest first",onRemove:y}):null,x?u.jsx("button",{type:"button",onClick:v,className:"btn btn-accent-soft btn-sm ml-auto",children:"Save as view…"}):null]})}function G3({existingNames:t,isSaving:a,onCancel:r,onSave:i}){const[o,c]=b.useState(""),h=o.trim(),m=YR(h,t.map(_m)),p=h.length>0&&!m&&!a;return u.jsx("div",{className:"dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Save view",children:u.jsxs("div",{className:"dialog-panel max-w-(--w-narrow)",children:[u.jsx("h3",{className:"mb-3 font-serif text-lg text-fg",children:"Save view"}),u.jsxs("label",{className:"block text-sm",children:[u.jsx("span",{className:"mb-1 block text-fg-muted",children:"Name"}),u.jsx("input",{type:"text",value:o,autoFocus:!0,onChange:y=>c(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?u.jsx("p",{className:"mt-2 text-xs text-danger",children:"A view with that name already exists."}):null,u.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[u.jsx("button",{type:"button",onClick:r,className:"btn btn-secondary btn-touch",children:"Cancel"}),u.jsx("button",{type:"button",onClick:()=>p&&i(h),disabled:!p,className:"btn btn-primary btn-touch",children:a?"Saving…":"Save"})]})]})})}function Y3({noteId:t,existing:a,suggestions:r}){const[i,o]=b.useState(!1),[c,h]=b.useState(""),m=b.useRef(null),p=b.useRef(null),y=yR(t),x=sa(T=>T.push);b.useEffect(()=>{var _;if(!i)return;(_=p.current)==null||_.focus();const T=R=>{var M;(M=m.current)!=null&&M.contains(R.target)||o(!1)},E=R=>{R.key==="Escape"&&o(!1)};return document.addEventListener("mousedown",T),document.addEventListener("keydown",E),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",E)}},[i]);const v=b.useMemo(()=>{const T=_u(c).toLowerCase(),E=new Set(a.map(R=>R.toLowerCase())),_=r.filter(R=>!E.has(R.name.toLowerCase()));return T?_.filter(R=>R.name.toLowerCase().includes(T)).slice(0,8):_.slice(0,8)},[c,r,a]),w=b.useCallback(async T=>{const E=_u(T);if(E)try{await y.mutateAsync({tags:{add:[E]}}),x(`Added #${E}`,"success"),h(""),o(!1)}catch(_){x(`Could not add tag: ${_.message}`,"error")}},[y,x]);return i?u.jsxs("div",{ref:m,className:"relative",children:[u.jsx("input",{ref:p,type:"text",value:c,onChange:T=>h(T.target.value),onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),w(c))},placeholder:"tag…","aria-label":"Tag name",disabled:y.isPending,className:"input w-32 px-2 py-1 text-xs"}),v.length>0?u.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=>u.jsx("li",{children:u.jsxs("button",{type:"button",onMouseDown:E=>{E.preventDefault(),w(T.name)},className:"flex w-full items-center justify-between px-2 py-1 text-left text-fg hover:bg-bg/60",children:[u.jsx("span",{className:"truncate",children:T.name}),u.jsx("span",{className:"ml-2 shrink-0 text-fg-dim",children:T.count??0})]})},T.name))}):null]}):u.jsx("button",{type:"button",onClick:()=>o(!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 u.jsxs("nav",{"aria-label":"Show only",className:"flex flex-wrap items-center gap-2",children:[u.jsx("span",{className:"text-fg-muted text-sm",children:"Show only:"}),a.map(r=>{const i=r.view===t;return u.jsx(Ne,{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 F3(){return u.jsx("ol",{className:"flex flex-col gap-0.5","aria-busy":"true",children:[0,1,2,3,4].map(t=>u.jsxs("li",{className:"rounded-xl px-3 py-3",children:[u.jsx(Ch,{className:"h-4 w-1/3"}),u.jsx(Ch,{className:"mt-2 h-3 w-2/3"})]},t))})}function X3({error:t,retry:a}){const r=t instanceof qu;return u.jsx(_w,{title:r?"Session expired":"Could not load notes",message:t.message,retry:r?void 0:a,action:r?u.jsx(Ne,{to:"/add",className:"btn btn-primary",children:"Reconnect vault"}):void 0})}function Z3({filtering:t}){return t?u.jsx(Ah,{title:"No notes match these filters."}):u.jsx(Ah,{title:"This vault has no notes yet.",action:u.jsx(Ne,{to:"/new",className:"btn btn-primary",children:"Create one"})})}const J3=b.lazy(()=>Ke(()=>import("./Account-BATMJZJa.js"),__vite__mapDeps([0,1])).then(t=>({default:t.Account}))),W3=b.lazy(()=>Ke(()=>import("./Activity-B5veG9-7.js"),[]).then(t=>({default:t.Activity}))),eD=b.lazy(()=>Ke(()=>import("./AddVault-RIYjxbdI.js"),__vite__mapDeps([2,3,4,5])).then(t=>({default:t.AddVault}))),tD=b.lazy(()=>Ke(()=>import("./AddVaultChooser-CWUDOhZF.js"),__vite__mapDeps([6,3,4])).then(t=>({default:t.AddVaultChooser}))),nD=b.lazy(()=>Ke(()=>import("./AddVaultCreate-BE3EYXef.js"),__vite__mapDeps([7,3,4])).then(t=>({default:t.AddVaultCreate}))),aD=b.lazy(()=>Ke(()=>import("./AddVaultCreate-BE3EYXef.js"),__vite__mapDeps([7,3,4])).then(t=>({default:t.AddVaultReady}))),rD=b.lazy(()=>Ke(()=>import("./Calendar-CN00mtO8.js"),[]).then(t=>({default:t.Calendar}))),sD=b.lazy(()=>Ke(()=>import("./ConnectAI-CSuI0Yoc.js"),[]).then(t=>({default:t.ConnectAI}))),iD=b.lazy(()=>Ke(()=>import("./DayView-CZZ5Upgs.js"),__vite__mapDeps([8,4])).then(t=>({default:t.DayView}))),lD=b.lazy(()=>Ke(()=>import("./Export-CrAILYQp.js"),[]).then(t=>({default:t.Export}))),oD=b.lazy(()=>Ke(()=>import("./Import-GVSfg168.js"),__vite__mapDeps([9,10])).then(t=>({default:t.Import}))),uD=b.lazy(()=>Ke(()=>import("./NoteEditor-h03ldU1x.js"),__vite__mapDeps([11,10,12,13,14,15])).then(t=>({default:t.NoteEditor}))),cD=b.lazy(()=>Ke(()=>import("./NoteNew-Cb8lPDeH.js"),__vite__mapDeps([16,10,12,13,17,18,15])).then(t=>({default:t.NoteNew}))),fD=b.lazy(()=>Ke(()=>import("./NoteView-BhyqbuWQ.js"),__vite__mapDeps([19,14,13])).then(t=>({default:t.NoteView}))),dD=b.lazy(()=>Ke(()=>import("./OAuthCallback-CuQZENVJ.js"),__vite__mapDeps([20,3,4,5])).then(t=>({default:t.OAuthCallback}))),hD=b.lazy(()=>Ke(()=>import("./Settings-BcVzNKyK.js"),__vite__mapDeps([21,17,18,15])).then(t=>({default:t.Settings}))),mD=b.lazy(()=>Ke(()=>import("./Tags-BVja3Y83.js"),__vite__mapDeps([22,23])).then(t=>({default:t.Tags}))),pD=b.lazy(()=>Ke(()=>import("./TagPage-De-8_dnv.js"),__vite__mapDeps([24,25,23])).then(t=>({default:t.TagPage}))),gD=b.lazy(()=>Ke(()=>import("./VaultGraph-EAIfK4Pi.js"),[]).then(t=>({default:t.VaultGraph}))),yD=b.lazy(()=>Ke(()=>import("./Vaults-siYPRrp1.js"),__vite__mapDeps([26,1,18])).then(t=>({default:t.Vaults}))),vD=b.lazy(()=>Ke(()=>import("./Welcome-Cpd4_G3A.js"),__vite__mapDeps([27,3,4,1])).then(t=>({default:t.Welcome}))),bD=b.lazy(()=>Ke(()=>import("./CheckEmail-CPk4SrzN.js"),__vite__mapDeps([28,3,4])).then(t=>({default:t.CheckEmail}))),xD=b.lazy(()=>Ke(()=>import("./ViewNew-KjZfga8E.js"),[]).then(t=>({default:t.ViewNew}))),wD=b.lazy(()=>Ke(()=>import("./ViewSurface-CCFPmjfV.js"),__vite__mapDeps([25,23])).then(t=>({default:t.ViewSurface})));function SD(){const t=ne(h=>h.getActiveVault()),[a]=Yh(),[r,i]=b.useState(null),o=b.useRef(!1),c=b.useCallback(()=>{o.current=!0,i(null),Gw().catch(()=>{}),SO({hasLocalActiveVault:!1}).then(i).catch(()=>i({kind:"front-door"}))},[]);if(b.useEffect(()=>{t||o.current||c()},[t,c]),a.get("add"))return u.jsx(dn,{to:`/add?${a.toString()}`,replace:!0});if(t)return u.jsx(Le,{children:u.jsx(Mh,{lens:"recent"})});if(!r)return u.jsx(Le,{resetKey:"boot-loading",children:u.jsx(ED,{})});switch(r.kind){case"home":return u.jsx(Le,{children:u.jsx(Mh,{lens:"recent"})});case"signed-in":return u.jsx(Le,{resetKey:"boot-signed-in",children:u.jsx(Bd,{signedIn:{email:r.email,username:r.username,vaults:r.vaults}})});case"net-error":return u.jsx(Le,{resetKey:"boot-net-error",children:u.jsx(Bd,{netError:r.message,onRetry:c})});default:return u.jsx(Le,{resetKey:"boot-front-door",children:u.jsx(Bd,{})})}}function ED(){return u.jsx("output",{"aria-live":"polite",className:"mx-auto flex min-h-[50dvh] items-center justify-center text-sm text-fg-dim",children:u.jsx("span",{className:"animate-pulse",children:"Loading…"})})}function TD(){return u.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 ex({suffix:t=""}){const{id:a}=rj();return a?AO(window.location.pathname)?u.jsx(dn,{to:"/",replace:!0}):u.jsx(dn,{to:`/n/${encodeURIComponent(a)}${t}`,replace:!0}):u.jsx(dn,{to:"/",replace:!0})}function tx({to:t}){const a=Ie();return u.jsx(dn,{to:`${t}${a.search}`,replace:!0})}function jD(){return u.jsx("div",{className:"page",children:u.jsx(Ah,{title:u.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:u.jsx(Ne,{to:"/notes",className:"btn btn-primary btn-touch",children:"Back to notes"})})})}function ND(){const{pathname:t}=Ie();return Nw(t)?null:u.jsx("footer",{className:"mx-auto max-w-5xl px-6 py-10 text-center text-sm text-fg-dim",children:u.jsxs("p",{children:["Part of the"," ",u.jsx("a",{href:"https://parachute.computer",className:"focus-ring text-accent hover:underline",children:"Parachute Computer"})," ","ecosystem. AGPL-3.0."]})})}function AD(){const t=ne(r=>r.activeVaultId),a=ze();return DR(t,a),null}function _D(){const t=Ie(),r=ju(i=>i.on)&&Cw(t.pathname);return u.jsxs("div",{className:"app-canvas min-h-dvh overflow-x-hidden text-fg",children:[u.jsx(ZM,{}),u.jsx(iO,{}),u.jsx(lO,{}),u.jsx(eN,{}),u.jsx(tN,{}),u.jsx(_M,{}),u.jsx(HC,{}),u.jsxs("div",{className:"md:flex",children:[r?null:u.jsx(OM,{}),r?null:u.jsx(GM,{}),u.jsxs("div",{className:`flex min-w-0 flex-1 flex-col ${r?"":"pb-16 md:pb-0"}`,children:[r?null:u.jsx(AM,{}),u.jsx(IM,{}),u.jsx("main",{className:"flex-1","data-focus-safe-area":r?"true":void 0,style:r?{paddingTop:"env(safe-area-inset-top)"}:void 0,children:u.jsx(b.Suspense,{fallback:u.jsx(TD,{}),children:u.jsxs(bj,{children:[u.jsx(je,{path:"/",element:u.jsx(SD,{})}),u.jsx(je,{path:"/check-email",element:u.jsx(Le,{children:u.jsx(bD,{})})}),u.jsx(je,{path:"/notes",element:u.jsx(Le,{children:u.jsx(Mh,{})})}),u.jsx(je,{path:"/all",element:u.jsx(tx,{to:"/notes"})}),u.jsx(je,{path:"/pinned",element:u.jsx(dn,{to:"/notes?view=pinned",replace:!0})}),u.jsx(je,{path:"/archived",element:u.jsx(dn,{to:"/notes?view=archived",replace:!0})}),u.jsx(je,{path:"/untagged",element:u.jsx(dn,{to:"/notes?view=untagged",replace:!0})}),u.jsx(je,{path:"/orphaned",element:u.jsx(dn,{to:"/notes?view=orphaned",replace:!0})}),u.jsx(je,{path:"/tags",element:u.jsx(Le,{children:u.jsx(mD,{})})}),u.jsx(je,{path:"/tags/:name",element:u.jsx(Le,{children:u.jsx(pD,{})})}),u.jsx(je,{path:"/new",element:u.jsx(Le,{children:u.jsx(cD,{})})}),u.jsx(je,{path:"/capture",element:u.jsx(dn,{to:"/new",replace:!0})}),u.jsx(je,{path:"/import",element:u.jsx(Le,{children:u.jsx(oD,{})})}),u.jsx(je,{path:"/export",element:u.jsx(Le,{children:u.jsx(lD,{})})}),u.jsx(je,{path:"/connect",element:u.jsx(Le,{children:u.jsx(sD,{})})}),u.jsx(je,{path:"/map",element:u.jsx(Le,{children:u.jsx(gD,{})})}),u.jsx(je,{path:"/graph",element:u.jsx(tx,{to:"/map"})}),u.jsx(je,{path:"/today",element:u.jsx(Le,{children:u.jsx(iD,{})})}),u.jsx(je,{path:"/calendar",element:u.jsx(Le,{children:u.jsx(rD,{})})}),u.jsx(je,{path:"/activity",element:u.jsx(Le,{children:u.jsx(W3,{})})}),u.jsx(je,{path:"/views/new",element:u.jsx(Le,{children:u.jsx(xD,{})})}),u.jsx(je,{path:"/views/:id",element:u.jsx(Le,{children:u.jsx(wD,{})})}),u.jsx(je,{path:"/n/:id",element:u.jsx(Le,{children:u.jsx(fD,{})})}),u.jsx(je,{path:"/n/:id/edit",element:u.jsx(Le,{children:u.jsx(uD,{})})}),u.jsx(je,{path:"/:id",element:u.jsx(ex,{})}),u.jsx(je,{path:"/:id/edit",element:u.jsx(ex,{suffix:"/edit"})}),u.jsx(je,{path:"/add",element:u.jsx(Le,{children:u.jsx(eD,{})})}),u.jsx(je,{path:"/add-vault",element:u.jsx(Le,{children:u.jsx(tD,{})})}),u.jsx(je,{path:"/add-vault/create",element:u.jsx(Le,{children:u.jsx(nD,{})})}),u.jsx(je,{path:"/add-vault/ready",element:u.jsx(Le,{children:u.jsx(aD,{})})}),u.jsx(je,{path:"/welcome",element:u.jsx(Le,{children:u.jsx(vD,{})})}),u.jsx(je,{path:"/oauth/callback",element:u.jsx(Le,{children:u.jsx(dD,{})})}),u.jsx(je,{path:"/vaults",element:u.jsx(Le,{children:u.jsx(yD,{})})}),u.jsx(je,{path:"/account",element:u.jsx(Le,{children:u.jsx(J3,{})})}),u.jsx(je,{path:"/settings",element:u.jsx(Le,{children:u.jsx(hD,{})})}),u.jsx(je,{path:"*",element:u.jsx(jD,{})})]})})}),r?null:u.jsx(ND,{})]})]}),r?null:u.jsx(OC,{}),r?null:u.jsx(MC,{}),r?null:u.jsx(FM,{}),r?u.jsx(qC,{}):null]})}function RD(){vR(),b.useEffect(()=>{Dw(Ts())},[]);const t=ne(a=>{var r;return((r=a.getActiveVault())==null?void 0:r.name)??null});return b.useEffect(()=>{document.title=t?`Parachute — ${t}`:"Parachute"},[t]),u.jsx(VC,{children:u.jsx(jO,{children:u.jsxs(f2,{children:[u.jsx(AD,{}),u.jsx(tM,{}),u.jsx(Ij,{basename:yl(),children:u.jsx(RC,{children:u.jsx(_D,{})})})]})})})}var qd={exports:{}},Zi={},$d={exports:{}},Qd={};/**
|
|
35
35
|
* @license React
|
|
36
36
|
* scheduler.production.js
|
|
37
37
|
*
|